コード例 #1
0
    def __init__(self, screen, handler):
        super().__init__(screen, "media/Levels/Factory.png", handler)
        self.plat1 = Platform(screen, 0, 416, 412, 50, speed=2)
        self.plat2 = Platform(screen, 688, 416, 412, 50, speed=-2)
        self.platformGroup.add(self.plat1)
        self.platformGroup.add(self.plat2)
        self.conveyorAnimation = CircularQueue()
        self.conveyorAnimation2 = CircularQueue()
        self.conveyorOne = pygame.image.load("media/misc/conveyorSpriteOne.png").convert_alpha()
        self.conveyorTwo = pygame.image.load("media/misc/conveyorSpriteTwo.png").convert_alpha()
        self.shedsprite = pygame.image.load("media/misc/shedSprite.png")
        self.boxList = []

        actionLeft = lambda: self.boxList.append(FallingShed(handler, 950))
        actionRight = lambda: self.boxList.append(FallingShed(handler, 100))

        self.buttonLeft = Button(actionLeft, 60, 400, 48, handler)
        self.buttonRight = Button(actionRight, 1000, 400, 48, handler)

        for a in range(0, 10):
            self.conveyorAnimation.addData(self.conveyorOne)
        for a in range(0, 10):
            self.conveyorAnimation.addData(self.conveyorTwo)

        self.conveyorOne2 = pygame.transform.flip(self.conveyorOne, True, False)
        self.conveyorTwo2 = pygame.transform.flip(self.conveyorTwo, True, False)

        for a in range(0, 10):
            self.conveyorAnimation2.addData(self.conveyorOne2)
        for a in range(0, 10):
            self.conveyorAnimation2.addData(self.conveyorTwo2)
コード例 #2
0
    def __init__(self, method_id, args, size, pos, item, margin, index, price, disabled=False):
        name = ""
        if item:
            name = str(item)
        price_text = ""
        if price > 0:
            price_text = "(" + str(price) + " gold)"

        padding = size[1] // 10
        frame_pos = (padding, padding)
        frame_size = (size[1] - padding * 2, size[1] - padding * 2)
        frame = pg.transform.scale(pg.image.load(FRAME_SPRITE).convert_alpha(),
                                   frame_size)
        frame_hover = pg.transform.scale(pg.image.load(FRAME_SPRITE_HOVER).convert_alpha(),
                                         frame_size)

        item_frame = pg.transform.scale(pg.image.load(ITEM_SPRITE).convert_alpha(), size)
        item_frame.blit(frame, frame_pos)
        if item:
            item_frame.blit(pg.transform.scale(item.sprite, (frame_size[0] - padding * 2, frame_size[1] - padding * 2)),
                            (frame_pos[0] + padding, frame_pos[1] + padding))

        name_rendering = fonts['ITEM_FONT'].render(name, 1, BLACK)
        if price_text:
            price_rendering = fonts['ITEM_FONT'].render(price_text, 1, BLACK)
            item_frame.blit(name_rendering, (frame.get_width() + padding * 2,
                                             item_frame.get_height() / 3 - fonts['ITEM_FONT'].get_height() / 2))
            item_frame.blit(price_rendering, (frame.get_width() + padding * 2,
                                              2 * item_frame.get_height() / 3 - fonts['ITEM_FONT'].get_height() / 2))
        else:
            item_frame.blit(name_rendering, (frame.get_width() + padding * 2,
                                             item_frame.get_height() / 2 - fonts['ITEM_FONT'].get_height() / 2))

        item_frame_hover = item_frame
        if item and not disabled:
            item_frame_hover = pg.transform.scale(pg.image.load(ITEM_SPRITE).convert_alpha(), size)
            item_frame_hover.blit(frame_hover, frame_pos)
            item_frame_hover.blit(pg.transform.scale(item.sprite, (frame_size[0] - padding * 2,
                                                                   frame_size[1] - padding * 2)),
                                  (frame_pos[0] + padding, frame_pos[1] + padding))
            name_rendering_hover = fonts['ITEM_FONT_HOVER'].render(name, 1, MIDNIGHT_BLUE)
            if price_text:
                price_rendering_hover = fonts['ITEM_FONT_HOVER'].render(price_text, 1, MIDNIGHT_BLUE)
                item_frame_hover.blit(name_rendering_hover, (frame.get_width() + padding * 2,
                                                             item_frame.get_height() / 3
                                                             - fonts['ITEM_FONT_HOVER'].get_height() / 2))
                item_frame_hover.blit(price_rendering_hover, (frame.get_width() + padding * 2,
                                                              2 * item_frame.get_height() / 3
                                                              - fonts['ITEM_FONT_HOVER'].get_height() / 2))
            else:
                item_frame_hover.blit(name_rendering_hover, (frame.get_width() + padding * 2,
                                                             item_frame.get_height() / 2
                                                             - fonts['ITEM_FONT_HOVER'].get_height() / 2))

        args.append(price)
        Button.__init__(self, method_id, args, size, pos, item_frame, item_frame_hover, margin)
        self.item = item
        self.index = index
        self.disabled = disabled
コード例 #3
0
    def setUp(self):
        """Create two test Buttons and start pygame."""
        pygame.init()

        # Create a test Button with text
        self.test_text_button = Button('text', GameWindow.BLACK,
                                       GameWindow.WHITE, Point(0, 0), (10, 10))

        # Create a test Button with an Arrow
        self.test_icon_button = Button('Forward', GameWindow.BLACK,
                                       GameWindow.WHITE, Point(0, 0), (10, 10))
コード例 #4
0
 def init_start_menu(self):
     """
     Init start menu page
     :return: None
     """
     self.game_objects.reset()
     self.game_objects.buttons.extend([
         Button(self.ui, "New game", "new", (400, 100)),
         Button(self.ui, "Rules", "rules", (400, 250)),
         Button(self.ui, "Exit", "exit", (400, 400))
     ])
コード例 #5
0
    def init_new_level(self):
        """
        :return: None
        """
        self.game_objects.reset()
        self.game_objects.player = Player((400, 300))

        self._generate_level_objects(levels[self.game_state.current_level])
        self.game_objects.buttons.extend([
            Button(self.ui, "Restart", "restart", (10, 500)),
            Button(self.ui, "Exit", "exit", (200, 500))
        ])
コード例 #6
0
    def __init__(self, size, pos, item, margin, index, disabled=False):
        name = ""
        if item:
            name = item.get_formatted_name()

        padding = size[1] // 10
        frame_pos = (padding, padding)
        frame_size = (size[1] - padding * 2, size[1] - padding * 2)
        frame = pg.transform.scale(
            pg.image.load(FRAME_SPRITE).convert_alpha(), frame_size)
        frame_hover = pg.transform.scale(
            pg.image.load(FRAME_SPRITE_HOVER).convert_alpha(), frame_size)

        item_frame = pg.transform.scale(
            pg.image.load(ITEM_SPRITE).convert_alpha(), size)
        item_frame.blit(frame, frame_pos)
        if item:
            item_frame.blit(
                pg.transform.scale(item.get_sprite(),
                                   (frame_size[0] - padding * 2,
                                    frame_size[1] - padding * 2)),
                (frame_pos[0] + padding, frame_pos[1] + padding))
        item_sprite = ITALIC_ITEM_FONT.render(name, 1, BLACK)
        item_frame.blit(
            item_sprite,
            (frame.get_width() + padding * 2,
             item_frame.get_height() / 2 - ITALIC_ITEM_FONT.get_height() / 2))

        item_frame_hover = item_frame
        if item and not disabled:
            item_frame_hover = pg.transform.scale(
                pg.image.load(ITEM_SPRITE).convert_alpha(), size)
            item_frame_hover.blit(frame_hover, frame_pos)
            item_frame_hover.blit(
                pg.transform.scale(item.get_sprite(),
                                   (frame_size[0] - padding * 2,
                                    frame_size[1] - padding * 2)),
                (frame_pos[0] + padding, frame_pos[1] + padding))
            item_sprite_hover = ITALIC_ITEM_FONT_HOVER.render(
                name, 1, MIDNIGHT_BLUE)
            item_frame_hover.blit(
                item_sprite_hover,
                (frame.get_width() + padding * 2, item_frame.get_height() / 2 -
                 ITALIC_ITEM_FONT.get_height() / 2))

        Button.__init__(self, INTERAC_ITEM_ACTION_ID, size, pos, item_frame,
                        item_frame_hover, margin)
        self.item = item
        self.index = index
        self.disabled = disabled
コード例 #7
0
    def determine_sizepos(self, close_button):
        # Margin to be add at begin and at end
        height = MARGINBOX * 2
        for row in self.elements:
            max_height = 0
            for el in row:
                el_height = el.get_height() + MARGINTOP
                if el_height > max_height:
                    max_height = el_height
            height += max_height
            row.insert(0, max_height)
        if close_button > 0:
            close_button_height = CLOSE_BUTTON_SIZE[1] + MARGINTOP + CLOSE_BUTTON_MARGINTOP
            height += close_button_height

            # Button sprites
            name = ITEM_FONT.render("Close", 1, WHITE)
            sprite = pg.transform.scale(pg.image.load(BUTTON_INACTIVE).convert_alpha(), CLOSE_BUTTON_SIZE)
            sprite.blit(name, (sprite.get_width() // 2 - name.get_width() // 2,
                               sprite.get_height() // 2 - name.get_height() // 2))
            sprite_hover = pg.transform.scale(pg.image.load(BUTTON_ACTIVE).convert_alpha(), CLOSE_BUTTON_SIZE)
            sprite_hover.blit(name, (sprite_hover.get_width() // 2 - name.get_width() // 2,
                                     sprite_hover.get_height() // 2 - name.get_height() // 2))

            self.elements.append([close_button_height,
                                  Button(CLOSE_ACTION_ID, [close_button], CLOSE_BUTTON_SIZE, (0, 0), sprite,
                                         sprite_hover, (CLOSE_BUTTON_MARGINTOP, 0, 0, 0))])
        return height
コード例 #8
0
    def setUp(self):
        """Initiate pygame and create a test ButtonGroup and Buttons."""
        # Initiate pygame so we can use fonts
        pygame.init()

        # Create a test ButtonGroup
        self.test_button_group = ButtonGroup()

        # Create some test Buttons
        self.test_button = Button("Test", (0, 0, 0), (255, 255, 255),
                                  Point(0, 0), (10, 10))
        self.other_button = Button("Other", (0, 0, 0), (255, 255, 255),
                                   Point(20, 20), (10, 10))

        # Add those test Buttons to the test ButtonGroup
        self.test_button_group.add(self.other_button)
        self.test_button_group.add(self.test_button)
コード例 #9
0
    def test_init(cls):
        """Test the init method of the Button class."""
        button_text = [
            'Forward', 'Turn Left', 'Turn Right', 'Backward', 'Other'
        ]

        for text in button_text:
            # Attempt to create a Button, if any fail the test will fail
            _unused_button = Button(text, GameWindow.BLACK, GameWindow.WHITE,
                                    (0, 0), (10, 10))
コード例 #10
0
 def init_game_finished(self):
     """
     If game is finished show relevant message
     :return:
     """
     self.game_objects.reset()
     self.game_objects.texts.append(
         Text(self.ui, "You win!\nCongratulations!", (450, 200)))
     self.game_objects.buttons.append(
         Button(self.ui, "New game", "new", (450, 300)))
コード例 #11
0
    def __init__(self, screenSize, eventHandler):
        if type(screenSize) != tuple:
            raise TypeError

        if len(screenSize) != 2:
            raise IndexError

        if type(eventHandler) != EventHandler:
            raise TypeError

        self.eventHandler = eventHandler

        self.active = True
        self.selection = -1

        # Hintergrund
        self.backgroundImg = pygame.image.load(
            "./resources/menu_background.png")
        self.backgroundImg = pygame.transform.scale(self.backgroundImg,
                                                    screenSize)
        self.backgroundImg = self.backgroundImg.convert()

        # UI
        buttonSpacing = 20
        upperLeft = pygame.Vector2(buttonSpacing, buttonSpacing)

        self.button_ResumeGame = Button(
            pygame.Rect(upperLeft, self.buttonSize), "Resume Game",
            Menu.buttonColor)

        self.button_NewGame = Button(
            pygame.Rect((upperLeft.x, self.button_ResumeGame.rect.y +
                         self.button_ResumeGame.rect.height + buttonSpacing),
                        self.buttonSize), "New Game", Menu.buttonColor)

        self.button_Highscores = Button(
            pygame.Rect((upperLeft.x, self.button_NewGame.rect.y +
                         self.button_NewGame.rect.height + buttonSpacing),
                        self.buttonSize), "Highscores", Menu.buttonColor)

        self.button_Quit = Button(
            pygame.Rect((upperLeft.x, self.button_Highscores.rect.y +
                         self.button_Highscores.rect.height + buttonSpacing),
                        self.buttonSize), "Quit Game", Menu.buttonColor)

        self.buttons = [
            self.button_ResumeGame, self.button_NewGame,
            self.button_Highscores, self.button_Quit
        ]
コード例 #12
0
 def __init__(self,
              method_id,
              args,
              size,
              pos,
              sprite,
              sprite_hover,
              margin,
              values,
              current_value,
              base_title,
              base_sprite,
              base_sprite_hover,
              linked_object=None):
     Button.__init__(self, method_id, args, size, pos, sprite, sprite_hover,
                     margin, linked_object)
     self.values = values
     self.current_value_ind = current_value
     self.base_title = base_title
     self.base_sprite = base_sprite
     self.base_sprite_hover = base_sprite_hover
     self.args.append(ANIMATION_SPEED)
コード例 #13
0
 def show_rules_page(self):
     """
     Init rules page
     :return: None
     """
     self.game_objects.reset()
     self.game_objects.texts.append(
         Text(
             self.ui, """
         You play as a red box!
         Your goal is to push green boxes to circles.
         When they will be on circles the game is finished.""", (450, 200)))
     self.game_objects.buttons.append(
         Button(self.ui, "Back", "back", (600, 300)))
コード例 #14
0
    def init_elements(self, entries, width):
        elements = []
        for row in entries:
            element = []
            for entry in row:
                if 'margin' not in entry:
                    entry['margin'] = (0, 0, 0, 0)

                if 'type' not in entry:
                    # It is an empty element
                    element.append(
                        BoxElement((0, 0), pg.Surface((0, 0)),
                                   entry['margin']))
                elif entry['type'] == 'button':
                    if 'size' not in entry:
                        size = BUTTON_SIZE
                    else:
                        size = entry['size']
                    if 'font' not in entry:
                        font = fonts['BUTTON_FONT']
                    else:
                        font = entry['font']
                    name = font.render(entry['name'], 1, WHITE)
                    sprite = pg.transform.scale(
                        pg.image.load(BUTTON_INACTIVE).convert_alpha(), size)
                    sprite.blit(
                        name,
                        (sprite.get_width() // 2 - name.get_width() // 2,
                         sprite.get_height() // 2 - name.get_height() // 2))
                    sprite_hover = pg.transform.scale(
                        pg.image.load(BUTTON_ACTIVE).convert_alpha(), size)
                    sprite_hover.blit(
                        name,
                        (sprite_hover.get_width() // 2 - name.get_width() // 2,
                         sprite_hover.get_height() // 2 -
                         name.get_height() // 2))
                    if 'args' not in entry:
                        entry['args'] = []

                    element.append(
                        Button(entry['id'], entry['args'], size, (0, 0),
                               sprite, sprite_hover, entry['margin']))
                elif entry['type'] == 'parameter_button':
                    name = fonts['ITEM_FONT'].render(
                        entry['name'] + ' ' +
                        entry['values'][entry['current_value_ind']]['label'],
                        1, WHITE)
                    base_sprite = pg.transform.scale(
                        pg.image.load(BUTTON_INACTIVE).convert_alpha(),
                        BUTTON_SIZE)
                    sprite = base_sprite.copy()
                    sprite.blit(
                        name,
                        (base_sprite.get_width() // 2 - name.get_width() // 2,
                         base_sprite.get_height() // 2 -
                         name.get_height() // 2))
                    base_sprite_hover = pg.transform.scale(
                        pg.image.load(BUTTON_ACTIVE).convert_alpha(),
                        BUTTON_SIZE)
                    sprite_hover = base_sprite_hover.copy()
                    sprite_hover.blit(name,
                                      (base_sprite_hover.get_width() // 2 -
                                       name.get_width() // 2,
                                       base_sprite_hover.get_height() // 2 -
                                       name.get_height() // 2))
                    element.append(
                        DynamicButton(entry['id'], [], BUTTON_SIZE, (0, 0),
                                      sprite, sprite_hover, entry['margin'],
                                      entry['values'],
                                      entry['current_value_ind'],
                                      entry['name'], base_sprite,
                                      base_sprite_hover))
                elif entry['type'] == 'text_button':
                    name = fonts['ITEM_FONT'].render(entry['name'], 1,
                                                     entry['color'])
                    name_hover = fonts['ITEM_FONT'].render(
                        entry['name'], 1, entry['color_hover'])
                    if 'obj' not in entry:
                        entry['obj'] = None
                    element.append(
                        Button(entry['id'], [], name.get_size(), (0, 0), name,
                               name_hover, entry['margin'], entry['obj']))

                elif entry['type'] == 'item_button':
                    button_size = entry[
                        'size'] if 'size' in entry else ITEM_BUTTON_SIZE

                    disabled = 'disabled' in entry
                    if 'subtype' in entry:
                        if entry['subtype'] == 'trade':
                            button_size = TRADE_ITEM_BUTTON_SIZE
                    if 'price' not in entry:
                        entry['price'] = 0
                    if 'quantity' not in entry:
                        entry['quantity'] = 0
                    if 'args' not in entry:
                        entry['args'] = []
                    element.append(
                        ItemButton(entry['id'], entry['args'], button_size,
                                   (0, 0), entry['item'], entry['margin'],
                                   entry['index'], entry['price'],
                                   entry['quantity'], disabled))
                elif entry['type'] == 'text':
                    if 'font' not in entry:
                        entry['font'] = fonts['ITEM_FONT']
                    if 'color' not in entry:
                        entry['color'] = WHITE
                    element.append(
                        TextElement(entry['text'], width, (0, 0),
                                    entry['font'], entry['margin'],
                                    entry['color']))
            elements.append(element)
        title = TextElement(self.name, width, (0, 0), fonts['MENU_TITLE_FONT'],
                            (len(entries), 0, 20, 0), self.title_color)
        self.sep['posY'] += title.get_height()
        elements.insert(0, [title])
        return elements
コード例 #15
0
class TestButton(unittest.TestCase):
    """This test class unit tests the Button class."""
    def setUp(self):
        """Create two test Buttons and start pygame."""
        pygame.init()

        # Create a test Button with text
        self.test_text_button = Button('text', GameWindow.BLACK,
                                       GameWindow.WHITE, Point(0, 0), (10, 10))

        # Create a test Button with an Arrow
        self.test_icon_button = Button('Forward', GameWindow.BLACK,
                                       GameWindow.WHITE, Point(0, 0), (10, 10))

    @classmethod
    def test_init(cls):
        """Test the init method of the Button class."""
        button_text = [
            'Forward', 'Turn Left', 'Turn Right', 'Backward', 'Other'
        ]

        for text in button_text:
            # Attempt to create a Button, if any fail the test will fail
            _unused_button = Button(text, GameWindow.BLACK, GameWindow.WHITE,
                                    (0, 0), (10, 10))

    def test_swap_colours(self):
        """Test the swap_colours method."""
        # Store the original colours of the Buttons text and background
        text_colour = self.test_text_button.text_colour
        background_colour = self.test_text_button.background_colour

        # Swap the colours
        self.test_text_button.swap_colours()

        # Assert the colour of the text is now background_colour
        self.assertEqual(self.test_text_button.text_colour, background_colour)

        # Assert the colour of the background is now the text colour
        self.assertEqual(self.test_text_button.background_colour, text_colour)

        # Assert the Button has registered it has been swapped
        self.assertTrue(self.test_text_button.swapped)

        # We don't have to worry about un-swapping the Button
        # as each test case recreates the test buttons

    def test_is_mouse_over_button(self):
        """Test the is_mouse_over_button."""
        # Assert that a mouse position outside the Button does not return True
        self.assertFalse(self.test_text_button.is_mouse_over_button((5, -2)))
        self.assertFalse(self.test_text_button.is_mouse_over_button((-2, 5)))
        self.assertFalse(self.test_text_button.is_mouse_over_button((12, 5)))
        self.assertFalse(self.test_text_button.is_mouse_over_button((5, 12)))

        # Assert that a mouse position inside the Button does return True
        self.assertTrue(self.test_text_button.is_mouse_over_button((5, 5)))

        # Make this Button not displayed
        self.test_icon_button.displayed = False
        # Assert that a mouse position inside a non displayed Button
        # does not return True
        self.assertFalse(self.test_icon_button.is_mouse_over_button((5, 5)))
コード例 #16
0
    def init_elements(self, entries, width):
        elements = []
        for row in entries:
            element = []
            for entry in row:
                if 'margin' not in entry:
                    entry['margin'] = (0, 0, 0, 0)

                if entry['type'] == 'button':
                    name = ITEM_FONT.render(entry['name'], 1, WHITE)
                    sprite = pg.transform.scale(pg.image.load(BUTTON_INACTIVE).convert_alpha(), BUTTON_SIZE)
                    sprite.blit(name, (sprite.get_width() // 2 - name.get_width() // 2,
                                       sprite.get_height() // 2 - name.get_height() // 2))
                    sprite_hover = pg.transform.scale(pg.image.load(BUTTON_ACTIVE).convert_alpha(), BUTTON_SIZE)
                    sprite_hover.blit(name, (sprite_hover.get_width() // 2 - name.get_width() // 2,
                                             sprite_hover.get_height() // 2 - name.get_height() // 2))
                    if 'args' not in entry:
                        entry['args'] = []

                    element.append(Button(entry['id'], entry['args'], BUTTON_SIZE, (0, 0), sprite, sprite_hover,
                                          entry['margin']))
                elif entry['type'] == 'parameter_button':
                    name = ITEM_FONT.render(entry['name'] + ' ' + entry['values'][entry['current_value_ind']]['label'], 1, WHITE)
                    base_sprite = pg.transform.scale(pg.image.load(BUTTON_INACTIVE).convert_alpha(), BUTTON_SIZE)
                    sprite = base_sprite.copy()
                    sprite.blit(name, (base_sprite.get_width() // 2 - name.get_width() // 2,
                                       base_sprite.get_height() // 2 - name.get_height() // 2))
                    base_sprite_hover = pg.transform.scale(pg.image.load(BUTTON_ACTIVE).convert_alpha(), BUTTON_SIZE)
                    sprite_hover = base_sprite_hover.copy()
                    sprite_hover.blit(name, (base_sprite_hover.get_width() // 2 - name.get_width() // 2,
                                             base_sprite_hover.get_height() // 2 - name.get_height() // 2))
                    element.append(DynamicButton(entry['id'], [], BUTTON_SIZE, (0, 0), sprite, sprite_hover,
                                                 entry['margin'], entry['values'], entry['current_value_ind'], entry['name'],
                                                 base_sprite, base_sprite_hover))
                elif entry['type'] == 'text_button':
                    name = ITEM_FONT.render(entry['name'], 1, entry['color'])
                    name_hover = ITEM_FONT.render(entry['name'], 1, entry['color_hover'])
                    if 'obj' not in entry:
                        entry['obj'] = None
                    element.append(Button(entry['id'], [], name.get_size(), (0, 0), name, name_hover, entry['margin'], entry['obj']))

                elif entry['type'] == 'item_button':
                    button_size = ITEM_BUTTON_SIZE
                    disabled = 'disabled' in entry
                    if 'subtype' in entry:
                        if entry['subtype'] == 'equip':
                            button_size = EQUIP_BUTTON_SIZE
                    if 'price' not in entry:
                        entry['price'] = 0
                    element.append(ItemButton(button_size, (0, 0), entry['item'], entry['margin'], entry['index'],
                                              entry['price'], disabled))
                elif entry['type'] == 'text':
                    if 'font' not in entry:
                        entry['font'] = ITEM_FONT
                    if 'color' not in entry:
                        entry['color'] = WHITE
                    element.append(TextElement(entry['text'], width, (0, 0), entry['font'], entry['margin'], entry['color']))
            elements.append(element)
        elements.insert(0, [TextElement(self.name, width, (0, 0), MENU_TITLE_FONT, (len(entries) + 5, 0, 0, 0),
                                        self.title_color)])
        return elements
コード例 #17
0
ファイル: GameWindow.py プロジェクト: gregcorbett/SciBot
    def choose_scenario(self):
        """Choose a Scenario (possibly using a PyGame UI)."""
        # Get the available Scenarios (those under ./scenarios/)
        scenario_list = glob.glob("./scenarios/*.scibot")

        # If no scenarios, exit!
        if len(scenario_list) is 0:
            print("No scibot files found.")
            print("Please place them in ./scenarios/")
            self.rendering_mode = RenderingMode.END_RENDERING
            sleep(1)
            pygame.quit()
            sys.exit()

        # If only one scenario, use that one!
        if len(scenario_list) is 1:
            self.scenario = scenario_list[0]
            return

        # else, Remove Default.scenario from returned list if there
        scenario_list = [
            scenario for scenario in scenario_list
            if "Default.scibot" not in scenario
        ]

        # If now only one scenario, use that one!
        if len(scenario_list) is 1:
            self.scenario = scenario_list[0]
            return

        # Determine the size of the window needed to display all the buttons.
        # Set maximum scenarios to display on a single row.
        max_width = 3
        # If scenarios less than max_width, they can be displayed on one row.
        if len(scenario_list) <= max_width:
            height = 1
            width = len(scenario_list)
        else:  # Work out how many rows are needed.
            height = math.ceil(len(scenario_list) / 3.0)
            width = max_width

        # Work out screen size to display 120x120
        # buttons with 10 space between.
        screen_width = 10 + (width * (120 + 10))
        screen_height = 10 + (height * (120 + 10))

        # Variables used to draw Buttons
        # Start a 10 because of padding
        width_counter = 10
        height_counter = 10

        # Empty ButtonGroup
        self.buttons.removal_all()

        for scenario_path in scenario_list:
            # Get the Scenario filename from the full path
            scenario_file = os.path.basename(scenario_path)
            # Add the Scenario filename (minus extension) to a list
            temp = Button(
                os.path.splitext(scenario_file)[0],
                GameWindow.BLACK, GameWindow.WHITE,
                Point(width_counter, height_counter), (120, 120))

            # Add temp Button to ButtonGroup
            self.buttons.add(temp)

            # If the next Button would be printed off screen,
            # start a new row.
            if width_counter > ((width - 1) * 120):
                width_counter = 10
                height_counter = height_counter + 120 + 10
            else:
                width_counter = width_counter + 120 + 10

        # Display the PyGame UI
        self.screen = pygame.display.set_mode((screen_width, screen_height))
        self.rendering_mode = RenderingMode.CHOOSE_SCENARIO

        # User choose's a Scenario
        while self.scenario is None:
            event = pygame.event.poll()
            # If the event is a left mouse button up
            # assume it is a button press
            if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
                # If it was indeed a Button release
                button = self.buttons.get_pressed_button(event.pos)
                if button is not None and button.swapped:
                    # Get the file corresponding to the Button pressed
                    button.swap_colours()
                    self.scenario = "./scenarios/" + button.text + ".scibot"
                else:
                    # Reset all Buttons without doing anything else
                    self.buttons.unswap_all()

            # If the event is a left mouse button up
            # assume it is a button press
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                # If it was indeed a Button press
                button = self.buttons.get_pressed_button(event.pos)
                if button is not None:
                    # Mark that Button as being pressed
                    button.swap_colours()

            if event.type == pygame.QUIT:
                self.rendering_mode = RenderingMode.END_RENDERING
                sleep(1)
                pygame.quit()
                sys.exit()
コード例 #18
0
class Menu:
    # Menueeinstellungen
    buttonSize = (300, 60)
    buttonColor = Color.WHITE
    buttonColorHover = Color.LIGHT_GREY
    buttonColorClick = Color.DARK_GREY

    # Menueauswahl
    class MenuSelection:
        resumeGame = 0
        startNewGame = 1
        highscores = 2
        quit = 3

    def __init__(self, screenSize, eventHandler):
        if type(screenSize) != tuple:
            raise TypeError

        if len(screenSize) != 2:
            raise IndexError

        if type(eventHandler) != EventHandler:
            raise TypeError

        self.eventHandler = eventHandler

        self.active = True
        self.selection = -1

        # Hintergrund
        self.backgroundImg = pygame.image.load(
            "./resources/menu_background.png")
        self.backgroundImg = pygame.transform.scale(self.backgroundImg,
                                                    screenSize)
        self.backgroundImg = self.backgroundImg.convert()

        # UI
        buttonSpacing = 20
        upperLeft = pygame.Vector2(buttonSpacing, buttonSpacing)

        self.button_ResumeGame = Button(
            pygame.Rect(upperLeft, self.buttonSize), "Resume Game",
            Menu.buttonColor)

        self.button_NewGame = Button(
            pygame.Rect((upperLeft.x, self.button_ResumeGame.rect.y +
                         self.button_ResumeGame.rect.height + buttonSpacing),
                        self.buttonSize), "New Game", Menu.buttonColor)

        self.button_Highscores = Button(
            pygame.Rect((upperLeft.x, self.button_NewGame.rect.y +
                         self.button_NewGame.rect.height + buttonSpacing),
                        self.buttonSize), "Highscores", Menu.buttonColor)

        self.button_Quit = Button(
            pygame.Rect((upperLeft.x, self.button_Highscores.rect.y +
                         self.button_Highscores.rect.height + buttonSpacing),
                        self.buttonSize), "Quit Game", Menu.buttonColor)

        self.buttons = [
            self.button_ResumeGame, self.button_NewGame,
            self.button_Highscores, self.button_Quit
        ]

    def pointInRect(self, rect, point):
        if type(rect) != pygame.Rect:
            raise TypeError

        if type(point) not in (tuple, list, pygame.Vector2):
            raise TypeError

        # Test, ob Punkt in Rechteck liegt
        if rect.x < point[0] < rect.x + rect.width:
            if rect.y < point[1] < rect.y + rect.height:
                return True

        return False

    def reload(self):
        # Menue neu laden
        self.active = True
        self.selection = -1
        self.eventHandler.pressed_M_Left = False
        self.eventHandler.pressed_M_Pos = ()
        self.eventHandler.released_M_Left = False
        self.eventHandler.released_M_Pos = ()

        for b in self.buttons:
            b.setColor(Menu.buttonColor)

    def update(self):
        # Buttons hervorheben (Hover)
        if not self.eventHandler.pressed_M_Left:
            for b in self.buttons:
                if self.pointInRect(b.rect, pygame.mouse.get_pos()):
                    if b.color != Menu.buttonColorHover:
                        b.setColor(Menu.buttonColorHover)
                elif b.color != Menu.buttonColor:
                    b.setColor(Menu.buttonColor)

        # Buttons hervorheben (Klick)
        else:
            for b in self.buttons:
                if self.pointInRect(b.rect, self.eventHandler.pressed_M_Pos):
                    if b.color != Menu.buttonColorClick:
                        b.setColor(Color.DARK_GREY)

        if self.eventHandler.released_M_Left:
            # Spiel fortsetzen
            if self.pointInRect(self.button_ResumeGame.rect,
                                self.eventHandler.released_M_Pos):
                if self.pointInRect(self.button_ResumeGame.rect,
                                    self.eventHandler.pressed_M_Pos):
                    self.active = False
                    self.selection = Menu.MenuSelection.resumeGame

            # Neues Spiel
            elif self.pointInRect(self.button_NewGame.rect,
                                  self.eventHandler.released_M_Pos):
                if self.pointInRect(self.button_NewGame.rect,
                                    self.eventHandler.pressed_M_Pos):
                    self.active = False
                    self.selection = Menu.MenuSelection.startNewGame

            # Highscores
            elif self.pointInRect(self.button_Highscores.rect,
                                  self.eventHandler.released_M_Pos):
                if self.pointInRect(self.button_Highscores.rect,
                                    self.eventHandler.pressed_M_Pos):
                    self.active = False
                    self.selection = Menu.MenuSelection.highscores

            # Spiel beenden
            elif self.pointInRect(self.button_Quit.rect,
                                  self.eventHandler.released_M_Pos):
                if self.pointInRect(self.button_Quit.rect,
                                    self.eventHandler.pressed_M_Pos):
                    self.active = False
                    self.selection = Menu.MenuSelection.quit

            # Reset Maus-Events
            self.eventHandler.pressed_M_Left = False
            self.eventHandler.pressed_M_Pos = ()
            self.eventHandler.released_M_Left = False
            self.eventHandler.released_M_Pos = ()

    def draw(self, screen):
        if type(screen) != pygame.Surface:
            raise TypeError

        # Bildschirm schwarz zeichnen
        screen.fill(Color.BLACK)

        # Hintergrund zeichnen
        screen.blit(self.backgroundImg, (0, 0))

        # Buttons zeichnen
        self.button_ResumeGame.draw(screen)
        self.button_NewGame.draw(screen)
        self.button_Highscores.draw(screen)
        self.button_Quit.draw(screen)
コード例 #19
0
        log("Laduje poprzedni modul")
        currentPartPlaying -= 1
        player.play(allParts[currentPartPlaying])
        button.toggleLed(True)


def forButtonPressed():
    global currentPartPlaying

    player.pause()
    currentPartPlaying += 1
    player.play(allParts[currentPartPlaying])
    button.toggleLed(True)


button = Button(18, 24, buttonPressed)
button.makeSignal(3)

rewButton = Button(23, 24, rewButtonPressed)
forButton = Button(25, 24, forButtonPressed)


def loadNextPart():
    global currentPartPlaying
    print(currentPartPlaying)
    log('End of part: ' + str(currentPartPlaying))
    currentPartPlaying += 1
    player.play(allParts[currentPartPlaying])


while True:
コード例 #20
0
ファイル: GameWindow.py プロジェクト: gregcorbett/SciBot
    def create_buttons(self, buttons_on_the_left):
        """Helper method to populate ButtonGroup."""
        # Empty ButtonGroup
        self.buttons.removal_all()

        if buttons_on_the_left:
            forward_button = Button(
                'Forward', GameWindow.BLACK, GameWindow.WHITE,
                Point(self.width + 140,
                      float(self.height) / 2 - 240), (120, 120))

            self.buttons.add(forward_button)

            backward_button = Button(
                'Backward', GameWindow.BLACK, GameWindow.WHITE,
                Point(self.width + 140,
                      float(self.height) / 2 + 20), (120, 120))

            self.buttons.add(backward_button)

            turn_left_button = Button(
                'Turn Left', GameWindow.BLACK, GameWindow.WHITE,
                Point(self.width + 10,
                      float(self.height) / 2 - 110), (120, 120))

            self.buttons.add(turn_left_button)

            turn_right_button = Button(
                'Turn Right', GameWindow.BLACK, GameWindow.WHITE,
                Point(self.width + 270,
                      float(self.height) / 2 - 110), (120, 120))

            self.buttons.add(turn_right_button)

            go_button = Button(
                'Go', GameWindow.BLACK, GameWindow.WHITE,
                Point(self.width + 140,
                      float(self.height) / 2 - 110), (120, 120))

            self.buttons.add(go_button)

            stop_button = Button(
                'Stop', GameWindow.WHITE, GameWindow.RED,
                Point(self.width + 140,
                      float(self.height) / 2 - 110), (120, 120), False)

            self.buttons.add(stop_button)

            reset_button = Button(
                'Reset', GameWindow.BLACK, GameWindow.WHITE,
                Point(self.width + 10,
                      float(self.height) / 2 + 20), (120, 120))

            self.buttons.add(reset_button)

            clear_button = Button(
                'Clear', GameWindow.BLACK, GameWindow.WHITE,
                Point(self.width + 270,
                      float(self.height) / 2 + 20), (120, 120))

            self.buttons.add(clear_button)

        else:
            forward_button = Button(
                'Forward', GameWindow.BLACK, GameWindow.WHITE,
                Point(float(self.width) / 2 - 60, self.height + 10),
                (120, 120))

            self.buttons.add(forward_button)

            backward_button = Button(
                'Backward', GameWindow.BLACK, GameWindow.WHITE,
                Point(float(self.width) / 2 - 60, self.height + 270),
                (120, 120))

            self.buttons.add(backward_button)

            turn_left_button = Button(
                'Turn Left', GameWindow.BLACK, GameWindow.WHITE,
                Point(float(self.width) / 2 - 190, self.height + 140),
                (120, 120))

            self.buttons.add(turn_left_button)

            turn_right_button = Button(
                'Turn Right', GameWindow.BLACK, GameWindow.WHITE,
                Point(float(self.width) / 2 + 70, self.height + 140),
                (120, 120))

            self.buttons.add(turn_right_button)

            go_button = Button(
                'Go', GameWindow.BLACK, GameWindow.WHITE,
                Point(float(self.width) / 2 - 60, self.height + 140),
                (120, 120))

            self.buttons.add(go_button)

            stop_button = Button(
                'Stop', GameWindow.WHITE, GameWindow.RED,
                Point(float(self.width) / 2 - 60, self.height + 140),
                (120, 120), False)

            self.buttons.add(stop_button)

            reset_button = Button(
                'Reset', GameWindow.BLACK, GameWindow.WHITE,
                Point(float(self.width) / 2 - 190, self.height + 270),
                (120, 120))

            self.buttons.add(reset_button)

            clear_button = Button(
                'Clear', GameWindow.BLACK, GameWindow.WHITE,
                Point(float(self.width) / 2 + 70, self.height + 270),
                (120, 120))

            self.buttons.add(clear_button)
コード例 #21
0
    def init_elements(entries, title, width):
        elements = []
        for row in entries:
            element = []
            for entry in row:
                if 'margin' not in entry:
                    entry['margin'] = (0, 0, 0, 0)

                if entry['type'] == 'button':
                    name = ITEM_FONT.render(entry['name'], 1, WHITE)
                    sprite = pg.transform.scale(
                        pg.image.load(BUTTON_INACTIVE).convert_alpha(),
                        BUTTON_SIZE)
                    sprite.blit(
                        name,
                        (sprite.get_width() // 2 - name.get_width() // 2,
                         sprite.get_height() // 2 - name.get_height() // 2))
                    sprite_hover = pg.transform.scale(
                        pg.image.load(BUTTON_ACTIVE).convert_alpha(),
                        BUTTON_SIZE)
                    sprite_hover.blit(
                        name,
                        (sprite_hover.get_width() // 2 - name.get_width() // 2,
                         sprite_hover.get_height() // 2 -
                         name.get_height() // 2))
                    element.append(
                        Button(entry['id'], BUTTON_SIZE, (0, 0), sprite,
                               sprite_hover, entry['margin']))
                elif entry['type'] == 'text_button':
                    name = ITEM_FONT.render(entry['name'], 1, entry['color'])
                    name_hover = ITEM_FONT.render(entry['name'], 1,
                                                  entry['color_hover'])
                    if 'obj' not in entry:
                        entry['obj'] = None
                    element.append(
                        Button(entry['id'], name.get_size(), (0, 0), name,
                               name_hover, entry['margin'], entry['obj']))

                elif entry['type'] == 'item_button':
                    button_size = ITEM_BUTTON_SIZE
                    disabled = 'disabled' in entry
                    if 'subtype' in entry:
                        if entry['subtype'] == 'equip':
                            button_size = EQUIP_BUTTON_SIZE
                    element.append(
                        ItemButton(button_size, (0, 0), entry['item'],
                                   entry['margin'], entry['index'], disabled))
                elif entry['type'] == 'text':
                    if 'font' not in entry:
                        entry['font'] = ITEM_FONT
                    if 'color' not in entry:
                        entry['color'] = WHITE
                    element.append(
                        TextElement(entry['text'], width, (0, 0),
                                    entry['font'], entry['margin'],
                                    entry['color']))
            elements.append(element)
        elements.insert(0, [
            TextElement(title, width, (0, 0), MENU_TITLE_FONT,
                        (len(entries) + 5, 0, 0, 0), WHITE)
        ])
        return elements