Ejemplo n.º 1
0
    def start(self, screen):
        width = screen.get_width()
        height = screen.get_height()

        if self.already_loaded:
            self.name_box.set_text("")

        else:
            self.header = Label(pygame.rect.Rect(width / 2 - 200, 10, 400, 30), "Add new account", options={
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.BORDER_WIDTH: 0,
            })
            self.name_box = Textbox(pygame.rect.Rect(width/2 - 200, height/2 - 50, 400, 30), "", options={
                Options.BORDER_WIDTH: 0,
            })
            self.create_btn = Button(pygame.rect.Rect(width / 2 - 100, height / 2 + 50, 200, 30), "Create", options={
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.HOVERED_BACKGROUND: (10, 30, 45),
                Options.BORDER_WIDTH: 0,
            })
            self.back_btn = Button(pygame.rect.Rect(10, 10, 60, 40), "Back", {
                Options.BORDER_WIDTH: 0,
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.HOVERED_BACKGROUND: (10, 30, 45),
                Options.FONT: pygame.font.SysFont("Comic Sans MS", 15)
            })

            self.already_loaded = True
Ejemplo n.º 2
0
def main():
    # ---------------------------------------- Pygame general settings ---------------------------------------- #
    pg.init()

    WIDTH = 800
    SIZE = (WIDTH, WIDTH)
    screen = pg.display.set_mode(SIZE)
    main_icon = pg.image.load(os.path.join('assets', 'main_icon.png'))
    icon = pg.image.load(os.path.join('assets', 'icon.png'))
    pg.display.set_icon(icon)
    pg.display.set_caption('Path Finding Algorithm Visualizer')
    font = pg.font.Font(os.path.join('assets', 'Ubuntu-Bold.ttf'), 22)
    title_font = pg.font.Font(os.path.join('assets', 'Ubuntu-Bold.ttf'), 50)

    # ---------------------------------------- Main-Menu settings ---------------------------------------- #
    buttons = []
    buttons.append(
        Button(50, 70, 260, 50, Colors.LIGHT_GREEN, font, 'Controls'))
    buttons.append(
        Button(50, WIDTH - 200, 260, 50, Colors.LIGHT_GREEN, font,
               'Breadth First Search'))
    buttons.append(
        Button(500, WIDTH - 200, 260, 50, Colors.LIGHT_GREEN, font,
               'Depth First Search'))
    buttons.append(
        Button(50, WIDTH - 100, 260, 50, Colors.LIGHT_GREEN, font,
               'A* Search'))
    buttons.append(
        Button(500, WIDTH - 100, 260, 50, Colors.LIGHT_GREEN, font,
               'Greedy Best First Search'))
    menu = MainMenu(screen, main_icon, title_font, font, buttons)

    menu.loop()
Ejemplo n.º 3
0
    def __init__(self, text, Thash, handler=None, handler_message=None, default_choice=0,
                 x=None, y=None, width=0, height=0, icon=None, vertical_expansion=1,
                 text_prop=None, parent='osd'):

        PopupBox.__init__(self, text, handler, x, y, width, height, icon, vertical_expansion, text_prop, parent)
        self.globalHash = Thash
        self.handler_message = handler_message

        # XXX: It may be nice if we could choose between
        #      OK/CANCEL and YES/NO
        s = xmlrpclib.ServerProxy(config.RPCHOST)
        if (s.d.is_active(self.globalHash) == 1) ^ (s.d.is_hash_checking(self.globalHash) == 1):
            self.b0 = Button(_('Stop'), width=(self.width-60)/2)
        else:
            self.b0 = Button(_('Start'), width=(self.width-60)/2)
        self.b0.set_h_align(Align.NONE)
        self.add_child(self.b0)

        self.b1 = Button(_('Erase'), width=(self.width-60)/2)
        self.b1.set_h_align(Align.NONE)
        self.add_child(self.b1)

        self.b2 = Button(_('Cancel'), width=(self.width-60)/2)
        self.b2.set_h_align(Align.NONE)
        self.add_child(self.b2)

        select = 'self.b%s.toggle_selected()' % default_choice
        eval(select)
Ejemplo n.º 4
0
    def start(self, screen):
        width = screen.get_width()
        height = screen.get_height()

        if not self.already_loaded:
            self.header = Label(pygame.rect.Rect(width / 2 - 200, 10, 400, 30), "Delete an account", options={
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.BORDER_WIDTH: 0,
            })
            self.confirm_text = Label(pygame.rect.Rect(width / 2 - 200, height / 2 - 50, 400, 30), "", options={
                                          Options.BACKGROUND: (82, 173, 200),
                                          Options.FOREGROUND: (20, 61, 89),
                                          Options.BORDER_WIDTH: 0
                                      })
            self.yes_btn = Button(pygame.rect.Rect(width / 2 - 200, height / 2 + 50, 50, 40), "Yes", options={
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.HOVERED_BACKGROUND: (10, 30, 45),
                Options.BORDER_WIDTH: 0,
            })
            self.no_btn = Button(pygame.rect.Rect(width / 2 + 150, height / 2 + 50, 50, 40), "No", options={
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.HOVERED_BACKGROUND: (10, 30, 45),
                Options.BORDER_WIDTH: 0,
            })

            self.already_loaded = True

        self.confirm_text.text = f"Are you sure you want to delete account {Account.account_to_delete.name}?"
        self.confirm_text.recreate()
Ejemplo n.º 5
0
    def __init__(self):
        self.__ACTION = MenuActions.NOSET
        self.Font = fonts.ubuntu_bold_graph(25)
        self.Input = input_text.text_input()
        self.Input.set_alpha_states(0.9, 1)
        self.Input.allowLetters()
        self.Input.allowNumbers()
        self.Input.set_show_text(dat.GetWord("aqui"))
        self.Input.set_background((0, 175, 255))
        self.Input.set_border_color((0, 107, 255))
        self.Input.set_border_size(2)
        self.Input.set_margin(6)

        self.Button = Button.Button(dat.GetWord("continuar"), (100, 100, 100),
                                    (0, 0))

        self.ReturnButton = Button.Button(dat.GetWord("cancelar"),
                                          (200, 200, 200), (0, 0))

        self.Moving = None
        self.Disf = pygame.display.get_surface().get_size(
        )[0] / 2 + self.Input.surface.get_size()[0]
        self.original = self.Disf
        self.SpeedMove = 0
        Name = self.Font.render(dat.GetWord("ingresar nombre"), 1, (0, 0, 0))
        self.GlobalSize = [
            self.Input.surface.get_size()[0],
            Name.get_size()[1] + 10 + self.Input.surface.get_size()[1] + 10 +
            self.Button.surface.get_size()[1]
        ]
        self.DirMove = None
        self.Finished = False
Ejemplo n.º 6
0
    def __init__(self, game):
        GameStateScreen.__init__(self, game)
        self.stackpanel = StackPanel(game, (200, 300), 400)

        btn_single_player = Button(game,
                                   text='Single Player',
                                   action=self.btn_sp_action)
        btn_multiplayer = Button(game,
                                 text='Multiplayer',
                                 action=self.btn_mp_action,
                                 enabled=False)
        btn_settings = Button(game,
                              text='Settings',
                              action=self.btn_st_action,
                              enabled=False)
        btn_credits = Button(game, text='Credits', action=self.btn_cr_action)
        btn_quit = Button(game, text='Quit', action=self.btn_qt_action)

        self.stackpanel.add_widgets(btn_single_player, btn_multiplayer,
                                    btn_settings, btn_credits, btn_quit)

        txt = 'Welcome to Battle Snakes!'
        textbox = TextDisplay(game, text=txt, bg_color=DARK_GREEN)
        self.container = StandaloneContainer(game, (650, 300), 600, 300,
                                             textbox)
Ejemplo n.º 7
0
    def __init__(self, game):
        self.game = game
        GameStateScreen.__init__(self, game)

        self.prev_screen = None

        self.stackpanel = StackPanel(game, (200, 300),
                                     400,
                                     action=self.stackpanel_action)
        btn_classic = Button(game,
                             text='Classic Snake',
                             action=self.btn_cl_action,
                             enabled=True)
        btn_timelimit = Button(game,
                               text='Time limit',
                               action=self.btn_tl_action,
                               enabled=False)
        btn_back = Button(game, text='Back', action=self.btn_bk_action)

        self.stackpanel.add_widgets(btn_classic, btn_timelimit, btn_back)

        self.textbox = TextDisplay(game, bg_color=DARK_GREEN)

        self.container = StandaloneContainer(game, (650, 300), 600, 300,
                                             self.textbox)
        self.stackpanel_action(0)
Ejemplo n.º 8
0
 def Button(self,
            x=0,
            y=0,
            width=400,
            height=40,
            image=button_image,
            image_highlighted=button_highlighted,
            caption="Unlabeled",
            batch=None,
            group=None,
            label_group=None,
            font_name='ChunkFive Roman',
            on_click=None,
            enabled=True):
     button = Button(self,
                     x=x,
                     y=y,
                     width=width,
                     height=height,
                     image=resize_button_image(image, 400, width),
                     image_highlighted=resize_button_image(
                         image_highlighted, 400, width),
                     caption=caption,
                     batch=(batch or self.batch),
                     group=(group or self.group),
                     label_group=(label_group or self.labels_group),
                     font_name=font_name,
                     enabled=enabled)
     if on_click:
         button.push_handlers(on_click=on_click)
     return button
Ejemplo n.º 9
0
    def start(self, screen):
        width = screen.get_width()
        height = screen.get_height()

        if not self.already_loaded:
            self.confirm_text = Label(
                pygame.rect.Rect(width / 2 - 200, height / 2 - 50, 400, 30),
                "Are you sure you want to forfeit the match?", {
                    Options.BACKGROUND: (82, 173, 200),
                    Options.FOREGROUND: (20, 61, 89),
                    Options.BORDER_WIDTH: 0
                })
            self.yes_btn = Button(pygame.rect.Rect(width / 2 - 100,
                                                   height / 2 + 50, 50, 40),
                                  "Yes",
                                  options={
                                      Options.BACKGROUND: (20, 61, 89),
                                      Options.FOREGROUND: (244, 180, 26),
                                      Options.HOVERED_BACKGROUND: (10, 30, 45),
                                      Options.BORDER_WIDTH: 0,
                                  })
            self.no_btn = Button(pygame.rect.Rect(width / 2 + 50,
                                                  height / 2 + 50, 50, 40),
                                 "No",
                                 options={
                                     Options.BACKGROUND: (20, 61, 89),
                                     Options.FOREGROUND: (244, 180, 26),
                                     Options.HOVERED_BACKGROUND: (10, 30, 45),
                                     Options.BORDER_WIDTH: 0,
                                 })

        self.underlay_screen = screen.copy()
        self.already_loaded = True
Ejemplo n.º 10
0
    def __init__(self, size):
        Template.__init__(self, size)
        self.size = size
        self.block = 64
        self.dt = 0.
        self.map1 = Map(self.size, (40, 40), self.block,
                        "./tiles/Empty_tile_64p.png")
        self.map2 = Map(self.size, (40, 40), self.block,
                        "./tiles/Empty_tile_64p.png")
        self.menu = Map(self.size, (2, 14), self.block,
                        "./tiles/Empty_tile_64p.png")
        self.menu_list = []
        self.palette = self.setup_menu()
        self.palette.xy = [250, 0]
        self.clip = pg.Rect(0, 0, self.size[0], self.size[1])
        self.c_pos = self.clip.topleft
        self.current_tile = None
        self.show_foreground = -1
        self.right_m_button = False
        self.right_m_pos = None
        self.m_pos = None
        self.fill = False
        self.m_select_rect = pg.Rect(1, 1, 1, 1)
        self.button1 = Button((120, 20), (129, 1), "Menu")
        self.drop_menu = Menu((120, 160), (129, 21))
        self.drop_menu.add_buttons(4, ["Save", "Load", "Palette", "Info"])
        self.drop_menu.set_bg_color(CONCRETE)
        self.load_menu = self.setup_loadmenu()
        self.floating_text = FloatingText("no text", self.size)
        self.setup()

        self.selected_map = self.map1
Ejemplo n.º 11
0
    def start(self, screen):
        if not self.already_loaded:
            self.back_btn = Button(
                pygame.rect.Rect(10, 10, 60, 40), "Back", {
                    Options.BORDER_WIDTH: 0,
                    Options.BACKGROUND: (20, 61, 89),
                    Options.FOREGROUND: (244, 180, 26),
                    Options.HOVERED_BACKGROUND: (10, 30, 45),
                    Options.FONT: pygame.font.SysFont("Comic Sans MS", 15)
                })

            about_text = "This game was made by Ritobroto Mukherjee and\n" \
                         "Shivam Gupta (who has done absolutely nothing yet)\n" \
                         "as practice for collaboration."
            y_offset = 0
            for line in about_text.splitlines():
                self.about_labels.append(
                    Label(
                        pygame.rect.Rect(10, 200 + y_offset * 30,
                                         screen.get_width() - 10, 30), line, {
                                             Options.BACKGROUND:
                                             (82, 173, 200),
                                             Options.FOREGROUND: (20, 61, 89),
                                             Options.BORDER_WIDTH: 0
                                         }))
                y_offset += 1

            self.already_loaded = True
Ejemplo n.º 12
0
class CreateAccountScene(Scene):
    header = None
    name_box = None
    create_btn = None
    back_btn = None

    # Create the various gui elements
    def start(self, screen):
        width = screen.get_width()
        height = screen.get_height()

        if self.already_loaded:
            self.name_box.set_text("")

        else:
            self.header = Label(pygame.rect.Rect(width / 2 - 200, 10, 400, 30), "Add new account", options={
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.BORDER_WIDTH: 0,
            })
            self.name_box = Textbox(pygame.rect.Rect(width/2 - 200, height/2 - 50, 400, 30), "", options={
                Options.BORDER_WIDTH: 0,
            })
            self.create_btn = Button(pygame.rect.Rect(width / 2 - 100, height / 2 + 50, 200, 30), "Create", options={
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.HOVERED_BACKGROUND: (10, 30, 45),
                Options.BORDER_WIDTH: 0,
            })
            self.back_btn = Button(pygame.rect.Rect(10, 10, 60, 40), "Back", {
                Options.BORDER_WIDTH: 0,
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.HOVERED_BACKGROUND: (10, 30, 45),
                Options.FONT: pygame.font.SysFont("Comic Sans MS", 15)
            })

            self.already_loaded = True

    # Check the buttons and switch to corresponding scenes when clicked
    def update(self, event):
        for elt in (self.name_box, self.create_btn, self.back_btn):
            elt.update(event)

        self.create_btn.set_enabled(len(self.name_box.text) > 0)
        if self.create_btn.clicked:
            new_account = Account(self.name_box.text)
            Account.save_to_file(new_account)
            Scene.push_scene(1)

        if self.back_btn.clicked:
            Scene.push_scene(1)

    # Clear the screen and draw the gui
    def draw(self, screen):
        screen.fill((82, 173, 200))

        for elt in (self.header, self.name_box, self.create_btn, self.back_btn):
            elt.draw(screen)
Ejemplo n.º 13
0
 def __init__(self, game):
     super().__init__(game)
     self.buttons = []
     x = (game.width - 150) / 2
     self.buttons.append(
         Button("1-Player", (x, 100, 150, 40), (220, 220, 0),
                self.changeToOnePlayerState))
     self.buttons.append(
         Button("2-Player", (x, 160, 150, 40), (220, 220, 0),
                self.changeToTwoPlayerState))
Ejemplo n.º 14
0
class AboutScene(Scene):
    back_btn = None
    about_labels = []
    version_label = None

    def start(self, screen):
        if not self.already_loaded:
            self.back_btn = Button(
                pygame.rect.Rect(10, 10, 60, 40), "Back", {
                    Options.BORDER_WIDTH: 0,
                    Options.BACKGROUND: (20, 61, 89),
                    Options.FOREGROUND: (244, 180, 26),
                    Options.HOVERED_BACKGROUND: (10, 30, 45),
                    Options.FONT: pygame.font.SysFont("Comic Sans MS", 15)
                })

            text_options = {
                Options.BACKGROUND: (82, 173, 200),
                Options.FOREGROUND: (20, 61, 89),
                Options.BORDER_WIDTH: 0
            }

            about_text = [
                "This game was made by Ritobroto Mukherjee and",
                "Shivam Gupta (who has done absolutely nothing)",
                "as practice for collaboration on a group project."
            ]
            y_offset = 0
            for line in about_text:
                lbl = Label(
                    pygame.Rect(10, 300 + y_offset * 30,
                                screen.get_width() - 10, 30), line,
                    text_options)
                self.about_labels.append(lbl)
                y_offset += 1

            version_text = "PenFight v1.0"
            self.version_label = Label(
                pygame.Rect(screen.get_width() / 2 - 25,
                            screen.get_height() - 50, 50, 30), version_text,
                text_options)

            self.already_loaded = True

    def update(self, event):
        self.back_btn.update(event)

        if self.back_btn.clicked:
            Scene.pop_scene()

    def draw(self, screen):
        screen.fill((82, 173, 200))
        self.back_btn.draw(screen)
        for elt in self.about_labels + [self.version_label]:
            elt.draw(screen)
Ejemplo n.º 15
0
    def __init__(self, parent):
        self.parent = parent

        self.last_time = pygame.time.get_ticks()

        self.button_font = pygame.font.SysFont('consolas', 20)
        self.font = pygame.font.SysFont('consolas', 25)

        self.tasks = ButtonContainer()
        self.selected_tasks = []
        self.task_start_y = 100

        self.buttons = ButtonContainer([
            Button(
                self.parent.window_size[0] - self.button_font.size('Back')
                [0],  # Make these buttons position themselves when resizing 
                10,
                text='Back',
                fg=(255, 0, 0),
                font=self.button_font,
                show_box=False,
                command=self.parent.main),
            Button(10,
                   40,
                   120,
                   20,
                   text='Add a task',
                   font=self.button_font,
                   show_box=False,
                   fg=(255, 255, 255),
                   command=self.input_task),
            Button(10,
                   self.parent.window_size[1] -
                   self.button_font.size('Complete')[1],
                   self.button_font.size('Complete')[0],
                   self.button_font.size('Complete')[1],
                   text='Complete',
                   font=self.button_font,
                   show_box=False,
                   fg=(255, 255, 255),
                   command=self.complete_tasks),
            Button(self.button_font.size('Complete')[0] + 30,
                   self.parent.window_size[1] -
                   self.button_font.size('Complete')[1],
                   self.button_font.size('Abandon')[0],
                   self.button_font.size('Abandon')[1],
                   text='Abandon',
                   font=self.button_font,
                   show_box=False,
                   fg=(255, 255, 255),
                   command=self.abandon_task)
        ])

        self.particles = ParticleContainer()
Ejemplo n.º 16
0
    def __init__(self, game):
        self.game = game
        GameStateScreen.__init__(self, game)
        self.prev_screen = None
        self.stackpanel = StackPanel(game, (SCR_W / 2 - 200, 300), 400)

        btn_controls = Button(game, text='Controls', action=self.btn_cl_action)
        btn_sound = Button(game, text='Sound', action=self.btn_sn_action)
        btn_back = Button(game, text='Back', action=self.btn_bk_action)

        self.stackpanel.add_widgets(btn_controls, btn_sound, btn_back)
Ejemplo n.º 17
0
    def __init__(self, game):
        self.game = game
        GameStateScreen.__init__(self, game)
        self.stackpanel = StackPanel(game, (SCR_W / 2 - 200, 300), 400)

        txt_question = label(game, text='Are you sure you want to quit?')
        btn_yes = Button(game, text='Yes', action=self.game.quit)
        btn_no = Button(game, text='No', action=self.btn_no_action)

        self.stackpanel.add_widgets(txt_question, btn_yes, btn_no)

        self.prev_screen = None
Ejemplo n.º 18
0
    def start(self, screen):
        if not self.already_loaded:
            width = screen.get_width()
            height = screen.get_height()

            self.header = Label(pygame.Rect(width / 2 - 75,
                                            height * 1 / 5 + 10, 150, 50),
                                "Game Paused",
                                options={
                                    Options.BACKGROUND: (20, 61, 89),
                                    Options.FOREGROUND: (244, 180, 26),
                                    Options.BORDER_WIDTH: 0,
                                })

            self.back_btn = Button(
                pygame.Rect(width * 1 / 5 + 10, height * 1 / 5 + 10, 60, 40),
                "Back", {
                    Options.BORDER_WIDTH: 0,
                    Options.BACKGROUND: (20, 61, 89),
                    Options.FOREGROUND: (244, 180, 26),
                    Options.HOVERED_BACKGROUND: (10, 30, 45),
                    Options.FONT: pygame.font.SysFont("Comic Sans MS", 15)
                })

            self.forfeit_btn = Button(
                pygame.Rect(width / 2 - 75, height / 2, 150, 40), "Forfeit", {
                    Options.BORDER_WIDTH: 0,
                    Options.BACKGROUND: (20, 61, 89),
                    Options.FOREGROUND: (244, 180, 26),
                    Options.HOVERED_BACKGROUND: (10, 30, 45),
                    Options.FONT: pygame.font.SysFont("Comic Sans MS", 25)
                })

            settings_gear_image = Resources.get("gear")
            settings_gear_rect = pygame.rect.Rect(width * 4 / 5 - 100,
                                                  height * 4 / 5 - 100, 75, 75)
            self.settings_btn = Image(
                settings_gear_rect, settings_gear_image, {
                    Options.BACKGROUND: (20, 61, 89),
                    Options.HOVERED_BACKGROUND: (10, 30, 45)
                })

            self.already_loaded = True

        if self.last_scene_id != Scene.scene_stack[-2]:
            self.last_scene_id = Scene.scene_stack[-2]
            self.underlay_screen = screen.copy()
            dark_cover = pygame.Surface(
                self.underlay_screen.get_size()).convert_alpha(
                    self.underlay_screen)
            dark_cover.fill((0, 0, 0, 0.6 * 255))
            self.underlay_screen.blit(dark_cover, (0, 0))
Ejemplo n.º 19
0
    def start(self, screen):
        width = screen.get_width()
        height = screen.get_height()

        if not self.already_loaded:
            StatsScene.create_metrics()

            self.header = Label(pygame.rect.Rect(width / 2 - 200, 10, 400, 30),
                                "Statistics",
                                options={
                                    Options.BACKGROUND: (20, 61, 89),
                                    Options.FOREGROUND: (244, 180, 26),
                                    Options.BORDER_WIDTH: 0,
                                })

            self.first_offset = pygame.rect.Rect(width / 2 - 125, 75, 250, 30)

            label_options = {
                Options.BACKGROUND: (82, 173, 200),
                Options.FOREGROUND: (20, 61, 89),
                Options.BORDER_WIDTH: 0
            }

            for metric in StatsScene.all_metrics.keys():
                text = f"{metric}: {StatsScene.all_metrics[metric](Account.current_account)}"
                stat_lbl = Label(pygame.rect.Rect(0, 0, 0, 0), text,
                                 label_options)
                self.statistics.append(stat_lbl)

            btn_options = {
                Options.BORDER_WIDTH: 0,
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.HOVERED_BACKGROUND: (10, 30, 45),
                Options.FONT: pygame.font.SysFont("Comic Sans MS", 15)
            }

            self.back_btn = Button(pygame.rect.Rect(10, 10, 60, 40), "Back",
                                   btn_options)

            self.up_btn = Button(
                pygame.rect.Rect(width * 5 / 6, height * 2 / 6, 60, 40), "Up",
                btn_options)
            self.down_btn = Button(
                pygame.rect.Rect(width * 5 / 6, height * 4 / 6 - 40, 60, 40),
                "Down", btn_options)

            self.already_loaded = True

        self.stat_index = 0
        self.reposition_stats()
Ejemplo n.º 20
0
    def __init__(self, game, mode):
        GameStateScreen.__init__(self, game)
        self.mode = mode
        self.stack_panel = StackPanel(game, (515, 400), 250)

        btn_again = Button(game,
                           text='Play again',
                           action=self.btn_again_action)
        btn_menu = Button(game,
                          text='Return to main menu',
                          action=self.btn_menu_action)
        btn_quit = Button(game, text='Quit', action=self.btn_quit_action)

        self.stack_panel.add_widgets(btn_again, btn_menu, btn_quit)
Ejemplo n.º 21
0
    def event_loop(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.VIDEORESIZE:
                self.parent.window_size = (event.w, event.h)
                self.parent.window = pygame.display.set_mode(
                    self.parent.window_size, pygame.RESIZABLE)

                self.buttons = ButtonContainer([
                    Button(self.parent.window_size[0] -
                           self.button_font.size('Back')[0],
                           10,
                           text='Back',
                           fg=(255, 0, 0),
                           font=self.button_font,
                           show_box=False,
                           command=self.parent.main),
                    Button(10,
                           40,
                           120,
                           20,
                           text='Add a task',
                           font=self.button_font,
                           show_box=False,
                           fg=(255, 255, 255),
                           command=self.input_task),
                    Button(10,
                           self.parent.window_size[1] -
                           self.button_font.size('Complete')[1],
                           self.button_font.size('Complete')[0],
                           self.button_font.size('Complete')[1],
                           text='Complete',
                           font=self.button_font,
                           show_box=False,
                           fg=(255, 255, 255),
                           command=self.complete_tasks),
                    Button(self.button_font.size('Complete')[0] + 30,
                           self.parent.window_size[1] -
                           self.button_font.size('Complete')[1],
                           self.button_font.size('Abandon')[0],
                           self.button_font.size('Abandon')[1],
                           text='Abandon',
                           font=self.button_font,
                           show_box=False,
                           fg=(255, 255, 255),
                           command=lambda: print(
                               'continue this | abandon button'))
                ])
Ejemplo n.º 22
0
def init_menu():
    global screen, width, height, image_menu
    button_width = 200
    button_height = 100
    horizontal = width / 2 - (button_width * 2 + 50) / 2 - 100
    vertical = height / 2 - button_height / 2 + 250
    menu_obj.append(
        Button((horizontal, vertical), (button_width, button_height),
               Colors.BLACK, Colors.RED, start_game, "PLAY"))
    menu_obj.append(
        Button((horizontal + 300, vertical), (button_width, button_height),
               Colors.BLACK, Colors.RED, go_to_load_menu, "LOAD"))
    image_menu = pygame.image.load(os.path.join("img/menu.jpg"))
    pygame.mixer.music.load('sounds/soundtrack.mp3')
    pygame.mixer.music.play(-1)
Ejemplo n.º 23
0
 def __init__(self, size):
     Template.__init__(self, size)
     self.name = "World Editor 1.1"
     self.size = size
     self.block = 32
     self.dt = 0.
     self.empty_tile = pg.image.load("./tiles/Empty_tile_32p.png").convert_alpha()
     self.map_bg = Map("Background", self, self.size, (120,80), self.block, self.empty_tile)
     self.map_mg = Map("Middleground", self, self.size, (120,80), self.block, self.empty_tile)
     self.map_fg = Map("Foreground", self, self.size, (120,80), self.block, self.empty_tile)
     self.poi_map = Map("POI Map", self, self.size, (120,80), self.block, self.empty_tile)
     self.poi_menu = Map("POI Menu", self, self.size, (4,1), self.block, self.empty_tile)
     self.menus = [Map("Menu", self, self.size, (2,14), self.block, self.empty_tile)]
     self.pal_menu = Menu((128, 40), (0,21))
     self.pal_menu.add_buttons(2, ["New", "Pal-1"])
     self.pal_menu.set_bg_color(SUBBUTTON_COLOR)
     self.menu = self.menus[0]
     self.menu.xy[1] += 20
     self.men_list = []
     self.sprite_map = self.setup_spritemap()
     self.sprite_map.xy = [250,0]
     self.clip = pg.Rect(0,0, self.size[0],self.size[1])
     self.c_pos = self.clip.topleft
     self.show_full_map = False
     self.show_poi = False
     self.full_map = None
     self.current_tile = None
     self.current_menu = None
     self.ground_state = None
     self.right_m_pos = None
     self.right_m_button = False
     self.fill = False
     self.m_pos = None
     self.m_select_rect = pg.Rect(1,1,1,1)
     self.menu_button = Button((120, 20), (129,1), "Menu")
     self.pal_button = Button((128,20), (0,0), "Palette")
     self.drop_menu = Menu((120, 160), (129, 21))
     self.drop_menu.add_buttons(5, ["Save", "Load", "Sprites", "See Map", "Info"])
     self.drop_menu.set_bg_color(SUBBUTTON_COLOR)
     self.load_menu = self.setup_loadmenu()
     self.floating_text = FloatingText("no text", self.size)
     self.info_panel = Panel((self.size[0] - self.size[0]/3, self.size[1] - self.size[1]/3), (self.size[0]/6, self.size[1]/6))
     self.info_panel.setup_text([self.name, "Made by Aurelio Aguirre", "", "Use WASD to move around.", "Use E to toggle the Foreground.", "Use R to toggle the Middleground.", "Use Q to toggle the Point of Interest map."])
     self.setup()
     self.setup_poi()
     self.selected_map = self.map_bg
     self.alternative = ALTERNATIVE_MODE
     self.enable_alternative_mode()
Ejemplo n.º 24
0
    def __init__(self):
        self.window_size = (1000, 700)
        self.window = pygame.display.set_mode(self.window_size, pygame.RESIZABLE)
        self.todo_menu = TodoMenu(self)

        self.font = pygame.font.SysFont('consolas', 40)
        
        self.characters = { # Add player buttons
            'dave': Character(50, 10, 950, 1, exp_color = (0, 0, 255), sprites = [
                pygame.transform.scale(load_sprite('characters\\dave\\1.png', (255, 255, 255)), (500, 500)),
                pygame.transform.scale(load_sprite('characters\\dave\\2.png', (255, 255, 255)), (500, 500)),
                pygame.transform.scale(load_sprite('characters\\dave\\3.png', (255, 255, 255)), (500, 500)),
                pygame.transform.scale(load_sprite('characters\\dave\\4.png', (255, 255, 255)), (500, 500))
            ])
        }
        
        self.current_character = self.characters['dave']

        self.buttons = ButtonContainer([
                Button(10, 10, text = 'Todo menu', command = self.todo_menu.main, font = pygame.font.SysFont('consolas', 20), fg = (255, 255, 255),
                       show_box = False),
        ])

        self.particles = ParticleContainer()

        self.last_time = pygame.time.get_ticks()
Ejemplo n.º 25
0
 def __init__(self, game):
     super().__init__(game)
     self.buttons = []
     x = (game.width)//2-250
     
     for i in range(1,4):
         self.buttons.append(Button(str(i),(x+25+((i-1)%5)*100,160+((i-1)//5)*100,50,50), (220,220,0),action=self.selectAIDifficulty, args=(i,)))
Ejemplo n.º 26
0
    def __init__(self, size):
        Template.__init__(self, size)
        self.size = size
        self.block = 64
        self.dt = 0.
        self.map1 = Map(self.size, (40,40), self.block, "./tiles/Empty_tile_64p.png")
        self.map2 = Map(self.size, (40,40), self.block, "./tiles/Empty_tile_64p.png")
        self.menu = Map(self.size, (2,14), self.block, "./tiles/Empty_tile_64p.png")
        self.menu_list = []
        self.palette = self.setup_menu()
        self.palette.xy = [250,0]
        self.clip = pg.Rect(0,0, self.size[0],self.size[1])
        self.c_pos = self.clip.topleft
        self.current_tile = None
        self.show_foreground = -1
        self.right_m_button = False
        self.right_m_pos = None
        self.m_pos = None
        self.fill = False
        self.m_select_rect = pg.Rect(1,1,1,1)
        self.button1 = Button((120, 20), (129,1), "Menu")
        self.drop_menu = Menu((120, 160), (129, 21))
        self.drop_menu.add_buttons(4, ["Save", "Load", "Palette", "Info"])
        self.drop_menu.set_bg_color(CONCRETE)
        self.load_menu = self.setup_loadmenu()
        self.floating_text = FloatingText("no text", self.size)
        self.setup()

        self.selected_map = self.map1
Ejemplo n.º 27
0
    def __init__(self):
        self.character_sprites = SpriteGroup()
        self.grid_sprites = SpriteGroup()
        self.button_sprites = SpriteGroup()
        self.infowidget_sprites = SpriteGroup()

        self.characters, n_characters = [], 8
        hex_positions = [(i, j) for i in range(pr.grid_width) for j in range(pr.grid_height)]
        character_positions = random.sample(hex_positions, n_characters)
        for cp in character_positions:
            h, w = cp
            cts = pr.CharacterType.type_names()
            ct_i = random.randrange(0, len(cts))
            self.characters.append(character_module.Character(sprite_group=self.character_sprites,
                                                              grid_position=(h, w),
                                                              character_type=pr.CharacterType[cts[ct_i]]))

        self.grid_topleft_position = (pr.game_window_width // 4, pr.game_window_height // 4)
        self.bg_grid_surface = pg.Surface((pr.game_window_width // 2, pr.game_window_height // 2))
        self.bg_grid_surface_rect = self.bg_grid_surface.get_rect(topleft=self.grid_topleft_position)
        self.bg_grid_surface.fill(pr.WHITE_RGB)

        self.grid = grid_module.Grid(sprite_group=self.grid_sprites,
                                     bg_surface_data=(self.bg_grid_surface, self.bg_grid_surface_rect),
                                     width_in_hexes=pr.grid_width,
                                     height_in_hexes=pr.grid_height,
                                     hex_edge_length=pr.hex_edge_length,
                                     objects=self.characters)

        self.menu_button = Button(game_state=self,
                                  pos=(13 * pr.game_window_width // 16, 1 * pr.game_window_height // 8),
                                  text='Back to menu',
                                  action=finish_game_action)
        self.end_turn_button = Button(game_state=self,
                                      pos=(13 * pr.game_window_width // 16, 7 * pr.game_window_height // 8),
                                      text='End the turn',
                                      action=end_turn_action)
        self.hex_infowidget = InfoWidget(game_state=self,
                                         pos=(0, 1 * pr.game_window_height // 4),
                                         size=(pr.game_window_width // 6, pr.game_window_height // 4),
                                         action=update_hex_infowidget)
        self.initiative_order_infowidget = InfoWidget(game_state=self,
                                                      pos=(
                                                      13 * pr.game_window_width // 16, 1 * pr.game_window_height // 4),
                                                      size=(3 * pr.game_window_width // 16, pr.game_window_height // 2),
                                                      action=update_initiative_order_infowidget)
Ejemplo n.º 28
0
def setup_light(idx, light):
    Button(light.name, [(0, 0, 255), (255, 255, 0), (255, 0, 0),
                        (0, 255, 0)][x], (10 + left, 10), (100, 100),
           lambda b, e, t: light.toggle())

    Slider((0, 100, 0), [(0, 0, 255), (255, 255, 0), (255, 0, 0),
                         (0, 255, 0)][x], (10 + left, 120), (100, 350),
           lambda s, v: light.brightness(v))
Ejemplo n.º 29
0
    def __init__(self,
                 parent='osd',
                 text=None,
                 search=None,
                 handler=None,
                 left=None,
                 top=None,
                 width=600,
                 height=200,
                 bg_color=None,
                 fg_color=None,
                 icon=None,
                 border=None,
                 bd_color=None,
                 bd_width=None,
                 vertical_expansion=1):

        if not text:
            text = _('Program Search')

        PopupBox.__init__(self,
                          text,
                          handler,
                          left,
                          top,
                          width,
                          height,
                          icon,
                          vertical_expansion,
                          parent=parent)

        (self.server_available, msg) = record_client.connectionTest()
        if not self.server_available:
            errormsg = Label(_('Recording server is unavailable.') + \
                             ( ': %s\n\n' % msg ) + \
                             _('Feel free to implement this function inside the main guide.'),
                             self, Align.CENTER)
            return

        self.internal_h_align = Align.CENTER

        self.lbg = LetterBoxGroup(text=search)
        self.add_child(self.lbg)

        items_height = Button('foo').height
        self.num_shown_items = 8
        self.results = ListBox(width=(self.width - 2 * self.h_margin),
                               height=self.num_shown_items * items_height,
                               show_v_scrollbar=0)
        self.results.y_scroll_interval = self.results.items_height = items_height
        max_results = 10

        self.results.set_h_align(Align.CENTER)
        self.add_child(self.results)

        if search:
            self.searchProg(search)
        self.center_on_screen = TRUE
Ejemplo n.º 30
0
class LoadGameWindow:
    """
    Loads an in game window for handling saved games
    """
    def __init__(self,
                 x_pos=CONFIG.WINDOW_WIDTH // 2,
                 y_pos=CONFIG.WINDOW_HEIGHT // 2,
                 width=0.5 * CONFIG.WINDOW_WIDTH,
                 height=0.8 * CONFIG.WINDOW_HEIGHT):
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.width = width
        self.height = height
        self.list = [fn.replace('.save', '') for fn in os.listdir(SAVE_FOLDER)]
        self.file_list = List(self.x_pos, self.y_pos, self.list)
        self.background = pygame.Surface((
            self.width,
            self.height,
        ))
        self.background.fill(BG_COLOR_2)

        common_y = self.y_pos + self.height // 2 - 3 * CONFIG.CHARACTER_SIZE
        self.back_button = Button(self.x_pos + self.width // 4 - 15, common_y,
                                  'BACK')
        self.load_button = Button(
            self.x_pos + self.width // 4 - self.back_button.width - 15,
            common_y, 'LOAD')

    def display(self, screen):
        """
        :returns bool: true if the window is still opened, false if it can be closed
        """
        screen.blit(self.background, (
            self.x_pos - self.width // 2,
            self.y_pos - self.height // 2,
        ))
        self.load_button.display(screen)
        self.back_button.display(screen)
        self.file_list.display(screen)

        if self.load_button.state == ButtonState.RELEASED:
            return False
        elif self.back_button.state == ButtonState.RELEASED:
            return False
        return True
Ejemplo n.º 31
0
	def __init__(self, display):
		GUI.__init__(self, display)

		self.onClose = None
		self.onSetLight = None
		self.lumWarm = 0
		self.lumCold = 0

		self.margin = 16

		self.cellsX = 3
		self.cellsY = 4

		self.gridW = (self.width - self.margin * (self.cellsX + 1)) / self.cellsX
		self.gridH = (self.height - self.margin * (self.cellsY + 1)) / self.cellsY

		nextX = self.margin
		nextY = self.margin

		buttonQuit = Button(self, nextX, nextX, self.gridW, self.gridH, name="quit", label="Quit")
		nextX += self.gridW + self.margin
		buttonReboot = Button(self, nextX, nextY, self.gridW, self.gridH, name="reboot", label="Reboot")
		#nextX += self.gridW + self.margin
		#button3 = Button(self, nextX, nextY, self.gridW, self.gridH)
		nextX += self.gridW + self.margin
		buttonClose = Button(self, nextX, nextY, self.gridW, self.gridH, name="close", label="CLOSE")
		sliderWidth = self.gridW * self.cellsX + (self.cellsX-1) * self.margin
		nextX = self.margin
		nextY  += self.gridH + self.margin
		sliderWarm = Slider(self, nextX, nextY, sliderWidth, self.gridH, name="warm", label="WARM")
		nextY  += self.gridH + self.margin
		sliderCold = Slider(self, nextX, nextY, sliderWidth, self.gridH, name="cold", label="COLD")

		sliderWarm.onChange = self.changeLight
		sliderCold.onChange = self.changeLight
		buttonQuit.onClick = self.clickButton
		buttonReboot.onClick = self.clickButton
		#button3.onClick = self.clickButton
		buttonClose.onClick = self.clickButton

		self.addWidget(buttonQuit)
		self.addWidget(buttonReboot)
		#self.addWidget(button3)
		self.addWidget(buttonClose)
		self.addWidget(sliderWarm)
		self.addWidget(sliderCold)

		self.drawBG()
Ejemplo n.º 32
0
    def __init__(self, game):
        self.game = game
        GameStateScreen.__init__(self, game)
        self.prev_screen = None

        self.btn_back = Button(game, text='Back', action=self.btn_bk_action)
        self.container = StandaloneContainer(game, (0, 0),
                                             150,
                                             50,
                                             self.btn_back,
                                             focus=True)
Ejemplo n.º 33
0
    def __init__(self):
        self.logo = self.logo = pygame.image.load(IMAGE_FOLDER + 'logo.png')
        self.logo_size = self.logo.get_rect().size
        self.show_game_loader = False
        self.game_loader = LoadGameWindow()

        button_margin = 50
        self.new_game_button = Button(
            96, CONFIG.WINDOW_HEIGHT - 96 - 3 * button_margin, 'NEW GAME')
        self.load_game_button = Button(
            96, CONFIG.WINDOW_HEIGHT - 96 - 2 * button_margin, 'LOAD GAME')
        self.settings_button = Button(
            96, CONFIG.WINDOW_HEIGHT - 96 - button_margin, 'SETTINGS')
        self.exit_button = Button(96, CONFIG.WINDOW_HEIGHT - 96, 'EXIT')
Ejemplo n.º 34
0
 def __init__(self, view, game):
     
     self.game = game
     self.controller = view.controller
     #ugly
     view.controller = Controller()
     
     win = ContenedorMovil(position=(230, 50), size=(550, 530), parent=view.desktop)
     
     pass_button = Button(position = (400, 10), size=(60, 0),parent = win, text="Pass")
     pass_button.onClick = self.controller.pass_game
     
     win.onClick = self.controller.on_click
     win.onMouseDown = self.capture_first_position
     win.first_position = pygame.mouse.get_pos() 
     win.board = GoBoard(parent=win, position=(0, 80), delta=(30, 40), game=game)        
     win.board.windows = win
     win.board.controller = view.controller
     
     thread = threading.Thread(target=game.play)
     thread.start()
     
     win.onClose = self.finish_game
Ejemplo n.º 35
0
    def __init__(self, user, password, id, status, set_default):
        super(Varify, self).__init__()
        self.__status = status
        self.set_title('Verification')
        self.set_icon_from_file(ICON_PATH + '/validate.png')
        self.__set_default = set_default
        self.set_modal(True)
        self.set_resizable(False)
        self.set_border_width(20)
        vbox = gtk.VBox(False, 10)
        label = gtk.Label()
        label.set_markup('<span font_desc="belgrano">    Enter the <b>\
Activation Code</b> sent\nto your mobile <span foreground="#FF0000"><b>%s</b>\
</span> below</span>' % user)
        vbox.pack_start(label)
        hbox = gtk.HBox(False, 10)
        re_send = Button(ICON_PATH + '/resend.png', 'Re Send Code', 20, 20)
        re_send.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#000000'))
        re_send.connect('clicked', self.__resend, user, id)
        entry = gtk.Entry()
        entry.modify_font(pango.FontDescription('CrashNumberingGothic'))
        def clear_background(entry, unused):
            entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse('#FFFFFF'))
            if entry.get_text() == 'Incorrect Code' or\
               entry.get_text() == 'Re Send Code':
                entry.set_text('')
            return False
        entry.connect('focus-in-event', clear_background)
        entry.set_alignment(0.5)
        hbox.pack_start(entry, True, True)
        hbox.pack_start(re_send, False, False)
        alignment = gtk.Alignment(0.5, 0, 0, 0)
        alignment.add(hbox)
        vbox.pack_start(alignment)
        activate = Button(ICON_PATH + '/activate.png', 'Activate Account', 60,
                          30)
        activate.connect('clicked', self.__activate, entry, user, password, id)
        alignment = gtk.Alignment(0.86, 0, 0, 0)
        alignment.add(activate)
        vbox.pack_start(alignment)
        alignment = gtk.Alignment(0, 0, 0, 1)
        alignment.add(vbox)
        self.add(alignment)
        self.connect('destroy', gtk.main_quit)
        self.show_all()
Ejemplo n.º 36
0
    def __init__(self, contact = None):
        super(PhoneBook, self).__init__()
        self.set_size_request(444, 300)
        self.set_border_width(10)
        self.set_title('Contact Information')
        self.set_icon_from_file(ICON_PATH + '/contact.png')
        self.set_decorated(True)
        self.set_modal(True)
        self.set_position(gtk.WIN_POS_MOUSE)
        self.entry_list = []
        label = gtk.Label()
        label.set_markup('<span font_desc="belgrano 11">Name : </span>')
        label.set_justify(gtk.JUSTIFY_LEFT)
        self.entry_list.append(gtk.Entry())
        def left_strip_name(entry):
            entry.set_text(entry.get_text().lstrip())
        self.entry_list[0].connect("changed", left_strip_name)
        self.entry_list[0].modify_font(pango.FontDescription('belgrano'))
        h_box = gtk.HBox()
        h_box.pack_start(label)
        h_box.pack_start(self.entry_list[-1])
        alignment = gtk.Alignment(0.5, 0, 0, 0)
        alignment.add(h_box)
        v_box = gtk.VBox(False, 4)
        v_box.pack_start(alignment)
        self.__add_button = Button(ICON_PATH + '/add.png', 'add contact', 20,
                                   20)
        self.__remove_button = Button(ICON_PATH + '/remove.png',
                                      'remove contact', 20, 20)
        self.__default_button = Button(ICON_PATH + '/default.png',
                                       'set default', 20, 20)
        h_box = gtk.HBox(False, 10)
        label = gtk.Label()
        label.set_markup('<span font_desc="belgrano 10" foreground="#ffffff">\
<b>Default No</b> :</span>')
        h_box.pack_start(label)
        self.entry_list.append(gtk.Entry())
        self.entry_list[-1].connect("changed", self.__check_num)
        self.entry_list[-1].modify_font(pango.FontDescription('CrashNumberingGothic'))
        self.entry_list[-1].set_max_length(10)
        h_box.pack_start(self.entry_list[-1])
        h_box.pack_start(self.__add_button)
        alignment = gtk.Alignment(0, 0, 0, 0)
        alignment.add(h_box)
        vbox = gtk.VBox(True, 4)
        vbox.pack_start(alignment)
        alignment = gtk.Alignment(0, 0, 0, 0)
        alignment.add(vbox)
        alignment.set_border_width(8)
        scroll = gtk.ScrolledWindow()
        scroll.set_size_request(420, 180)
        scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        scroll.add_with_viewport(alignment)
        scroll.set_border_width(8)
        self.__add_button.connect("clicked", self.__add_entry, vbox)
        self.__remove_button.connect("clicked", self.__remove_entry, vbox)
        self.__default_button.connect("clicked", self.__change_default)
        frame = gtk.Frame('Contact Numbers')
        frame.get_label_widget().modify_font(pango.FontDescription('belgrano'))
        frame.set_label_align(0.5, 0.5)
        frame.set_shadow_type(gtk.SHADOW_IN)
        self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ffffff'))
        frame.get_label_widget().set_sensitive(False)
        frame.add(scroll)
        scroll.get_child().modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(
                                                                  '#000000'))
        v_box.pack_start(frame)
        save = Button(ICON_PATH + '/save.png', 'Save')
        cancel = Button(ICON_PATH + '/cancel.png', 'Cancel')
        save.connect("clicked", self.__save)
        cancel.connect("clicked", self.__cancel)
        h_box = gtk.HBox(True, 8)
        h_box.pack_start(cancel)
        h_box.pack_start(save)
        alignment = gtk.Alignment(1, 0.5, 0, 1)
        alignment.add(h_box)
        v_box.pack_start(alignment)
        self.__count = 1
        self.add(v_box)
        self.connect('destroy', gtk.main_quit)
        self.set_resizable(False)
        if contact:
            for text in contact[2:]:
                if text:
                    self.__add_button.emit('clicked')
            for index in range(len(contact)):
                if contact[index]:
                    self.entry_list[index].set_text(contact[index])
        self.show_all()
Ejemplo n.º 37
0
 def Button(self, x=0, y=0, width=160, height=50, image=button_image, image_highlighted=button_highlighted, caption="Unlabeled", batch=None, group=None, label_group=None, font_name='ChunkFive Roman', on_click=None, enabled=True):
     button = Button(self, x=x, y=y, width=width, height=height, image=image, image_highlighted=image_highlighted, caption=caption, batch=(batch or self.batch), group=(group or self.group), label_group=(label_group or self.labels_group), font_name=font_name, enabled=enabled)
     if on_click:
         button.push_handlers(on_click=on_click)
     return button
Ejemplo n.º 38
0
    def __init__(self, login_thread_list):
        super(Interface, self).__init__()
        self.set_size_request(460, 400)
        self.set_border_width(4)
        self.set_title('SMS')
        self.set_icon_from_file(ICON_PATH + '/logo.png')
        self.set_decorated(True)
        self.set_position(gtk.WIN_POS_MOUSE)
        text_field = gtk.TextView()
        text_field.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ffffff'))
        text_field.set_border_width(10)
        text_field.modify_font(pango.FontDescription('belgrano'))
        text_buffer = gtk.TextBuffer()
        text_field.set_buffer(text_buffer)
        text_field.set_wrap_mode(gtk.WRAP_WORD_CHAR)
        text_field.set_tooltip_markup('   Type in your\n<b>MESSAGE</b> here')
        text_field.set_sensitive(False)
        def _enable_text_view_widget(field, thread_list):
            for thread in thread_list:
                if thread.isAlive():
                    return True
            status = True
            for thread in thread_list:
                status = status and thread.getStatus()
            field.set_sensitive(status)
            if not status:
                self.__push_status_message('<span font_desc="belgrano 10"><b>  Login Failed - Network Error</b></span>')
            return False
        gobject.timeout_add(200, _enable_text_view_widget, text_field, login_thread_list)
        self.spell_check_enable = False
        spell_correction = None
        size_tag = text_buffer.create_tag("size", size_points = 11)
        error_tag = text_buffer.create_tag("error", underline = pango.UNDERLINE_ERROR)
        frame = gtk.Frame('Message Body')
        frame.get_label_widget().modify_font(pango.FontDescription('belgrano'))
        frame.set_label_align(0.5, 0.5)
        frame.set_shadow_type(gtk.SHADOW_IN)
        frame.get_label_widget().set_sensitive(False)
        scroll = gtk.ScrolledWindow()
        scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scroll.set_border_width(4)
        scroll.add_with_viewport(text_field)
        scroll.get_child().modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ffffff'))
        frame.add(scroll)
        frame.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#70EDF7'))
        vbox = gtk.VBox(False, 4)
        hbox = gtk.HBox(False, 20)
        alignment = gtk.Alignment(1, 0.5, 1, 1)
        send = Button(ICON_PATH + '/send.png', 'Send Message')
        clear = Button(ICON_PATH + '/clear.png', 'Clear Field')
        send.connect("clicked", self.__send, text_buffer)
        clear.connect("clicked", self.__clear, text_buffer)
        def check_number(entry):
            'enforces only digits in the entry field'

            text = entry.get_active_text().strip()
            entry.child.set_text(''.join([i for i in text if i in '0123456789']))
            if not len(entry.child.get_text()):
                if self._receiver_index != -1:
                    index = self._receiver_index
                    self._receiver_index = -1
                    del self._receiver[index]
                    self._receiver_widget.remove_text(index)
            if len(entry.child.get_text()) == 10:
                if entry.get_active() != -1:
                    self._receiver_index = entry.get_active()
                if entry.child.get_text() not in self._receiver:
                    if self._receiver_index != -1:
                        self._receiver[self._receiver_index] = entry.child.get_text()
                        self._receiver_widget.remove_text(self._receiver_index)
                        self._receiver_widget.insert_text(self._receiver_index, entry.child.get_text())
                        self._receiver_index = -1
                    else:
                        entry.append_text(entry.child.get_text())
                        self._receiver.append(entry.child.get_text())
                    entry.child.set_text('')
            return False
        receiver_box = gtk.VBox(False, 4)
        label = gtk.Label()
        label.set_markup('<span font_desc="belgrano 10"><b>Receivers</b></span>')
        self._receiver = []
        self._receiver_index = -1
        self._receiver_widget = gtk.combo_box_entry_new_text()
        self._receiver_widget.child.modify_font(pango.FontDescription('CrashNumberingGothic'))
        self._receiver_widget.child.set_max_length(10)
        self._receiver_widget.child.set_tooltip_text("Enter Receivers'\n Numbers Here")
        self._receiver_widget.set_size_request(120, -1)
        self._receiver_widget.child.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('#0000ff'))
        self._receiver_widget.connect('changed', check_number)
        receiver_box.pack_start(label)
        receiver_box.pack_start(self._receiver_widget)
        hbox.pack_start(receiver_box, True, False)
        hbox.pack_start(clear, False, False)
        hbox.pack_start(send, False, False)
        alignment.add(hbox)
        vbox.pack_start(frame, True, True)
        vbox.pack_start(alignment, False, False)
        paned = gtk.HPaned()
        v_box = gtk.VBox(False, 8)
        paned.pack1(vbox, True, False)
        frame = gtk.Frame('Phone Book')
        frame.get_label_widget().modify_font(pango.FontDescription('belgrano'))
        frame.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#70EDF7'))
        frame.set_label_align(0.5, 0.5)
        frame.set_shadow_type(gtk.SHADOW_IN)
        frame.get_label_widget().set_sensitive(False)
        self.__contact_box = gtk.VBox(False, 10)
        alignment = gtk.Alignment(0, 0, 0, 0)
        alignment.set_border_width(4)
        alignment.add(self.__contact_box)
        self.add_contacts()
        scroll = gtk.ScrolledWindow()
        scroll.set_size_request(140, -1)
        scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        scroll.set_border_width(4)
        scroll.add_with_viewport(alignment)
        scroll.get_child().modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ffffff'))
        vbox = gtk.VBox(False, 2)
        hbox = gtk.HBox(True, 0)
        add = Button(ICON_PATH + '/add-user.png', 'Add Contact')
        add.set_border_width(2)
        add.connect('clicked', self.__add_user)
        edit = Button(ICON_PATH + '/edit-user.png', 'Edit Contact\nInformation')
        edit.connect('clicked', self.__edit_user)
        delete = Button(ICON_PATH + '/remove-user.png', 'Remove Contact')
        delete.set_border_width(2)
        delete.connect('clicked', self.__delete_user)
        vbox.pack_start(scroll, True, True)
        hbox.pack_start(add, True, True)
        hbox.pack_start(delete, True, True)
        alignment = gtk.Alignment(0.5, 0, 0, 0)
        alignment.add(hbox)
        vbox.pack_start(alignment, False, False)
        alignment = gtk.Alignment(0.5, 0, 0, 0)
        alignment.add(edit)
        vbox.pack_start(alignment, False, False)
        frame.add(vbox)
        paned.pack2(frame, False, False)
        def manage_account(unused):
            from account import AccountManager
            AccountManager()
            gtk.main()
        def show_about(unused):
            About()
        def show_history(unused):
            from history import HistoryManager
            HistoryManager()
            gtk.main()
        def load_from_file(unused):
            from path import HOME_PATH
            loader = gtk.FileChooserDialog(title = 'Open ...', action = gtk.FILE_CHOOSER_ACTION_OPEN, buttons = (gtk.STOCK_CANCEL,
                                                                            gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
            loader.set_icon_from_file(ICON_PATH + '/logo.png')
            loader.set_current_folder(HOME_PATH + '/Desktop')
            loader.set_default_response(gtk.RESPONSE_OK)
            filter = gtk.FileFilter()
            filter.set_name("Text")
            filter.add_pattern("*.txt")
            loader.add_filter(filter)
            filter = gtk.FileFilter()
            filter.set_name("All files")
            filter.add_pattern("*")
            loader.add_filter(filter)
            response = loader.run()
            if response == gtk.RESPONSE_OK:
                text_buffer.set_text(open(loader.get_filename()).read())
            loader.destroy()
            return
        def save_to_file(unused):
            from path import HOME_PATH
            import os
            if not os.path.exists(HOME_PATH + '/.sms/saved messages/'):
                os.makedirs(HOME_PATH + '/.sms/saved messages/')
            files = len([name for name in os.listdir(HOME_PATH + '/.sms/saved messages/')])
            loader = gtk.FileChooserDialog(title = "Save ...", action = gtk.FILE_CHOOSER_ACTION_SAVE, buttons = (gtk.STOCK_CANCEL,
                                                                            gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
            loader.set_icon_from_file(ICON_PATH + '/logo.png')
            loader.set_current_folder(HOME_PATH + '/.sms/saved messages/')
            loader.set_default_response(gtk.RESPONSE_OK)
            loader.set_current_name('message %s.txt' % str(files + 1))
            text = text_buffer.get_text(text_buffer.get_start_iter(), text_buffer.get_end_iter())
            response = loader.run()
            if response == gtk.RESPONSE_OK and text:
                filename = loader.get_filename()
                file = open(filename, 'w')
                file.write(text)
                file.close()
            loader.destroy()
            return
        def check_spell(unused):
            from SpellCheck import spell_check
            global spell_correction
            spell_correction = {}
            thread.start_new(spell_check, (text_buffer.get_text(text_buffer.get_start_iter(), text_buffer.get_end_iter()), spell_correction))
            text_buffer.remove_tag(error_tag, text_buffer.get_start_iter(), text_buffer.get_end_iter())
            text_buffer.apply_tag(size_tag, text_buffer.get_start_iter(), text_buffer.get_end_iter())
            gtk.main()
            if spell_correction:
                self.spell_check_enable = True
                for key in spell_correction.keys():
                    text_buffer.apply_tag(error_tag, text_buffer.get_iter_at_offset(key[0] - 1), text_buffer.get_iter_at_offset(key[0] + key[1] - 1))
        menu_bar = gtk.MenuBar()
        menu_bar.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ff0000'))
        menu = gtk.Menu()
        menu.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ff8800'))
        menu_item = gtk.MenuItem("Load")
        menu.append(menu_item)
        menu_item.connect('activate', load_from_file)
        menu_item = gtk.MenuItem("Save")
        menu.append(menu_item)
        menu_item.connect('activate', save_to_file)
        menu_item = gtk.MenuItem("User Account")
        menu.append(menu_item)
        menu_item.connect('activate', manage_account)
        menu_item = gtk.SeparatorMenuItem()
        menu.append(menu_item)
        menu_item = gtk.MenuItem("Quit")
        menu.append(menu_item)
        menu_item.connect('activate', gtk.main_quit)
        action_menu = gtk.MenuItem("_Action")
        action_menu.set_submenu(menu)
        menu_bar.append(action_menu)
        menu = gtk.Menu()
        menu.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ff8800'))
        menu_item = gtk.MenuItem("History")
        menu.append(menu_item)
        message_menu = gtk.MenuItem("_Message")
        menu_item.connect('activate', show_history)
        menu_item = gtk.MenuItem("Spell Check")
        menu.append(menu_item)
        menu_item.connect('activate', check_spell)
        message_menu.set_submenu(menu)
        menu_bar.append(message_menu)
        menu = gtk.Menu()
        menu.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ff8800'))
        menu_item = gtk.MenuItem("About")
        menu.append(menu_item)
        help_menu = gtk.MenuItem("_Help")
        menu_item.connect('activate', show_about)
        help_menu.set_submenu(menu)
        menu_bar.append(help_menu)
        self.status_bar = gtk.Statusbar()
        self.status_bar.set_size_request(-1, 28)
        self.status_bar.set_has_resize_grip(True)
        hbox = gtk.HBox(False, 2)
        hbox.pack_start(menu_bar, True, True)
        v_box.pack_start(hbox, False, False)
        v_box.pack_start(paned, True, True)
        v_box.pack_start(self.status_bar, False, False)
        self.add(v_box)
        text_buffer.connect("changed", self.__current_char, size_tag, error_tag)
        def spell_check_context_menu(unused, menu):
            global spell_correction
            cursor_pos = text_buffer.props.cursor_position
            if not self.spell_check_enable:
                return
            def replace_rectified(unused, word, key):
                del(spell_correction[key])
                start = text_buffer.get_iter_at_offset(key[0] - 1)
                end = text_buffer.get_iter_at_offset(key[0] + key[1] - 1)
                replaced = text_buffer.get_text(start, end)
                text_buffer.delete(start, end)
                text_buffer.insert(start, word)
                diff = len(replaced) - len(word)
                if diff:
                    for (k, v) in spell_correction.items()[:]:
                        del(spell_correction[k])
                        if key[0] < k[0]:
                            spell_correction[(k[0] - diff, k[1])] = v
                        else:
                            spell_correction[(k[0], k[1])] = v
                for key in spell_correction.keys():
                    text_buffer.apply_tag(error_tag,
                                    text_buffer.get_iter_at_offset(key[0] - 1),
                           text_buffer.get_iter_at_offset(key[0] + key[1] - 1))
                self.spell_check_enable = True
                return
            for key in spell_correction.keys():
                if cursor_pos >= key[0] - 1 and cursor_pos <= key[0] + key[1] - 1:
                    correct = spell_correction[key][:]
                    correct.reverse()
                    for word in correct:
                        menu_item = gtk.MenuItem(word)
                        menu.prepend(menu_item)
                        menu_item.connect('activate', replace_rectified, word, key)
                    menu.show_all()
                    break
            return
        text_field.connect('populate-popup', spell_check_context_menu)
        def destroy(unused):
            gtk.main_quit()
            return
        self.connect("destroy", destroy)
        self.set_focus(text_field)
        self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ffffff'))
        self.show_all()
Ejemplo n.º 39
0
 def __init__(self, set_default = False):
     from spinner import Spinner
     super(Auth, self).__init__()
     self.set_border_width(10)
     self.set_title('Authentication')
     self.set_icon_from_file(ICON_PATH + '/authenticate.png')
     self.set_resizable(False)
     self.set_modal(True)
     self.set_position(gtk.WIN_POS_MOUSE)
     self.__set_default = set_default
     v_box = gtk.VBox(False, 4)
     label = gtk.Label()
     label.set_markup('<span font_desc="belgrano 12">Your Phone Number : </span>')
     label.set_justify(gtk.JUSTIFY_LEFT)
     self.__user = gtk.Entry()
     self.__user.modify_font(pango.FontDescription('CrashNumberingGothic'))
     self.__user.set_max_length(10)
     self.__user.set_alignment(0.5)
     def check_user_name(entry):
         text = entry.get_text().strip()
         entry.set_text(''.join([i for i in text if i in '0123456789']))
         if len(entry.get_text()) == 10:
             self.set_focus(self.__password)
     def clear_background(entry, unused):
         entry.modify_base(gtk.STATE_NORMAL,
                                  gtk.gdk.color_parse('#FFFFFF'))
     self.__user.connect('changed', check_user_name)
     h_box = gtk.HBox()
     h_box.pack_start(label)
     h_box.pack_start(self.__user)
     alignment = gtk.Alignment(1, 0, 0, 0)
     alignment.add(h_box)
     v_box.pack_start(alignment)
     h_box = gtk.HBox()
     label = gtk.Label()
     label.set_markup('<span font_desc="belgrano 12">Way2Sms Password : </span>')
     h_box.pack_start(label)
     self.__password = gtk.Entry()
     def change_focus(unused, event, button):
         if event.keyval == gtk.keysyms.Return:
             button.emit('clicked')
     h_box.pack_start(self.__password)
     self.__password.set_visibility(False)
     alignment = gtk.Alignment(1, 0, 0, 0)
     alignment.add(h_box)
     v_box.pack_start(alignment)
     self.__user.connect('focus-in-event', clear_background)
     self.__password.connect('focus-in-event', clear_background)
     cancel = Button(ICON_PATH + '/cancel.png', 'Cancel', 40, 30)
     def __destroy(unused, self):
         self.emit('destroy')
     cancel.connect('clicked', __destroy, self)
     login = Button(ICON_PATH + '/login.png', 'Login', 40, 30)
     login.connect('clicked', self.__validate)
     self.__password.connect('key-release-event', change_focus, login)
     h_box = gtk.HBox(True, 10)
     h_box.pack_start(cancel)
     h_box.pack_start(login)
     alignment = gtk.Alignment(1, 0, 0, 0)
     alignment.add(h_box)
     v_box.pack_start(alignment)
     alignment = gtk.Alignment(0, 0, 0, 0)
     alignment.add(v_box)
     self.add(alignment)
     self.__spinner = Spinner('logging in ...')
     self.connect('destroy', gtk.main_quit)
     self.show_all()
     self.__spinner.hide_all()
Ejemplo n.º 40
0
class Main(Template):
    def __init__(self, size):
        Template.__init__(self, size)
        self.size = size
        self.block = 64
        self.dt = 0.
        self.map1 = Map(self.size, (40,40), self.block, "./tiles/Empty_tile_64p.png")
        self.map2 = Map(self.size, (40,40), self.block, "./tiles/Empty_tile_64p.png")
        self.menu = Map(self.size, (2,14), self.block, "./tiles/Empty_tile_64p.png")
        self.menu_list = []
        self.palette = self.setup_menu()
        self.palette.xy = [250,0]
        self.clip = pg.Rect(0,0, self.size[0],self.size[1])
        self.c_pos = self.clip.topleft
        self.current_tile = None
        self.show_foreground = -1
        self.right_m_button = False
        self.right_m_pos = None
        self.m_pos = None
        self.fill = False
        self.m_select_rect = pg.Rect(1,1,1,1)
        self.button1 = Button((120, 20), (129,1), "Menu")
        self.drop_menu = Menu((120, 160), (129, 21))
        self.drop_menu.add_buttons(4, ["Save", "Load", "Palette", "Info"])
        self.drop_menu.set_bg_color(CONCRETE)
        self.load_menu = self.setup_loadmenu()
        self.floating_text = FloatingText("no text", self.size)
        self.setup()

        self.selected_map = self.map1

    def update(self, dt):
        self.dt = dt
        self.map1.update(dt)
        self.menu.update(dt)
        self.palette.update(dt)
        self.floating_text.update(dt)
        if self.drop_menu.buttons[0].clicked:
            self.savemap()
            self.drop_menu.buttons[0].clicked = False
        if self.drop_menu.buttons[2].clicked:
            self.selected_map = self.palette
        else:
            self.selected_map = self.map1
        if self.map1.clipped:
            self.map2.map.set_clip()
            self.map1.clipped = False
        if self.c_pos != self.clip.topleft:
            self.c_pos = (self.c_pos[0] - self.map1.xy[0], self.c_pos[1] - self.map1.xy[1])
            self.clip.topleft = self.c_pos
        self.button1.update(self.dt)
        self.mouse_select()

    def draw(self):
        self.screen.fill(BLACK)

        # MAP
        # Background
        self.map1.draw(self.screen, self.clip)

        # Foreground
        if self.show_foreground > 0:
            self.map2.xy = self.map1.xy
            self.map2.draw(self.screen, self.clip)

        # GUI
        self.menu.draw(self.screen, None)
        self.button1.draw(self.screen)
        if self.button1.clicked:
            self.drop_menu.draw(self.screen)
        if self.drop_menu.buttons[1].clicked:
            self.load_menu.draw(self.screen)
        if self.drop_menu.buttons[2].clicked:
            self.palette.draw(self.screen)
        if self.right_m_button:
            screen_rect = self.m_select_rect.copy()
            screen_rect.x += self.map1.xy[0]
            screen_rect.y += self.map1.xy[1]
            pg.draw.rect(self.screen, WHITE, screen_rect, 1)

        self.floating_text.draw(self.screen)

########################## Setup methods #######################################

    def setup_loadmenu(self):
        folder = Path("./save")
        filelist = [f for f in folder.files("*.sav")]
        amount = len(filelist)
        menu = Menu((240, amount*21), (250, 21))
        menu.add_buttons(amount, filelist)
        menu.set_bg_color(CONCRETE)
        return menu

    def setup(self):
        self.map1.setup(TEAL)
        self.map2.setup(CONCRETE, 200)
        self.menu.setup(CYAN)

    def setup_menu(self):
        sheet = SpriteSheet("./img/magecity_64p.png", 64, (0,0), (8,44))
        self.menu_list = sum(sheet.image_list, [])
        length = len(self.menu_list)
        size = (10, length/10)
        menu = Map(self.size, size, self.block, "./tiles/Empty_tile_64p.png")
        menu.setup(CYAN)
        i = 1
        for tile in menu.group:
            tile.filename = "maptile{}".format(i)
            tile.image = self.menu_list[i]
            if i+1 >= len(self.menu_list):
                break
            else:
                i += 1
        return menu

#################### Key and Mouse Methods #####################################

    def key_down(self, key):
        if key == K_ESCAPE:
            print "Quitting..."
            self.game_on == False
            self.end_game()

        if key == K_e:
            self.show_foreground *= -1

        if key in (K_w, K_UP):
            self.selected_map.move["up"] = True
        if key in (K_a, K_LEFT):
            self.selected_map.move["left"] = True
        if key in (K_s, K_DOWN):
            self.selected_map.move["down"] = True
        if key in (K_d, K_RIGHT):
            self.selected_map.move["right"] = True

    def key_up(self, key):
        if key in (K_w, K_UP):
            self.selected_map.move["up"] = False
        if key in (K_a, K_LEFT):
            self.selected_map.move["left"] = False
        if key in (K_s, K_DOWN):
            self.selected_map.move["down"] = False
        if key in (K_d, K_RIGHT):
            self.selected_map.move["right"] = False

    def mouse_down(self, button, pos):
        not_menu = True
        if button == 1:
            if self.button1.click(pos):
                not_menu = False
            if self.button1.clicked:
                if self.drop_menu.click(pos):
                    not_menu = False
            if self.drop_menu.buttons[1].clicked:
                if self.load_menu.click(pos):
                    self.loadmap()
            if not_menu:
                if self.drop_menu.buttons[2].clicked:
                    self.find_tile(pos, self.palette, self.menu)
                elif self.show_foreground > 0:
                    self.find_tile(pos, self.menu, self.map2)
                else:
                    self.find_tile(pos, self.menu, self.map1)
        if button == 3:
            self.right_m_button = True
            self.right_m_pos = pos

    def mouse_up(self, button, pos):
        if button == 3:
            self.right_m_button = False
            self.right_m_pos = pos
            new_rect = self._invert_rect(self.m_select_rect)

            if self.show_foreground < 0:
                self.group_select(new_rect, self.map1.group)
            else:
                self.group_select(new_rect, self.map2.group)

    def mouse_motion(self, button, pos, rel):
        self.m_pos = pos

    def mouse_select(self):
        if self.right_m_button:
            old_pos = (self.right_m_pos[0] - self.map1.xy[0], self.right_m_pos[1] - self.map1.xy[1])
            new_pos = (self.m_pos[0] - self.map1.xy[0], self.m_pos[1] - self.map1.xy[1])
            self.m_select_rect = pg.Rect(1,1,1,1)
            xoff, yoff = new_pos[0] - old_pos[0], new_pos[1] - old_pos[1]
            self.m_select_rect.inflate_ip(xoff, yoff)
            self.m_select_rect.topleft = old_pos

    def _invert_rect(self, rect):
            new_rect = pg.Rect(1,1,1,1)
            new_rect.size = rect.size
            if rect.width < 0:
                new_rect.width *= -1
            if rect.height < 0:
                new_rect.height *= -1
            if rect.left > rect.right:
                new_rect.left = rect.right
            else:
                new_rect.left = rect.left
            if rect.top > rect.bottom:
                new_rect.top = rect.bottom
            else:
                new_rect.top = rect.top
            return new_rect

###################### Button Activated Methods ################################

    def group_select(self, rect, group):
        for sprite in group:
            if sprite.rect.colliderect(rect):
                self.change_tile(sprite)

    def find_tile(self, pos, menu, bg_map):
        found = False
        for tile in menu.group:
            map_pos = (pos[0] - menu.xy[0], pos[1] - menu.xy[1])
            if tile.rect.collidepoint(map_pos):
                found = True
                menu.fill = True
                menu.selected = tile
                self.current_tile = tile
        if not found:
            for tile in bg_map.group:
                map_pos = (pos[0] - bg_map.xy[0], pos[1] - bg_map.xy[1])
                if tile.rect.collidepoint(map_pos):
                    self.change_tile(tile)
                    bg_map.clear_map()

    def change_tile(self, tile):
        if self.current_tile != None:
            tile.filename = self.current_tile.filename
            tile.image = self.current_tile.image
            tile.dirty = 1

    def savemap(self):
        size = tuple_mult((40,40), self.block)
        save = SaveMap("savemap", size, self.block, "./img/magecity_64p.png",
                        self.map1.group, self.map2.group)
        save.write_to_file()
        self.floating_text.set_text("Map Saved", True)

    def loadmap(self):
        select = None
        for button in self.load_menu.buttons:
            if button.clicked:
                select = button.text
        if select != None:
            load = LoadMap(select)
            self.map1.group = load.bg_group
            self.map2.group = load.fg_group
            self.floating_text.set_text("Map Loaded", True)
Ejemplo n.º 41
0
class PhoneBook(gtk.Window):
    'the contact widget holding all contacts'

    def __init__(self, contact = None):
        super(PhoneBook, self).__init__()
        self.set_size_request(444, 300)
        self.set_border_width(10)
        self.set_title('Contact Information')
        self.set_icon_from_file(ICON_PATH + '/contact.png')
        self.set_decorated(True)
        self.set_modal(True)
        self.set_position(gtk.WIN_POS_MOUSE)
        self.entry_list = []
        label = gtk.Label()
        label.set_markup('<span font_desc="belgrano 11">Name : </span>')
        label.set_justify(gtk.JUSTIFY_LEFT)
        self.entry_list.append(gtk.Entry())
        def left_strip_name(entry):
            entry.set_text(entry.get_text().lstrip())
        self.entry_list[0].connect("changed", left_strip_name)
        self.entry_list[0].modify_font(pango.FontDescription('belgrano'))
        h_box = gtk.HBox()
        h_box.pack_start(label)
        h_box.pack_start(self.entry_list[-1])
        alignment = gtk.Alignment(0.5, 0, 0, 0)
        alignment.add(h_box)
        v_box = gtk.VBox(False, 4)
        v_box.pack_start(alignment)
        self.__add_button = Button(ICON_PATH + '/add.png', 'add contact', 20,
                                   20)
        self.__remove_button = Button(ICON_PATH + '/remove.png',
                                      'remove contact', 20, 20)
        self.__default_button = Button(ICON_PATH + '/default.png',
                                       'set default', 20, 20)
        h_box = gtk.HBox(False, 10)
        label = gtk.Label()
        label.set_markup('<span font_desc="belgrano 10" foreground="#ffffff">\
<b>Default No</b> :</span>')
        h_box.pack_start(label)
        self.entry_list.append(gtk.Entry())
        self.entry_list[-1].connect("changed", self.__check_num)
        self.entry_list[-1].modify_font(pango.FontDescription('CrashNumberingGothic'))
        self.entry_list[-1].set_max_length(10)
        h_box.pack_start(self.entry_list[-1])
        h_box.pack_start(self.__add_button)
        alignment = gtk.Alignment(0, 0, 0, 0)
        alignment.add(h_box)
        vbox = gtk.VBox(True, 4)
        vbox.pack_start(alignment)
        alignment = gtk.Alignment(0, 0, 0, 0)
        alignment.add(vbox)
        alignment.set_border_width(8)
        scroll = gtk.ScrolledWindow()
        scroll.set_size_request(420, 180)
        scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        scroll.add_with_viewport(alignment)
        scroll.set_border_width(8)
        self.__add_button.connect("clicked", self.__add_entry, vbox)
        self.__remove_button.connect("clicked", self.__remove_entry, vbox)
        self.__default_button.connect("clicked", self.__change_default)
        frame = gtk.Frame('Contact Numbers')
        frame.get_label_widget().modify_font(pango.FontDescription('belgrano'))
        frame.set_label_align(0.5, 0.5)
        frame.set_shadow_type(gtk.SHADOW_IN)
        self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ffffff'))
        frame.get_label_widget().set_sensitive(False)
        frame.add(scroll)
        scroll.get_child().modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(
                                                                  '#000000'))
        v_box.pack_start(frame)
        save = Button(ICON_PATH + '/save.png', 'Save')
        cancel = Button(ICON_PATH + '/cancel.png', 'Cancel')
        save.connect("clicked", self.__save)
        cancel.connect("clicked", self.__cancel)
        h_box = gtk.HBox(True, 8)
        h_box.pack_start(cancel)
        h_box.pack_start(save)
        alignment = gtk.Alignment(1, 0.5, 0, 1)
        alignment.add(h_box)
        v_box.pack_start(alignment)
        self.__count = 1
        self.add(v_box)
        self.connect('destroy', gtk.main_quit)
        self.set_resizable(False)
        if contact:
            for text in contact[2:]:
                if text:
                    self.__add_button.emit('clicked')
            for index in range(len(contact)):
                if contact[index]:
                    self.entry_list[index].set_text(contact[index])
        self.show_all()

    def __save(self, unused):
        'saves the contact details'

        def show_message(msg_type, msg_format, text, button =
                         gtk.BUTTONS_CLOSE):
            '''
            shows warning/error messages if
            anything goes wrong in contact info
            '''

            def set_flag(unused_button):
                '''
                sets the flag to overwrite same
                contact name with newer details
                '''

                self.__over_write = True
                return False
            self.__over_write = False
            message = gtk.MessageDialog(type = msg_type, message_format =
                                        msg_format, buttons = button)
            message.format_secondary_markup(text)
            message.set_icon_from_file(ICON_PATH + '/contact.png')
            if button == gtk.BUTTONS_YES_NO:
                message.get_child().get_children()[-1].get_children()[0].\
                                            connect('clicked', set_flag)
            message.run()
            message.destroy()
        if not self.entry_list[0].get_text():
            show_message(gtk.MESSAGE_ERROR, 'ERROR', '<span font_desc=\
"belgrano 12">Name can not be empty</span>')
            return False
        elif not self.entry_list[1].get_text():
            show_message(gtk.MESSAGE_ERROR, 'ERROR', '<span font_desc="primitiv\
e 12"><span foreground="#3EA9DC"><b>' + self.entry_list[0].get_text() + \
'</b></span> must have a default number</span>')
            return False
        else:
            faulty = []
            for entry in range(1, len(self.entry_list)):
                if len(self.entry_list[entry].get_text()) < 10:
                    faulty.append(entry)
            if faulty:
                text = '<span font_desc="belgrano 12">The following contact(s)\
 has(have) less than 10 digits :\n'
                for index in faulty:
                    if index == 1:
                        text += '<b>default</b>\n'
                    else:
                        text += '#<b>' + str(index) + '</b>\n'
                text += '</span>'
                show_message(gtk.MESSAGE_ERROR, 'ERROR', text)
                return False
        values = [self.entry_list[1].get_text(), self.entry_list[0].get_text()]
        for entry in self.entry_list[2:]:
            values.append(entry.get_text())
        values = tuple(values)
        from database import DataBase
        database = DataBase()
        if database.row_count('contacts', self.entry_list[1].get_text()):
            show_message(gtk.MESSAGE_WARNING, 'WARNING', '<span font_desc="belgrano 12">Number <span foreground="#0000FF"><b>' + \
self.entry_list[1].get_text() + '</b></span> is already in use for <span foreground="#FF0000"><b>%s</b></span>\n\nOverwrite the \
details for <span foreground="#077E11"><b>%s</b></span> ?</span>' % (database.select('contacts', self.entry_list[1].get_text())[0][0],
self.entry_list[0].get_text()), gtk.BUTTONS_YES_NO)
            if self.__over_write:
                database.update('contacts', values)
                database.close()
                self.destroy()
        else:
            database.update('contacts', values)
            database.close()
            self.destroy()

    def __cancel(self, unused_button):
        'cancels all the informations for a contact'

        self.destroy()

    def __check_num(self, entry):
        'forces the characters in the entry field to be digits only'

        text = entry.get_text().strip()
        entry.set_text(''.join([i for i in text if i in '0123456789']))

    def __remove_entry(self, unused, vbox):
        'removes a contact number field'

        self.__count -= 1
        hbox = self.__remove_button.parent
        alignment = hbox.parent
        remove_list = self.__remove_button.parent.get_children()
        for item in remove_list:
            item.hide()
            hbox.remove(item)
        remove_list[0].destroy()
        remove_list[1].destroy()
        self.entry_list.pop()
        alignment.remove(hbox)
        hbox.destroy()
        alignment.destroy()
        hbox = vbox.get_children()[-1].get_children()[0]
        hbox.pack_start(self.__add_button)
        if self.__count > 1:
            hbox.pack_start(self.__remove_button)
        hbox.show_all()

    def __add_entry(self, unused, vbox):
        'adds a new field for a new contact number'

        def cursor_enter(unused_entry, unused_event, hbox):
            'places the default button next to the field whenever cursor enters the field'

            if self.__default_button.parent:
                self.__default_button.parent.remove(self.__default_button)
            hbox.pack_start(self.__default_button)
            self.__default_button.show()
        if self.__count > 1:
            self.__remove_button.hide()
            self.__remove_button.parent.remove(self.__remove_button)
        h_box = gtk.HBox(False, 10)
        self.entry_list.append(gtk.Entry())
        self.entry_list[-1].connect("changed", self.__check_num)
        self.entry_list[-1].modify_font(pango.FontDescription('CrashNumberingGothic'))
        self.entry_list[-1].connect("enter-notify-event", cursor_enter, h_box)
        self.entry_list[-1].set_max_length(10)
        self.__add_button.hide()
        self.__add_button.parent.remove(self.__add_button)
        label = gtk.Label()
        label.set_markup('<span font_desc="belgrano 11"foreground = "#ffffff">\
Contact #%02d :</span>' % (self.__count + 1))
        h_box.pack_start(label)
        h_box.pack_start(self.entry_list[-1])
        h_box.pack_start(self.__add_button)
        h_box.pack_start(self.__remove_button)
        alignment = gtk.Alignment(0, 0, 0, 0)
        alignment.add(h_box)
        vbox.pack_start(alignment)
        alignment.show_all()
        self.__count += 1

    def __change_default(self, unused):
        'swaps the focused contact number with the default number'

        entry = self.__default_button.parent.get_children()[1]
        temp = entry.get_text()
        entry.set_text(self.entry_list[1].get_text())
        self.entry_list[1].set_text(temp)
        return False
Ejemplo n.º 42
0
class Main(Template):
    def __init__(self, size):
        Template.__init__(self, size)
        self.name = "World Editor 1.1"
        self.size = size
        self.block = 32
        self.dt = 0.
        self.empty_tile = pg.image.load("./tiles/Empty_tile_32p.png").convert_alpha()
        self.map_bg = Map("Background", self, self.size, (120,80), self.block, self.empty_tile)
        self.map_mg = Map("Middleground", self, self.size, (120,80), self.block, self.empty_tile)
        self.map_fg = Map("Foreground", self, self.size, (120,80), self.block, self.empty_tile)
        self.poi_map = Map("POI Map", self, self.size, (120,80), self.block, self.empty_tile)
        self.poi_menu = Map("POI Menu", self, self.size, (4,1), self.block, self.empty_tile)
        self.menus = [Map("Menu", self, self.size, (2,14), self.block, self.empty_tile)]
        self.pal_menu = Menu((128, 40), (0,21))
        self.pal_menu.add_buttons(2, ["New", "Pal-1"])
        self.pal_menu.set_bg_color(SUBBUTTON_COLOR)
        self.menu = self.menus[0]
        self.menu.xy[1] += 20
        self.men_list = []
        self.sprite_map = self.setup_spritemap()
        self.sprite_map.xy = [250,0]
        self.clip = pg.Rect(0,0, self.size[0],self.size[1])
        self.c_pos = self.clip.topleft
        self.show_full_map = False
        self.show_poi = False
        self.full_map = None
        self.current_tile = None
        self.current_menu = None
        self.ground_state = None
        self.right_m_pos = None
        self.right_m_button = False
        self.fill = False
        self.m_pos = None
        self.m_select_rect = pg.Rect(1,1,1,1)
        self.menu_button = Button((120, 20), (129,1), "Menu")
        self.pal_button = Button((128,20), (0,0), "Palette")
        self.drop_menu = Menu((120, 160), (129, 21))
        self.drop_menu.add_buttons(5, ["Save", "Load", "Sprites", "See Map", "Info"])
        self.drop_menu.set_bg_color(SUBBUTTON_COLOR)
        self.load_menu = self.setup_loadmenu()
        self.floating_text = FloatingText("no text", self.size)
        self.info_panel = Panel((self.size[0] - self.size[0]/3, self.size[1] - self.size[1]/3), (self.size[0]/6, self.size[1]/6))
        self.info_panel.setup_text([self.name, "Made by Aurelio Aguirre", "", "Use WASD to move around.", "Use E to toggle the Foreground.", "Use R to toggle the Middleground.", "Use Q to toggle the Point of Interest map."])
        self.setup()
        self.setup_poi()
        self.selected_map = self.map_bg
        self.alternative = ALTERNATIVE_MODE
        self.enable_alternative_mode()

    def update(self, dt):
        self.dt = dt
        self.map_bg.update(dt)
        if not self.alternative:
            self.map_fg.update(dt)
            self.map_mg.update(dt)
            self.sprite_map.update(dt)
            self.menu.update(dt)
        self.poi_map.update(dt)
        self.poi_menu.update(dt)
        self.floating_text.update(dt)
        if self.drop_menu.buttons[0].active:
            self.savemap()
            self.drop_menu.buttons[0].active = False
        if self.drop_menu.buttons[2].active:
            self.selected_map = self.sprite_map
        else:
            self.selected_map = self.map_bg
        if not self.alternative:
            if self.pal_button.active:
                if self.pal_menu.clickinfo != None:
                    if self.pal_menu.clickinfo == "New":
                        self.new_palette()
                    else:
                        self.switch_palette(text=self.pal_menu.clickinfo)
                    self.pal_menu.clickinfo = None
        if self.map_bg.clipped:
            self.map_fg.map.set_clip()
            self.map_mg.map.set_clip()
            self.poi_map.map.set_clip()
            self.map_bg.clipped = False
        if self.c_pos != self.clip.topleft:
            self.c_pos = (self.c_pos[0] - self.map_bg.xy[0], self.c_pos[1] - self.map_bg.xy[1])
            self.clip.topleft = self.c_pos
        self.menu_button.update(self.dt)
        self.mouse_select()

    def draw(self):
        self.screen.fill(BLACK)

        # MAPs
        # Background
        self.map_bg.draw(self.screen, self.clip)
        if not self.alternative:
            # Middleground
            if self.ground_state == "MG":
                self.map_mg.xy = self.map_bg.xy
                self.map_mg.draw(self.screen, self.clip)

            # Foreground
            if self.ground_state == "FG":
                self.map_fg.xy = self.map_bg.xy
                self.map_fg.draw(self.screen, self.clip)

        # POI Map
        if self.show_poi:
            self.poi_map.xy = self.map_bg.xy
            self.poi_map.draw(self.screen, self.clip)

        # GUI
        if not self.alternative:
            self.menu.draw(self.screen)
        if self.show_poi:
            self.poi_menu.draw(self.screen)
        self.menu_button.draw(self.screen)
        if not self.alternative:
            self.pal_button.draw(self.screen)
        if self.menu_button.active:
            self.drop_menu.draw(self.screen)
        if self.pal_button.active:
            self.pal_menu.draw(self.screen)
        if self.drop_menu.buttons[1].active:
            self.load_menu.draw(self.screen)
        if self.drop_menu.buttons[2].active:
            self.sprite_map.draw(self.screen)
        if self.right_m_button:
            screen_rect = self.m_select_rect.copy()
            screen_rect.x += self.map_bg.xy[0]
            screen_rect.y += self.map_bg.xy[1]
            pg.draw.rect(self.screen, WHITE, screen_rect, 1)
        if self.show_full_map:
            if self.full_map:
                self.screen.blit(self.full_map, (0,0))
        self.info_panel.draw(self.screen)
        self.floating_text.draw(self.screen)

########################## Setup methods #######################################

    def enable_alternative_mode(self):
        if self.alternative:
            bgimage = pg.image.load("./img/CI Main 128.png").convert_alpha()
            self.map_bg = Map("Static Image", self, self.size, (120,80), 128, bgimage)
            self.map_bg.setup(BG_COLOR, alt=True)
            self.alternative = True

    def setup_loadmenu(self):
        folder = Path("./save")
        filelist = [f.basename() for f in folder.files("*.sav")]
        amount = len(filelist)
        menu = Menu((240, amount*21), (250, 21))
        menu.add_buttons(amount, filelist)
        menu.set_bg_color(WHITE)
        return menu

    def setup(self):
        self.map_bg.setup(BG_COLOR)
        self.map_fg.setup(FG_COLOR, 200)
        self.map_mg.setup(MG_COLOR, 200)
        self.menu.setup(PAL_COLOR)
        self.poi_map.setup(POI_MAP, alpha=150)
        self.poi_menu.setup(POI_MENU)

    def setup_poi(self):
        wall = pg.image.load("./tiles/Wall32.png").convert_alpha()
        door = pg.image.load("./tiles/Door32.png").convert_alpha()
        poi = pg.image.load("./tiles/POI32.png").convert_alpha()
        delete = pg.image.load("./tiles/Eliminate32.png").convert_alpha()
        self.poi_dict = OrderedDict((("Poi Wall", wall), ("Poi Door", door), ("Poi Symbol", poi), ("Delete", delete)))
        p = [i for i in self.poi_dict.keys()]
        for num, tile in enumerate(self.poi_menu.group):
            tile.image = self.poi_dict[p[num]]
            tile.rect = tile.image.get_rect()
            tile.rect.topleft = ((self.block*num), 1)
            tile.filename = p[num]
            tile.dirty = 1
        xplace = self.size[0] - self.block*4
        self.poi_menu.xy = [xplace, 1]

    def setup_spritemap(self):
        sheet = SpriteSheet("img/magecity_64p.png", 64, (0,0), (8,44))
        self.men_list = sum(sheet.image_list, [])
        length = len(self.men_list)
        size = (10, int(length/10))
        menu = Map("Palette", self, self.size, size, self.block, self.empty_tile)
        menu.setup(WHITE)
        for i, tile in enumerate(menu.group):
            tile.filename = "{}".format(i)
            tile.image = self.men_list[i]
            if i+1 >= length:
                break
        return menu

#################### Key and Mouse Methods #####################################

    def key_down(self, key):
        if key == K_ESCAPE:
            print("Quitting...")
            self.game_on == False
            self.end_game()

        if key == K_e:
            if self.ground_state == None or self.ground_state == "MG":
                self.ground_state = "FG"
            else:
                self.ground_state = None

        if key == K_r:
            if self.ground_state == None or self.ground_state == "FG":
                self.ground_state = "MG"
            else:
                self.ground_state = None

        if key == K_q:
            self.show_poi = not self.show_poi
            self.current_tile = None

        if key in (K_w, K_UP):
            self.selected_map.move["up"] = True
        if key in (K_a, K_LEFT):
            self.selected_map.move["left"] = True
        if key in (K_s, K_DOWN):
            self.selected_map.move["down"] = True
        if key in (K_d, K_RIGHT):
            self.selected_map.move["right"] = True

    def key_up(self, key):
        if key in (K_w, K_UP):
            self.selected_map.move["up"] = False
        if key in (K_a, K_LEFT):
            self.selected_map.move["left"] = False
        if key in (K_s, K_DOWN):
            self.selected_map.move["down"] = False
        if key in (K_d, K_RIGHT):
            self.selected_map.move["right"] = False

    def mouse_down(self, button, pos):
        not_menu = True
        if button == 1:
            # First we check for the unique states, Info Panel and Full Map.
            if not self.info_panel.display:
                if not self.show_full_map:
                    # Now we check for menu buttons being clicked, and switch our
                    # not_menu switch if they are. From here the rest is handled by update.
                    if self.menu_button.click(pos):
                        not_menu = False
                    elif self.pal_button.click(pos):
                        not_menu = False
                    if self.menu_button.active:
                        if self.drop_menu.click(pos):
                            not_menu = False
                    if self.pal_button.active:
                        if self.pal_menu.click(pos):
                            not_menu = False
                    # Assuming we are in our main menu we check for the the buttons being clicked.
                    # This part is allowed to happen WHILE maps are also being manipulated. (not_menu is not switched)
                    if self.drop_menu.buttons[1].active:
                        if self.load_menu.click(pos):
                            self.loadmap(self.load_menu.clickinfo)
                    elif self.drop_menu.buttons[3].active:
                        self.show_map()
                        self.drop_menu.buttons[3].active = False
                    elif self.drop_menu.buttons[4].active:
                        self.info_panel.display_panel()
                        self.drop_menu.buttons[4].active = False
                    # Here we look for our Maps. Basically we are moving a tile from one map to another.
                    # We just need to pick the right one, and they should all overwrite each other.
                    # In other words, only one map is active at a time.
                    if not_menu:
                        if self.drop_menu.buttons[2].active: # Tiles are showing.
                            self.find_tile(pos, self.sprite_map, self.menu)
                        elif self.show_poi: # POI Map is up.
                            self.find_tile(pos, self.poi_menu, self.poi_map)
                        elif self.ground_state == "FG": # we are on the Foreground map.
                            self.find_tile(pos, self.menu, self.map_fg)
                        elif self.ground_state == "MG": # We are on the middleground map.
                            self.find_tile(pos, self.menu, self.map_mg)
                        else: # We default to the Background map.
                            self.find_tile(pos, self.menu, self.map_bg)
                else:
                    # While the full map is up, any left mouse click will deactivate it.
                    self.show_full_map = False
            else:
                self.info_panel.click(pos)

        if button == 3:
            if not self.show_full_map:
                self.right_m_button = True
                self.right_m_pos = pos
            else:
                self.take_image(self.full_map)

    def mouse_up(self, button, pos):
        if button == 3:
            self.right_m_button = False
            self.right_m_pos = pos
            new_rect = self._invert_rect(self.m_select_rect)

            if self.show_poi:
                self.group_select(new_rect, self.poi_map.group)
            elif self.ground_state == "FG":
                self.group_select(new_rect, self.map_fg.group)
            elif self.ground_state == "MG":
                self.group_select(new_rect, self.map_mg.group)
            else:
                self.group_select(new_rect, self.map_bg.group)

    def mouse_motion(self, button, pos, rel):
        self.m_pos = pos

    def mouse_select(self):
        if self.right_m_button:
            old_pos = (self.right_m_pos[0] - self.map_bg.xy[0], self.right_m_pos[1] - self.map_bg.xy[1])
            new_pos = (self.m_pos[0] - self.map_bg.xy[0], self.m_pos[1] - self.map_bg.xy[1])
            self.m_select_rect = pg.Rect(1,1,1,1)
            xoff, yoff = new_pos[0] - old_pos[0], new_pos[1] - old_pos[1]
            self.m_select_rect.inflate_ip(xoff, yoff)
            self.m_select_rect.topleft = old_pos

    def _invert_rect(self, rect):
            new_rect = pg.Rect(1,1,1,1)
            new_rect.size = rect.size
            if rect.width < 0:
                new_rect.width *= -1
            if rect.height < 0:
                new_rect.height *= -1
            if rect.left > rect.right:
                new_rect.left = rect.right
            else:
                new_rect.left = rect.left
            if rect.top > rect.bottom:
                new_rect.top = rect.bottom
            else:
                new_rect.top = rect.top
            return new_rect

###################### Button Activated Methods ################################

    def group_select(self, rect, group):
        for sprite in group:
            if sprite.rect.colliderect(rect):
                self.change_tile(sprite)

    def find_tile(self, pos, menu, bg_map):
        found = False
        for tile in menu.group:
            map_pos = (pos[0] - menu.xy[0], pos[1] - menu.xy[1])
            if tile.rect.collidepoint(map_pos):
                found = True
                menu.fill = True
                menu.select_rect(tile.rect)
                menu.draw_border = True
                self.current_tile = tile
                self.current_menu = menu.name
            if found:
                break
        if not found:
            for tile in bg_map.group:
                map_pos = (pos[0] - bg_map.xy[0], pos[1] - bg_map.xy[1])
                if tile.rect.collidepoint(map_pos):
                    self.change_tile(tile)
                    bg_map.clear_map()
        return found

    def change_tile(self, tile):
        if self.current_tile != None:
            if self.current_tile.filename != "Delete":
                tile.filename = self.current_tile.filename
                tile.image = self.current_tile.image
                tile.dirty = 1
            else:
                print("Removing Tile!")
                tile.filename = "Empty_tile"
                tile.image = self.empty_tile
                tile.dirty = 1

    def new_palette(self):
        self.menus.append(Map("Menu", self, self.size, (2,14), self.block, self.empty_tile))
        self.menus[-1].setup(WHITE)

        size = self.pal_menu.size
        self.pal_menu.change_size((size[0], size[1]+20))
        num = len(self.menus)
        self.pal_menu.add_buttons(1, ["Pal-{}".format(num)])
        self.switch_palette(ind=-1)

    def switch_palette(self, ind=None, text=None):
        if ind:
            self.menu = self.menus[ind]
        elif text:
            self.menu = self.menus[int(text[-1])-1]

# <-------This Needs adjustment, needs to differentiate between Layers-------->
    def show_map(self):
        full_map = pg.Surface((40*64, 40*64))
        for tile in self.map_bg.group:
            full_map.blit(tile.image, tile.rect.topleft)
        for tile in self.map_mg.group:
            if tile.filename != "Empty_tile":
                full_map.blit(tile.image, tile.rect.topleft)
        for tile in self.map_fg.group:
            if tile.filename != "Empty_tile":
                full_map.blit(tile.image, tile.rect.topleft)
        self.full_map = pg.transform.smoothscale(full_map, self.size)
        self.show_full_map = True

    def take_image(self, surf):
        folder = Path("./image")
        amount = len(folder.files("*.jpg"))
        filename = "{}{}{}{}".format(folder, "/map", amount, ".jpg")
        pg.image.save(surf, filename)

    def savemap(self):
        if not self.alternative:
            saving = SaveMap()
            saving.add_map(self.map_bg)
            saving.add_map(self.map_mg)
            saving.add_map(self.map_fg)
            saving.add_map(self.poi_map)
            saving.write_to_file()
        else:
            saving = SaveMap()
            saving.add_map(self.poi_map)
            saving.write_to_file()

    def loadmap(self, filename):
        load = LoadMap(filename)
        maplist = []
        for m in load.maps.values():
            a_map = Map(m["info"]["name"], self, m["info"]["size"], m["info"]["grid"], m["info"]["block"], self.empty_tile)
            if m["info"]["name"] == "Foreground" or m["info"]["name"] == "Middleground":
                a_map.setup(m["info"]["color"], 200)
            elif m["info"]["name"] == "POI Map":
                a_map.setup(m["info"]["color"], 150)
            else:
                a_map.setup(m["info"]["color"])
            for t in a_map.group:
                for i in m["tiles"]:
                    if list(t.rect.topleft) in m["tiles"][i]:
                        t.filename = i
                        if i[0] == "P":
                            t.image = self.poi_dict[i]
                            t.dirty = 1
                        else:
                            t.image = self.men_list[int(i)]
                            t.dirty = 1
            maplist.append(a_map)
        for j in maplist:
            if j.name == "Background":
                self.map_bg = j
            if j.name == "Middleground":
                self.map_mg = j
            if j.name == "Foreground":
                self.map_fg = j
            if j.name == "POI Map":
                self.poi_map = j
        print("Loading from file...")
Ejemplo n.º 43
0
    def __init__(self):
        super(AccountManager, self).__init__()
        self.set_size_request(260, 220)
        self.set_modal(True)
        self.set_title('Account Manager')
        self.set_icon_from_file(ICON_PATH + '/admin.png')
        vbox = gtk.VBox(True, 4)
        scroll = gtk.ScrolledWindow()
        scroll.set_size_request(140, -1)
        scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        scroll.set_border_width(8)
        alignment = gtk.Alignment(0.5, 0, 0, 0)
        alignment.set_border_width(8)
        from database import DataBase
        database = DataBase()
        users = database.get_user()
        def mark_default(radio):
            'mark the default user bold faced'

            for radio in radio.get_group():
                if radio.get_active():
                    number = radio.get_label()
                    radio.get_child().set_markup('<span font_desc="CrashNumberingGothic">\
<b>' + number + '</b></span>')
                    continue
                radio.get_child().set_markup('<span font_desc="CrashNumberingGothic">' +
                                             radio.get_label() + '</span>')
            return
        radio = gtk.RadioButton(None, str(users[0][0]))
        radio.connect('toggled', mark_default)
        vbox.pack_start(radio)
        for user in users[1:]:
            vbox.pack_start(gtk.RadioButton(radio, str(user[0])))
        default_user = str(database.get_default()[0])
        database.close()
        for radio in radio.get_group():
            if radio.get_label() == default_user:
                radio.set_active(True)
                break
        mark_default(radio)
        alignment.add(vbox)
        scroll.add_with_viewport(alignment)
        scroll.get_child().modify_bg(gtk.STATE_NORMAL,
                                     gtk.gdk.color_parse('#ffffff'))
        vbox = gtk.VBox(False, 4)
        vbox.pack_start(scroll, True, True)
        hbox = gtk.HBox(True, 10)
        add = Button(ICON_PATH + '/add-account.png', 'Add New Account', 30, 30)
        add.connect('clicked', self.__add_user, radio, vbox)
        remove = Button(ICON_PATH + '/remove-account.png', 'Remove Account',
                        30, 30)
        remove.connect('clicked', self.__remove_user, radio, vbox)
        save = Button(ICON_PATH + '/save.png', 'Save Account\n Information',
                      30, 30)
        save.connect('clicked', self.__save, radio)
        hbox.pack_start(add)
        hbox.pack_start(remove)
        alignment = gtk.Alignment(0.5, 0, 0, 0)
        alignment.add(hbox)
        vbox.pack_start(alignment, False, False)
        alignment = gtk.Alignment(0.5, 0, 0, 0)
        alignment.add(save)
        vbox.pack_start(alignment, False, False)
        self.add(vbox)
        self.connect('destroy', self.__save, radio)
        self.show_all()
Ejemplo n.º 44
0
class ChangeState(PopupBox):
    """
    """
    globalHash = ''
    def __init__(self, text, Thash, handler=None, handler_message=None, default_choice=0,
                 x=None, y=None, width=0, height=0, icon=None, vertical_expansion=1,
                 text_prop=None, parent='osd'):

        PopupBox.__init__(self, text, handler, x, y, width, height, icon, vertical_expansion, text_prop, parent)
        self.globalHash = Thash
        self.handler_message = handler_message

        # XXX: It may be nice if we could choose between
        #      OK/CANCEL and YES/NO
        s = xmlrpclib.ServerProxy(config.RPCHOST)
        if (s.d.is_active(self.globalHash) == 1) ^ (s.d.is_hash_checking(self.globalHash) == 1):
            self.b0 = Button(_('Stop'), width=(self.width-60)/2)
        else:
            self.b0 = Button(_('Start'), width=(self.width-60)/2)
        self.b0.set_h_align(Align.NONE)
        self.add_child(self.b0)

        self.b1 = Button(_('Erase'), width=(self.width-60)/2)
        self.b1.set_h_align(Align.NONE)
        self.add_child(self.b1)

        self.b2 = Button(_('Cancel'), width=(self.width-60)/2)
        self.b2.set_h_align(Align.NONE)
        self.add_child(self.b2)

        select = 'self.b%s.toggle_selected()' % default_choice
        eval(select)


    def send_enter_event(self):
        self.eventhandler(INPUT_ENTER)


    def eventhandler(self, event):
        if event in (INPUT_LEFT, INPUT_UP):
            if self.b0.selected:
                self.b0.toggle_selected()
                self.b2.toggle_selected()
            elif self.b1.selected:
                self.b1.toggle_selected()
                self.b0.toggle_selected()
            else:
                self.b1.toggle_selected()
                self.b2.toggle_selected()
            self.draw()
            return

        elif event in (INPUT_RIGHT, INPUT_DOWN):
            if self.b0.selected:
                self.b1.toggle_selected()
                self.b0.toggle_selected()
            elif self.b1.selected:
                self.b1.toggle_selected()
                self.b2.toggle_selected()
            else:
                self.b0.toggle_selected()
                self.b2.toggle_selected()
            self.draw()
            return

        elif event == INPUT_EXIT:
            self.destroy()

        elif event == INPUT_ENTER:
            if self.b0.selected:
                s = xmlrpclib.ServerProxy(config.RPCHOST)
                if (s.d.is_active(self.globalHash) == 1) ^ (s.d.is_hash_checking(self.globalHash) == 1):
                    s.d.stop(self.globalHash)
                else:
                    s.d.start(self.globalHash)
                rc.post_event(em.MENU_BACK_ONE_MENU)
                self.destroy()

            elif self.b1.selected:
                s = xmlrpclib.ServerProxy(config.RPCHOST)
                s.d.erase(self.globalHash)
                self.destroy()
                rc.post_event(em.MENU_BACK_ONE_MENU)

            else:
                self.destroy()

        else:
            return self.parent.eventhandler(event)