Пример #1
0
class Main:
    def __init__(self, parse, name=""):
        init()
        display.init()
        self.DIMS = (display.Info().current_w, display.Info().current_h)
        self.BG = Surface(self.DIMS)
        self.SCREEN = display.set_mode(self.DIMS, -2147483648)
        self.MANAGER = UIManager(self.DIMS)
        set_visible(True)
        update()
        Exit((0, 0), self.MANAGER)
        clear = Clear((0, 30), self.MANAGER)
        Spawn((0, 60), self.MANAGER, clear, self.DIMS, parse, name)
        Killer((0, 90), self.MANAGER, clear)
        Paint((0, 120), self.MANAGER)
        self.clock = Clock()
        while True:
            self.process_events()

    def process_events(self):
        for event in get():
            if event.type == 32774 and event.user_type == 17:
                self.BG.fill(event.colour[:-1])
            self.MANAGER.process_events(event)
        self.MANAGER.update(self.clock.tick(60) / 1000)
        self.SCREEN.blit(self.BG, (0, 0))
        self.MANAGER.draw_ui(self.SCREEN)
        update()
Пример #2
0
def main_menu_loop(screen, game_clock, settings):
    frame_resolution = settings.frame_resolution
    game_frame_rate = settings.frame_rate

    gui_manager = UIManager(frame_resolution, main_theme)
    menu_graphics = retrieve('main_menu_graphics')

    start_button = elements.UIButton(
        relative_rect=Rect((frame_resolution[0] / 2 + 150, frame_resolution[1] / 2 + 50),
                           (400, 80)),
        text="Start Simulation",
        object_id="start_sim_button",
        manager=gui_manager)

    settings_button = elements.UIButton(
        relative_rect=Rect((frame_resolution[0] / 2 + 150, frame_resolution[1] / 2 + 130),
                           (400, 80)),
        text="Settings",
        object_id="settings_button",
        manager=gui_manager)

    screen.fill((179, 147, 0))  # This is the initial draw, we don't need to re render the menu graphics later
    screen.blit(menu_graphics, (0, 0))  # This ensures a decent fps

    # Main Game Loop
    while True:

        time_delta = game_clock.tick(game_frame_rate) / 1000.0
        gui_manager.update(time_delta)
        gui_manager.draw_ui(screen)

        display.update()
        for e in event.get():
            if e.type == QUIT:
                quit()
                exit()

            if e.type == USEREVENT:
                if e.user_type == 'ui_button_pressed':
                    if e.ui_element == start_button:
                        return 1
                    if e.ui_element == settings_button:
                        return 2

            gui_manager.process_events(e)
Пример #3
0
    def test_show_hide_rendering(self, _init_pygame, default_ui_manager,
                                 _display_surface_return_none):
        resolution = (400, 400)
        empty_surface = pygame.Surface(resolution)
        empty_surface.fill(pygame.Color(0, 0, 0))

        surface = empty_surface.copy()
        manager = UIManager(resolution)

        window = UIWindow(pygame.Rect(100, 100, 400, 400),
                          window_display_title="Test Window",
                          manager=manager,
                          visible=0)
        manager.update(0.01)
        manager.draw_ui(surface)
        assert compare_surfaces(empty_surface, surface)

        surface.fill(pygame.Color(0, 0, 0))
        window.show()
        manager.update(0.01)
        manager.draw_ui(surface)
        assert not compare_surfaces(empty_surface, surface)

        surface.fill(pygame.Color(0, 0, 0))
        window.hide()
        manager.update(0.01)
        manager.draw_ui(surface)
        assert compare_surfaces(empty_surface, surface)
Пример #4
0
def settings_loop(screen, game_clock, settings):
    def update_settings():
        data = {
            'map_size': int(map_size_dropdown.selected_option),
            'resolution':
            ast.literal_eval(resolution_dropdown.selected_option),
            'initial_hives': int(bee_hive_dropdown.selected_option),
            'initial_bees': int(bees_dropdown.selected_option),
            'flower_strat': flower_spawn_strat_dropdown.selected_option,
            'hive_strat': hive_spawn_strat_dropdown.selected_option,
            'music': music_dropdown.selected_option == 'True',
            'flower_num': int(flower_num_dropdown.selected_option)
        }
        new_settings = Settings(data)
        new_screen = display.set_mode(new_settings.frame_resolution, DOUBLEBUF)
        return 0, new_screen, new_settings

    frame_resolution = settings.frame_resolution
    game_frame_rate = settings.frame_rate

    gui_manager = UIManager(frame_resolution, main_theme)

    element_size = (150, 50)
    element_size_l = (250, 50)

    tooltip_size = (150, 25)
    tooltip_size_l = (250, 25)

    back_button = elements.UIButton(relative_rect=Rect((30, 30), (50, 50)),
                                    text='',
                                    object_id="back_button",
                                    manager=gui_manager)

    save_settings_button = elements.UIButton(relative_rect=Rect((30, 100),
                                                                (125, 50)),
                                             text="Save Settings",
                                             object_id="save_settings_button",
                                             manager=gui_manager)

    resolution_dropdown = elements.UIDropDownMenu(
        options_list=[
            '1920, 1080',
            '1536, 864',
            '1360, 768',
            '1280, 1024',
            '640, 360',
        ],
        starting_option=str(
            settings.frame_resolution)[1:len(str(settings.frame_resolution)) -
                                       1],
        relative_rect=Rect((200, 100), element_size),
        manager=gui_manager)
    resolution_tooltip = elements.UILabel(relative_rect=Rect((200, 75),
                                                             tooltip_size),
                                          text="Window Resolution",
                                          manager=gui_manager)

    map_size_dropdown = elements.UIDropDownMenu(
        options_list=['2000', '1000', '500'],
        starting_option=str(settings.map_size),
        relative_rect=Rect((200, 250), element_size),
        manager=gui_manager)
    map_size_tooltip = elements.UILabel(relative_rect=Rect((200, 225),
                                                           tooltip_size),
                                        text="Map Size",
                                        manager=gui_manager)

    music_dropdown = elements.UIDropDownMenu(
        options_list=["True", "False"],
        starting_option=str(settings.play_music),
        relative_rect=Rect((200, 400), element_size),
        manager=gui_manager)
    music_tooltip = elements.UILabel(relative_rect=Rect((200, 375),
                                                        tooltip_size),
                                     text="Play Music",
                                     manager=gui_manager)

    bee_hive_dropdown = elements.UIDropDownMenu(
        options_list=['2', '5', '10', '12', '20'],
        starting_option=str(settings.initial_hives),
        relative_rect=Rect((375, 100), element_size),
        manager=gui_manager)
    bee_hive_tooltip = elements.UILabel(relative_rect=Rect((375, 75),
                                                           tooltip_size),
                                        text="Number of Hives",
                                        manager=gui_manager)

    bees_dropdown = elements.UIDropDownMenu(
        options_list=['6', '8', '10', '12', '16', '20'],
        starting_option=str(settings.initial_bees_per_hive),
        relative_rect=Rect((375, 250), element_size),
        manager=gui_manager)
    bees_tooltip = elements.UILabel(relative_rect=Rect((375, 225),
                                                       tooltip_size),
                                    text="Initial Bees",
                                    manager=gui_manager)

    flower_spawn_strat_dropdown = elements.UIDropDownMenu(
        options_list=['normal distribution'],
        starting_option=settings.flower_spawn_strategy,
        relative_rect=Rect((550, 100), element_size_l),
        manager=gui_manager)
    flower_spawn_strat_tooltip = elements.UILabel(relative_rect=Rect(
        (550, 75), tooltip_size_l),
                                                  text="Flower Spawn Strategy",
                                                  manager=gui_manager)

    hive_spawn_strat_dropdown = elements.UIDropDownMenu(
        options_list=['default'],
        starting_option=settings.hive_spawn_strategy,
        relative_rect=Rect((550, 250), element_size_l),
        manager=gui_manager)
    hive_spawn_strat_tooltip = elements.UILabel(relative_rect=Rect(
        (550, 225), tooltip_size_l),
                                                text="Hive Spawn Strategy",
                                                manager=gui_manager)

    flower_num_dropdown = elements.UIDropDownMenu(
        options_list=['200', '300', '400', '500', '600', '700'],
        starting_option=str(settings.flower_num),
        relative_rect=Rect((550, 400), element_size_l),
        manager=gui_manager)

    music_tooltip = elements.UILabel(relative_rect=Rect((550, 375),
                                                        tooltip_size_l),
                                     text="Number of Flowers",
                                     manager=gui_manager)

    while True:
        screen.fill((219, 173, 92))
        time_delta = game_clock.tick(game_frame_rate) / 1000.0
        gui_manager.update(time_delta)
        gui_manager.draw_ui(screen)

        display.update()
        for e in event.get():
            if e.type == QUIT:
                quit()
                exit()

            if e.type == USEREVENT:
                if e.user_type == 'ui_button_pressed':
                    if e.ui_element == back_button:
                        return 0, screen, settings  # Returns back to main menu
                    elif e.ui_element == save_settings_button:
                        return update_settings()

            gui_manager.process_events(e)
Пример #5
0
class GuiMaster:
    def __init__(self, screen_resolution, entity_master, game_clock):
        self.gui_manager = UIManager(screen_resolution, main_theme)

        self.entity_master = entity_master
        self.game_clock = game_clock
        self.main_menu_active = False

        self.main_menu_button = elements.UIButton(relative_rect=Rect(
            (screen_resolution[0] - 112, screen_resolution[1] - 112),
            (110, 110)),
                                                  text='',
                                                  object_id="button_main_menu",
                                                  manager=self.gui_manager,
                                                  tool_tip_text="Menu")

        self.pause_button = elements.UIButton(relative_rect=Rect(
            (screen_resolution[0] - 200, screen_resolution[1] - 80), (70, 70)),
                                              text="pause",
                                              object_id="sim_button",
                                              manager=self.gui_manager,
                                              tool_tip_text="Pause Sim")

        self.exit_button = elements.UIButton(relative_rect=Rect(
            (10, screen_resolution[1] - 80), (70, 70)),
                                             text="exit",
                                             object_id="sim_button",
                                             manager=self.gui_manager,
                                             tool_tip_text="Exit Sim")
        self.drag_begin = None
        self.info_screen = self.build_info_display(screen_resolution)
        self.info_screen.kill()

    def update(self, time_delta):
        self.update_info_screen()
        self.gui_manager.update(time_delta)

    def draw_ui(self, screen):
        return self.gui_manager.ui_group.draw(screen)

    def process_events(self, event, camera):
        if event.type == MOUSEBUTTONUP:
            if not (event.button == 4 or event.button == 5):
                test_position = mouse.get_pos()
                test_position = test_position[
                    0] + camera.location.x, test_position[1] + camera.location.y
                selected_hive = self.entity_master.get_hive_at(test_position)
                if selected_hive is not None:
                    selected_hive.highlight()
            if event.button == 1:
                drag_end = Vector2(event.pos)
                drag_direction = self.drag_begin - drag_end
                camera.move(drag_direction)

        elif event.type == MOUSEBUTTONDOWN:
            if event.button == 1:
                mouse_x, mouse_y = event.pos
                self.drag_begin = Vector2(mouse_x, mouse_y)

            elif event.button == 4:
                camera.zoom_in()
            elif event.button == 5:
                camera.zoom_out()

        elif event.type == USEREVENT:
            if event.user_type == 'ui_button_pressed':
                if event.ui_element == self.main_menu_button:
                    self.deactivate_main_menu(
                    ) if self.main_menu_active else self.activate_main_menu()
                elif event.ui_element == self.pause_button:
                    self.unpause_sim(
                    ) if self.entity_master.sim_paused else self.pause_sim()
                elif event.ui_element == self.exit_button:
                    return 0  # Takes us back to the main menu

        self.gui_manager.process_events(event)

    def unpause_sim(self):
        self.entity_master.sim_paused = False

    def pause_sim(self):
        self.entity_master.sim_paused = True

    def activate_main_menu(self):
        self.main_menu_active = True
        self.gui_manager.get_sprite_group().add(self.info_screen)

    def deactivate_main_menu(self):
        self.main_menu_active = False
        self.info_screen.kill()

    def build_info_display(self, res):
        """
        Builds the ui element displaying the current state of the simulation
        :return: Menu render
        """
        number_of_bees = "Number of Bees: " + str(
            self.entity_master.bee_population)
        number_of_flowers = "Number of Flowers: " + str(
            self.entity_master.flower_population)
        fps_string = "Frames per Second: " + str(
            self.game_clock.get_fps())[0:4]

        return elements.UITextBox(html_text=number_of_bees + '<br><br>' +
                                  number_of_flowers + '<br><br>' + fps_string,
                                  relative_rect=Rect(res[0] - 201, 0, 200,
                                                     120),
                                  manager=self.gui_manager)

    def update_info_screen(self):
        """
        Updates all the parameters that have changed since last time and rebuilds
        :return: void
        """
        number_of_bees = "Number of Bees: " + str(
            self.entity_master.bee_population)
        number_of_flowers = "Number of Flowers: " + str(
            self.entity_master.flower_population)
        fps_string = "Frames per Second: " + str(
            self.game_clock.get_fps())[0:4]
        self.info_screen.html_text = number_of_bees + '<br><br>' + number_of_flowers + '<br><br>' + fps_string
        self.info_screen.rebuild()
Пример #6
0
class OptionsUIApp:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("Options UI")
        self.options = Options()
        if self.options.fullscreen:
            self.window_surface = pygame.display.set_mode(
                self.options.resolution, pygame.FULLSCREEN)
        else:
            self.window_surface = pygame.display.set_mode(
                self.options.resolution)

        self.background_surface = None

        self.ui_manager = UIManager(self.options.resolution,
                                    'data/themes/theme_2.json')
        self.ui_manager.preload_fonts([{
            'name': 'fira_code',
            'point_size': 10,
            'style': 'bold'
        }, {
            'name': 'fira_code',
            'point_size': 10,
            'style': 'regular'
        }, {
            'name': 'fira_code',
            'point_size': 10,
            'style': 'italic'
        }, {
            'name': 'fira_code',
            'point_size': 14,
            'style': 'italic'
        }, {
            'name': 'fira_code',
            'point_size': 14,
            'style': 'bold'
        }])

        self.test_button = None
        self.test_button_2 = None
        self.test_button_3 = None
        self.test_slider = None
        self.test_text_entry = None
        self.test_drop_down = None
        self.panel = None

        self.message_window = None

        self.recreate_ui()

        self.clock = pygame.time.Clock()

        self.button_response_timer = pygame.time.Clock()
        self.running = True
        self.debug_mode = False

    def recreate_ui(self):
        self.ui_manager.set_window_resolution(self.options.resolution)
        self.ui_manager.clear_and_reset()

        self.background_surface = pygame.Surface(self.options.resolution)
        self.background_surface.fill(self.ui_manager.get_theme().get_colour(
            None, None, 'dark_bg'))

        self.test_button = UIButton(
            pygame.Rect((int(self.options.resolution[0] / 2),
                         int(self.options.resolution[1] * 0.90)), (100, 40)),
            '',
            self.ui_manager,
            tool_tip_text="<font face=fira_code color=normal_text size=2>"
            "<b><u>Test Tool Tip</u></b>"
            "<br><br>"
            "A little <i>test</i> of the "
            "<font color=#FFFFFF><b>tool tip</b></font>"
            " functionality."
            "<br><br>"
            "Unleash the Kraken!"
            "</font>",
            object_id='#hover_me_button')

        self.test_button_2 = UIButton(pygame.Rect(
            (int(self.options.resolution[0] / 3),
             int(self.options.resolution[1] * 0.90)), (100, 40)),
                                      'EVERYTHING',
                                      self.ui_manager,
                                      object_id='#everything_button')

        self.test_button_3 = UIButton(pygame.Rect(
            (int(self.options.resolution[0] / 6),
             int(self.options.resolution[1] * 0.90)), (100, 40)),
                                      'Scaling?',
                                      self.ui_manager,
                                      object_id='#scaling_button')

        self.test_slider = UIHorizontalSlider(pygame.Rect(
            (int(self.options.resolution[0] / 2),
             int(self.options.resolution[1] * 0.70)), (240, 25)),
                                              25.0, (0.0, 100.0),
                                              self.ui_manager,
                                              object_id='#cool_slider')

        self.test_text_entry = UITextEntryLine(pygame.Rect(
            (int(self.options.resolution[0] / 2),
             int(self.options.resolution[1] * 0.50)), (200, -1)),
                                               self.ui_manager,
                                               object_id='#main_text_entry')

        current_resolution_string = (str(self.options.resolution[0]) + 'x' +
                                     str(self.options.resolution[1]))
        self.test_drop_down = UIDropDownMenu(
            ['640x480', '800x600', '1024x768'], current_resolution_string,
            pygame.Rect((int(self.options.resolution[0] / 2),
                         int(self.options.resolution[1] * 0.3)),
                        (200, 25)), self.ui_manager)

        self.panel = UIPanel(pygame.Rect(50, 50, 200, 300),
                             starting_layer_height=4,
                             manager=self.ui_manager)

        UIButton(pygame.Rect(10, 10, 174, 30),
                 'Panel Button',
                 manager=self.ui_manager,
                 container=self.panel)

        UISelectionList(pygame.Rect(10, 50, 174, 200),
                        item_list=[
                            'Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5',
                            'Item 6', 'Item 7', 'Item 8', 'Item 9', 'Item 10',
                            'Item 11', 'Item 12', 'Item 13', 'Item 14',
                            'Item 15', 'Item 16', 'Item 17', 'Item 18',
                            'Item 19', 'Item 20'
                        ],
                        manager=self.ui_manager,
                        container=self.panel,
                        allow_multi_select=True)

    def create_message_window(self):
        self.button_response_timer.tick()
        self.message_window = UIMessageWindow(
            rect=pygame.Rect(
                (random.randint(0, self.options.resolution[0] - 300),
                 random.randint(0, self.options.resolution[1] - 200)),
                (300, 250)),
            window_title='Test Message Window',
            html_message='<font color=normal_text>'
            'This is a <a href="test">test</a> message to see if '
            'this box <a href=actually_link>actually</a> works.'
            ''
            'In <i>bibendum</i> orci et velit</b> gravida lacinia.<br><br><br> '
            'In hac a habitasse to platea dictumst.<br>'
            ' <font color=#4CD656 size=4>Vivamus I interdum mollis lacus nec '
            'porttitor.<br> Morbi'
            ' accumsan, lectus at'
            ' tincidunt to dictum, neque <font color=#879AF6>erat tristique'
            ' blob</font>,'
            ' sed a tempus for <b>nunc</b> dolor in nibh.<br>'
            ' Suspendisse in viverra dui <i>fringilla dolor laoreet</i>, sit amet '
            'on pharetra a ante'
            ' sollicitudin.</font>'
            '<br><br>'
            'In <i>bibendum</i> orci et velit</b> gravida lacinia.<br><br><br> '
            'In hac a habitasse to platea dictumst.<br>'
            ' <font color=#4CD656 size=4>Vivamus I interdum mollis lacus nec '
            'porttitor.<br> Morbi'
            ' accumsan, lectus at'
            ' tincidunt to dictum, neque <font color=#879AF6>erat tristique '
            'erat</font>,'
            ' sed a tempus for <b>nunc</b> dolor in nibh.<br>'
            ' Suspendisse in viverra dui <i>fringilla dolor laoreet</i>, sit amet '
            'on pharetra a ante'
            ' sollicitudin.</font>'
            '<br><br>'
            'In <i>bibendum</i> orci et velit</b> gravida lacinia.<br><br><br> '
            'In hac a habitasse to platea dictumst.<br>'
            ' <font color=#4CD656 size=4>Vivamus I interdum mollis lacus nec '
            'porttitor.<br> Morbi'
            ' accumsan, lectus at'
            ' tincidunt to dictum, neque <font color=#879AF6>erat tristique '
            'erat</font>,'
            ' sed a tempus for <b>nunc</b> dolor in nibh.<br>'
            ' Suspendisse in viverra dui <i>fringilla dolor laoreet</i>, '
            'sit amet on pharetra a ante'
            ' sollicitudin.</font>'
            '</font>',
            manager=self.ui_manager)
        time_taken = self.button_response_timer.tick() / 1000.0
        # currently taking about 0.35 seconds down from 0.55 to create
        # an elaborately themed message window.
        # still feels a little slow but it's better than it was.
        print("Time taken to create message window: " + str(time_taken))

    def check_resolution_changed(self):
        resolution_string = self.test_drop_down.selected_option.split('x')
        resolution_width = int(resolution_string[0])
        resolution_height = int(resolution_string[1])
        if (resolution_width != self.options.resolution[0]
                or resolution_height != self.options.resolution[1]):
            self.options.resolution = (resolution_width, resolution_height)
            self.window_surface = pygame.display.set_mode(
                self.options.resolution)
            self.recreate_ui()

    def process_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

            self.ui_manager.process_events(event)

            if event.type == pygame.KEYDOWN and event.key == pygame.K_d:
                self.debug_mode = False if self.debug_mode else True
                self.ui_manager.set_visual_debug_mode(self.debug_mode)

            if event.type == pygame.USEREVENT:
                if (event.user_type == pygame_gui.UI_TEXT_ENTRY_FINISHED
                        and event.ui_object_id == '#main_text_entry'):
                    print(event.text)

                if event.user_type == pygame_gui.UI_TEXT_BOX_LINK_CLICKED:
                    if event.link_target == 'test':
                        print("clicked test link")
                    elif event.link_target == 'actually_link':
                        print("clicked actually link")

                if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
                    if event.ui_element == self.test_button:
                        self.test_button.set_text(
                            random.choice(
                                ['', 'Hover me!', 'Click this.', 'A Button']))
                        self.create_message_window()

                    if event.ui_element == self.test_button_3:
                        ScalingWindow(pygame.Rect((50, 50), (224, 224)),
                                      self.ui_manager)
                    if event.ui_element == self.test_button_2:
                        EverythingWindow(pygame.Rect((10, 10), (640, 480)),
                                         self.ui_manager)

                if (event.user_type == pygame_gui.UI_DROP_DOWN_MENU_CHANGED
                        and event.ui_element == self.test_drop_down):
                    self.check_resolution_changed()

    def run(self):
        while self.running:
            time_delta = self.clock.tick(60) / 1000.0

            # check for input
            self.process_events()

            # respond to input
            self.ui_manager.update(time_delta)

            # draw graphics
            self.window_surface.blit(self.background_surface, (0, 0))
            self.ui_manager.draw_ui(self.window_surface)

            pygame.display.update()
Пример #7
0
class UrizenGuiApp:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption('Urizen 0.2.5')
        self.opt = GUIOptions()
        self.gen_state = GeneratorsState()
        if self.opt.fullscreen:
            self.window_surface = pygame.display.set_mode(
                self.opt.resolution, pygame.FULLSCREEN)
        else:
            self.window_surface = pygame.display.set_mode(
                self.opt.resolution, pygame.RESIZABLE)

        self.background_surface = None

        self.ui_manager = UIManager(
            self.opt.resolution,
            PackageResource('urizen.data.themes', 'gui_theme.json'))
        self.ui_manager.preload_fonts([{
            'name': 'fira_code',
            'point_size': 10,
            'style': 'bold'
        }, {
            'name': 'fira_code',
            'point_size': 10,
            'style': 'regular'
        }, {
            'name': 'fira_code',
            'point_size': 10,
            'style': 'italic'
        }, {
            'name': 'fira_code',
            'point_size': 14,
            'style': 'italic'
        }, {
            'name': 'fira_code',
            'point_size': 14,
            'style': 'bold'
        }])

        self.panel = None

        self.message_window = None

        self.active_panel = None
        self.recreate_ui()

        self.clock = pygame.time.Clock()
        self.time_delta_stack = deque([])

        self.button_response_timer = pygame.time.Clock()
        self.running = True

    def recreate_ui(self):
        self.ui_manager.set_window_resolution(self.opt.resolution)
        self.ui_manager.clear_and_reset()

        self.background_surface = pygame.Surface(self.opt.resolution)
        self.background_surface.fill(
            self.ui_manager.get_theme().get_colour('dark_bg'))

        self.btn_gen_explore = UIButton(
            pygame.Rect(5, 5, 48, 48),
            '',
            manager=self.ui_manager,
            container=None,
            object_id='#btn_gen_explore',
        )
        self.btn_gen_search = UIButton(
            pygame.Rect(5, 58, 48, 48),
            '',
            manager=self.ui_manager,
            container=None,
            object_id='#btn_gen_search',
            tool_tip_text='Not yet implemented',
        )
        self.btn_tiles_explore = UIButton(
            pygame.Rect(5, 111, 48, 48),
            '',
            manager=self.ui_manager,
            container=None,
            object_id='#btn_tiles_explore',
            tool_tip_text='Not yet implemented',
        )
        self.btn_tiles_search = UIButton(
            pygame.Rect(5, 164, 48, 48),
            '',
            manager=self.ui_manager,
            container=None,
            object_id='#btn_tiles_search',
            tool_tip_text='Not yet implemented',
        )

        self.main_area = pygame.Rect(5 + 48 + 5, 5,
                                     self.opt.W - (5 + 48 + 5 + 5),
                                     self.opt.H - (5 + 5))
        self.pnl_empty = UIPanel(self.main_area,
                                 starting_layer_height=1,
                                 manager=self.ui_manager)

        self.construct_gen_explore()
        self.construct_gen_search()
        self.btn_gen_search.disable()
        self.construct_tiles_explore()
        self.btn_tiles_explore.disable()
        self.construct_tiles_search()
        self.btn_tiles_search.disable()

        if self.active_panel:
            self.active_panel.show()

    def construct_gen_explore(self):
        #self.gen_explore_bg_surface = pygame.Surface(self.opt.resolution)
        #self.gen_explore_bg_surface.fill(self.ui_manager.get_theme().get_colour('dark_bg'))
        self.pnl_gen_explore = UIPanel(self.main_area,
                                       starting_layer_height=0,
                                       manager=self.ui_manager)

        self.gen_explore_label = UILabel(
            pygame.Rect(5, 5, 350, 35),
            'Explore generators',
            self.ui_manager,
            container=self.pnl_gen_explore,
        )
        self.gen_list = UISelectionList(
            relative_rect=pygame.Rect(5, 75, 350, self.opt.H - 95),
            item_list=self.gen_state.get_current_gen_list(),
            manager=self.ui_manager,
            container=self.pnl_gen_explore,
            allow_multi_select=False,
            object_id='#gen_list',
        )
        self.btn_gen_explore_save_as_png = None
        self.gen_explore_map_image = None
        self.gen_explore_image = None
        self.file_dialog_gen_explore_save_as_png = None
        self.pnl_gen_explore.hide()

    def construct_gen_search(self):
        self.pnl_gen_search = UIPanel(self.main_area,
                                      starting_layer_height=0,
                                      manager=self.ui_manager)
        self.pnl_gen_search.hide()

    def construct_tiles_explore(self):
        self.pnl_tiles_explore = UIPanel(self.main_area,
                                         starting_layer_height=0,
                                         manager=self.ui_manager)
        self.pnl_tiles_explore.hide()

    def construct_tiles_search(self):
        self.pnl_tiles_search = UIPanel(self.main_area,
                                        starting_layer_height=0,
                                        manager=self.ui_manager)
        self.pnl_tiles_search.hide()

    def process_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

            self.ui_manager.process_events(event)

            if event.type == pygame.VIDEORESIZE:
                self.opt.W = event.w
                self.opt.H = event.h
                self.opt.resolution = (event.w, event.h)
                self.recreate_ui()

            if event.type == pygame.USEREVENT:
                if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
                    if event.ui_element == self.btn_gen_explore:
                        self.pnl_gen_explore.show()
                        self.pnl_gen_search.hide()
                        self.pnl_tiles_explore.hide()
                        self.pnl_tiles_search.hide()
                        self.active_panel = self.pnl_gen_explore
                    elif event.ui_element == self.btn_gen_search:
                        self.pnl_gen_explore.hide()
                        self.pnl_gen_search.show()
                        self.pnl_tiles_explore.hide()
                        self.pnl_tiles_search.hide()
                        self.active_panel = self.btn_gen_search
                    elif event.ui_element == self.btn_tiles_explore:
                        self.pnl_gen_explore.hide()
                        self.pnl_gen_search.hide()
                        self.pnl_tiles_explore.show()
                        self.pnl_tiles_search.hide()
                        self.active_panel = self.btn_tiles_explore
                    elif event.ui_element == self.btn_tiles_search:
                        self.pnl_gen_explore.hide()
                        self.pnl_gen_search.hide()
                        self.pnl_tiles_explore.hide()
                        self.pnl_tiles_search.show()
                        self.active_panel = self.pnl_tiles_search
                    elif event.ui_element == self.btn_gen_explore_save_as_png:
                        self.file_dialog_gen_explore_save_as_png = UIFileDialog(
                            pygame.Rect(self.opt.W // 4, self.opt.H // 4,
                                        self.opt.W // 2, self.opt.H // 2),
                            self.ui_manager,
                            window_title='Save as PNG',
                            initial_file_path='map.png',
                            object_id='#file_dialog_gen_explore_save_as_png')

                if event.user_type == pygame_gui.UI_FILE_DIALOG_PATH_PICKED:
                    if event.ui_element == self.file_dialog_gen_explore_save_as_png:
                        self.gen_explore_image.save(event.text)

                if event.user_type == pygame_gui.UI_WINDOW_CLOSE:
                    if event.ui_element == self.file_dialog_gen_explore_save_as_png:
                        self.file_dialog_gen_explore_save_as_png = None

                if event.user_type == pygame_gui.UI_SELECTION_LIST_DOUBLE_CLICKED_SELECTION:
                    if event.ui_element == self.gen_list:
                        if self.gen_state.is_generator(event.text):
                            M = self.gen_state.get_generator(event.text)()
                            surface_w = self.opt.W - 435
                            surface_h = self.opt.H - 95
                            self.gen_explore_image = construct_bounded_map_image(
                                M, surface_w, surface_h)
                            image_bytes = self.gen_explore_image.tobytes()
                            im_w, im_h = self.gen_explore_image.size
                            shift_x = (surface_w - im_w) // 2
                            shift_y = (surface_h - im_h) // 2
                            if not self.gen_explore_map_image:
                                self.gen_explore_map_image = UIImage(
                                    relative_rect=pygame.Rect(
                                        360 + shift_x, 75 + shift_y, im_w,
                                        im_h),
                                    image_surface=pygame.image.fromstring(
                                        image_bytes,
                                        self.gen_explore_image.size,
                                        self.gen_explore_image.mode),
                                    manager=self.ui_manager,
                                    container=self.pnl_gen_explore,
                                    object_id='#gen_explore_map_image',
                                )
                            else:
                                self.gen_explore_map_image.set_relative_position(
                                    pygame.Rect(360 + shift_x, 75 + shift_y,
                                                im_w, im_h))
                                self.gen_explore_map_image.image = pygame.image.fromstring(
                                    image_bytes, self.gen_explore_image.size,
                                    self.gen_explore_image.mode)
                            if not self.btn_gen_explore_save_as_png:
                                self.btn_gen_explore_save_as_png = UIButton(
                                    pygame.Rect(self.opt.W - 265, 5, 190, 50),
                                    'Save as PNG',
                                    manager=self.ui_manager,
                                    container=self.pnl_gen_explore,
                                    object_id='#btn_gen_explore_save_as_png',
                                    starting_height=10,
                                )
                        else:
                            self.gen_state.change_state(event.text)
                            self.gen_list.set_item_list(
                                self.gen_state.get_current_gen_list())

    def run(self):
        while self.running:
            time_delta = self.clock.tick() / 1000.0
            self.time_delta_stack.append(time_delta)
            if len(self.time_delta_stack) > 2000:
                self.time_delta_stack.popleft()

            # check for input
            self.process_events()

            # respond to input
            self.ui_manager.update(time_delta)

            # draw graphics
            self.window_surface.blit(self.background_surface, (0, 0))
            self.ui_manager.draw_ui(self.window_surface)

            pygame.display.update()
Пример #8
0
def gameloop(
    playerOrder: bool,
    p1Char: str,
    nick1: str,
    p2Char: str,
    nick2: str,
    udp: UDP_P2P,
) -> str:
    # region DocString
    """
    Function that starts the loop for pygame

    ### Arguments
        `playerOrder {bool}`:
            `summary`: true if this host is the first player, false otherwise
        `p1Char {str}`:
            `summary`: the character chosen by this host
        `nick1 {str}`:
            `summary`: the username of this host
        `p2Char {str}`:
            `summary`: the character chosen by the remote player
        `nick2 {str}`:
            `summary`: the username of the remote player
        `udp {UDP_P2P}`:
            `summary`: the udp object

    ### Returns
        `str`: the exit status. It can be 'Lost' if this host lose, 'Quit' if this host closed the window,\n
        'Win' if the remote host lose, 'Quitted' if the remote host closed the window
    """
    # endregion

    global gamestate
    clock = Clock()
    COORDSYNC = USEREVENT + 1
    set_timer(COORDSYNC, 1000)

    # region Screen setup

    screen = set_mode((Game.SIZE[0] + 400, Game.SIZE[1]))
    set_caption(Game.TITLE)
    set_icon(load(Game.ICON_PATH))
    bg = load(Game.BG_PATH).convert_alpha()
    bg = scale(bg, Game.SIZE)

    manager = UIManager((Game.SIZE[0] + 400, Game.SIZE[1]))
    chat = Chat((400, Game.SIZE[1]), manager, udp, nick1)

    # endregion

    all_sprites = Group()

    # region Players setup

    if p1Char == "Ichigo":
        pl = Ichigo(playerOrder, nick1, all_sprites)
    elif p1Char == "Vegeth":
        pl = Vegeth(playerOrder, nick1, all_sprites)

    if p2Char == "Ichigo":
        pl2 = Ichigo(not playerOrder, nick2, all_sprites)
    elif p2Char == "Vegeth":
        pl2 = Vegeth(not playerOrder, nick2, all_sprites)

    # endregion

    rcvT = udp.receptionThread(
        lambda data, addr, time: rcv(pl2, data, addr, time, chat), rcvErr)
    rcvT.start()

    while True:

        dt = clock.tick(Game.FPS) / 1000

        # region Handle window close

        pressed_keys = get_pressed()

        for event in get():
            if event.type == QUIT:
                snd(nick1, "Quit", udp)
                gamestate = "Quit"

            if event.type == COORDSYNC:
                sndCoords(nick1, (pl.rect.x, pl.rect.y), udp)

            manager.process_events(event)

        # endregion

        manager.update(dt)

        # region Handle key press and update sprites

        all_sprites.update(pressed_keys)
        sndKeys(
            nick1,
            (
                pressed_keys[K_LEFT],
                pressed_keys[K_RIGHT],
                pressed_keys[K_UP],
                pressed_keys[K_z],
            ),
            udp,
        )
        if pl.update(pressed_keys):
            snd(nick1, "Lost", udp)
            gamestate = "Lost"

        # endregion

        # region Sprite drawing

        screen.fill(Color.WHITE)
        screen.blit(bg, (0, 0))
        all_sprites.draw(screen)
        pl.draw(screen)
        pl2.draw(screen)
        pl.health.draw(screen)
        pl2.health.draw(screen)

        # endregion

        manager.draw_ui(screen)
        flip()

        if gamestate:
            udp.stopThread()
            quit()
            return gamestate
Пример #9
0
class App():
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("MineSweaper")

        self.iconImage = pygame.image.load('data/images/mine.png')
        pygame.display.set_icon(self.iconImage)

        self.options = Options()
        if self.options.fullscreen:
            self.window_surface = pygame.display.set_mode(
                self.options.resolution, pygame.FULLSCREEN)
        else:
            self.window_surface = pygame.display.set_mode(
                self.options.resolution)

        self.background_surface = None

        self.ui_manager = UIManager(self.options.resolution,
                                    'data/theme/mineSweaper_theme.json')

        self.clock = pygame.time.Clock()
        self.running = True
        '''
            Create game Window
        '''
        self.mainMenu = None

        self.recreate_ui()

    def process_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

            self.ui_manager.process_events(event)

    def recreate_ui(self):
        self.ui_manager.set_window_resolution(self.options.resolution)
        self.ui_manager.clear_and_reset()

        self.background_surface = pygame.Surface(self.options.resolution)
        self.background_surface.fill(
            self.ui_manager.get_theme().get_colour('dark_bg'))

        self.mainMenu = MainMenu(
            pygame.Rect((25, 25), (self.options.resolution[0] - 250,
                                   self.options.resolution[1] - 50)),
            self.ui_manager)

    def run(self):

        while self.running:
            time_delta = self.clock.tick() / 1000.0

            # check for input
            self.process_events()

            # respond to input
            self.ui_manager.update(time_delta)

            # draw graphics
            self.window_surface.blit(self.background_surface, (0, 0))
            self.ui_manager.draw_ui(self.window_surface)

            pygame.display.update()
Пример #10
0
class Game:
    def __init__(self):
        # Start up Pygame.
        pygame.init()

        # Title the window our game runs in.
        pygame.display.set_caption(config.game_name)
        
        self.options = Options()

        # Define the dimensions of our game's window.
        self.window_surface = pygame.display.set_mode(self.options.resolution)
        self.window_surface.blit(pygame.image.load("media/images/background.png"), (0, 0))

        self.start_up = True
        self.enter_mines = False
        self.enter_busstop = False
        self.enter_uptown = False

        self.background_surface = None

        self.ui_manager = UIManager(self.options.resolution, PackageResource(package='media.themes', resource='theme.json'))

        self.text_block = None
        self.text_entry = None

        self.message_window = None

        self.recreate_ui()

        self.clock = pygame.time.Clock()
        self.time_delta_stack = deque([])
        self.running = True

    def recreate_ui(self):
        self.ui_manager.set_window_resolution(self.options.resolution)
        self.ui_manager.clear_and_reset()

        self.background_surface = pygame.Surface(self.options.resolution)

        if self.start_up == True:
            self.image = UIImage(pygame.Rect((0, 0), self.options.resolution), title_screen_image, self.ui_manager)
        elif self.enter_mines == True:
            self.image = UIImage(pygame.Rect((0, 0), self.options.resolution), mines_image, self.ui_manager)
        elif self.enter_busstop == True:
            self.image = UIImage(pygame.Rect((0, 0), self.options.resolution), busstop_image, self.ui_manager)
        elif self.enter_uptown == True:
            self.image = UIImage(pygame.Rect((0, 0), self.options.resolution), uptown_image, self.ui_manager)
        else: 
            self.background_surface.fill(self.ui_manager.get_theme().get_colour('dark_bg'))
            self.background_surface.blit(pygame.image.load("media/images/background.png"), (0, 0))
            
            global response_history
            response = response_history
            response_history = response
            self.text_entry = UITextEntryLine(pygame.Rect((50, 550), (700, 50)), self.ui_manager, object_id = "#text_entry")
            self.text_block = UITextBox(response, pygame.Rect((50, 25), (700, 500)), self.ui_manager, object_id = "#text_block")

    def process_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

            self.ui_manager.process_events(event)            

            if event.type==pygame.KEYDOWN:
                if event.key== pygame.K_UP:              
                    if self.start_up == True:
                        self.start_up = False
                        self.recreate_ui()
                    if self.enter_mines == True:
                        self.enter_mines = False
                        self.recreate_ui()
                    if self.enter_busstop == True:
                        self.enter_busstop = False
                        self.recreate_ui()
                    if self.enter_uptown == True:
                        self.enter_uptown = False
                        self.recreate_ui()
            if event.type == pygame.USEREVENT:
                if (event.user_type == pygame_gui.UI_TEXT_ENTRY_FINISHED and event.ui_object_id == '#text_entry'):
                    if event.text != "":
                        # Turn the user's input into a string.
                        message = event.text

                        # Begin the response message. Start with repeating the user's input.
                        response = "<b><i>> {message}</i></b>".format(message = message)

                        # Create a player object using the player's save data.
                        player_data = player.Player()

                        # Check to see if the player is in a scripted sequence.
                        if player_data.scene is not None: # If they are...
                            if player_data.scene == config.scene_id_newgame: # If the player has started the game for the first time.
                                command_response = scenes.Introduction(message)
                                response += ("<br>" * 4) + command_response
                        else: # If they aren't...
                            command_response = utilities.parse_message(message)
                            response += ("<br>" * 4) + command_response

                        # End the response with some decoration. ^_^
                        response += ("<br>" * 4) + ("-" * 20) + ("<br>" * 4)

                        # Add this response to our response history, and then send the entire history to be rendered.
                        global response_history
                        response += response_history
                        response_history = response
                        # Render the response.
                        self.text_entry.set_text("")
                        self.text_block.kill()
                        self.text_block = UITextBox(response, pygame.Rect((50, 25), (700, 500)), self.ui_manager, object_id = "#text_block")
                        
                        if command_response == "You enter the Mines.":
                            self.enter_mines = True
                            self.recreate_ui()
                        if command_response == "You enter a Bus Stop.":
                            self.enter_busstop = True
                            self.recreate_ui()
                        if command_response == "You enter Uptown.":
                            self.enter_uptown = True
                            self.recreate_ui()
    def run(self):
        while self.running:
            time_delta = self.clock.tick() / 1000
            
            # Check for inputs from the player.
            self.process_events()

            # Respond to inputs.
            self.ui_manager.update(time_delta)

            # Draw the graphics.
            self.window_surface.blit(self.background_surface, (0, 0))
            self.ui_manager.draw_ui(self.window_surface)

            pygame.display.update()