コード例 #1
0
ファイル: main.py プロジェクト: tarcisiojr/battle-ship-game
    def _collisions_detec(self):
        if self.player and (pygame.sprite.spritecollideany(
                self.player, self.bullets_group)
                            or pygame.sprite.spritecollideany(
                                self.player, self.enemies_group)):
            event = Event(
                pygame.USEREVENT,
                dict(value=CreateElementEvent(
                    element=_create_animation(self.player))))
            pygame.event.post(event)
            self.player.kill()
            self.player = None
            self.life_panel.update_life(-1)

            if self.life_panel.lives_count <= 0:
                self._create_element(Text('GAME OVER'))
            else:
                event = Event(
                    pygame.USEREVENT,
                    dict(value=CreateDelayedEvent(
                        delay=700, element=self, event=RestartPlayerEvent())))
                pygame.event.post(event)

        items = pygame.sprite.groupcollide(self.enemies_group,
                                           self.bullets_group, True, True)

        for enemy in items.keys():
            event = Event(
                pygame.USEREVENT,
                dict(value=CreateElementEvent(
                    element=_create_animation(enemy))))
            pygame.event.post(event)
            self.score_panel.update_score(100)
コード例 #2
0
    def setup(self, world):
        context = world.find_component("context")
        background = context["background"]

        player_entity = world.find_entity("player")

        # Create a sprite for the header
        self.pause = pygame.sprite.Sprite()
        self.pause.image = self.huge_font.render("You Crashed!", 1,
                                                 (200, 200, 200))
        self.pause.rect = self.pause.image.get_rect(
            centerx=background.get_width() // 2,
            centery=background.get_height() // 4)

        self.pause_help = pygame.sprite.Sprite()
        self.pause_help.image = self.regular_font.render(
            "Try hitting clouds, birds, or airplanes to get money for upgrades!",
            1,
            (200, 200, 200),
        )
        self.pause_help.rect = self.pause_help.image.get_rect(
            centerx=background.get_width() // 2,
            centery=background.get_height() // 2)

        self.pause_currency = pygame.sprite.Sprite()
        self.pause_currency.image = self.regular_font.render(
            f"Current money for upgrades: ${ player_entity.player.currency }",
            1,
            (200, 200, 200),
        )
        self.pause_currency.rect = self.pause_currency.image.get_rect(
            centerx=background.get_width() // 2,
            centery=background.get_height() // 2 + 100,
        )

        # menu setup
        men = [
            ("Quit", lambda: post(Event(PAUSE_QUIT_TO_MENU))),
            ("Save + Continue", lambda: post(Event(PAUSE_SAVE_AND_QUIT))),
        ]

        for idx, m in enumerate(men):
            offset = -((len(men) * 480) // 2) + 240

            rect = pygame.Rect(0, 0, 190, 49)
            rect.centerx = background.get_width() // 2 + (offset + (idx * 480))
            rect.centery = background.get_height() - 100

            button = world.gen_entity()
            button.attach(ButtonComponent(
                rect,
                m[0].upper(),
                m[1],
            ))

        # Put all the sprites we want to render into a sprite group for easy adds and removes
        self.pause_screen = pygame.sprite.Group()
        self.pause_screen.add(self.pause)
        self.pause_screen.add(self.pause_help)
        self.pause_screen.add(self.pause_currency)
コード例 #3
0
ファイル: husband.py プロジェクト: zbysheck/honey
    def _collision_detection(self):

        if not self.player.hidden:
            # husband sight range simulated by rectangle with given size
            width = 100
            height = 70
            block = Block(width, height)

            # compute sight rectangle coordinates in order to detect whether player has been seen or not
            if self._direction == "R":
                block.rect.x = self.rect.x + width
                block.rect.y = self.rect.y
            elif self._direction == "L":
                block.rect.x = self.rect.x - width
                block.rect.y = self.rect.y

            # check if player is in the husband sight
            if pygame.sprite.collide_rect(block, self.player):
                #print "I see you!!!"

                Husband._increase_suspicion_meter(10)
                if Husband._suspicion_value < 100:
                    pygame.event.post(Event(pygame.USEREVENT, {"action": constants.MESSAGE, "message": "I see you!!!", "time": 5}))

            # check if husband caught player
            if pygame.sprite.collide_rect(self, self.player):
                #print "I got you!!!"

                Husband._increase_suspicion_meter(100)

                pygame.event.post(Event(pygame.USEREVENT, {"action": constants.MESSAGE, "message": "GAME OVER", "time": 10, "kill": True}))
コード例 #4
0
ファイル: pause.py プロジェクト: aforry/icarus
    def setup(self, world):
        context = world.find_component("context")
        background = context["background"]

        # Create a sprite for the header
        self.pause = pygame.sprite.Sprite()
        self.pause.image = self.regular_font.render("Paused", 1,
                                                    (200, 200, 200))
        self.pause.rect = self.pause.image.get_rect(
            centerx=background.get_width() // 2,
            centery=background.get_height() // 4)

        options = [
            ("Continue", lambda: post(Event(PAUSE_CONTINUE))),
            ("Save & Quit", lambda: post(Event(PAUSE_SAVE_AND_QUIT))),
            ("Quit to Menu", lambda: post(Event(PAUSE_QUIT_TO_MENU))),
        ]
        for idx, menu_item in enumerate(options):
            offset = 0

            rect = pygame.Rect(0, 0, 200, 60)
            rect.centerx = background.get_width() // 2
            rect.centery = background.get_height() // 2 + (offset + (idx * 70))

            button = world.gen_entity()
            button.attach(
                ButtonComponent(
                    rect,
                    menu_item[0].upper(),
                    menu_item[1],
                ))

        # Put all the sprites we want to render into a sprite group for easy adds and removes
        self.pause_screen = pygame.sprite.Group()
        self.pause_screen.add(self.pause)
コード例 #5
0
ファイル: test_inputcontroller.py プロジェクト: IanPlu/Terra
    def test_invoke_handler_accepting_input(self):
        controller = InputController()
        test_object = TestObject()

        controller.register_handler(InputAction.PRESS, Key.CONFIRM, test_object.test_function)
        self.assertTrue(len(controller.__subscribers__[(InputAction.PRESS, Key.CONFIRM)]) > 0)

        # Try to invoke the handler
        test_event = Event(KEYDOWN, {
            'key': K_RETURN
        })

        controller.invoke_handlers(test_event)
        self.assertTrue(test_object.test_function_has_been_called)

        # Disable accepting input and try to invoke the handler
        test_object.test_function_has_been_called = False
        test_object.accepting_input = False

        # Try to invoke the handler again
        test_event = Event(KEYDOWN, {
            'key': K_RETURN
        })

        controller.invoke_handlers(test_event)
        self.assertFalse(test_object.test_function_has_been_called)
コード例 #6
0
ファイル: menu.py プロジェクト: numberQ/icarus
    def setup(self, world):
        context = world.find_component("context")
        settings = world.find_component("settings")
        background = context["background"]

        # Create our player entity here, and we can extend it once we pick an option
        # player_entity = world.gen_entity()
        # player_entity.attach(PlayerComponent())

        # menu setup
        men = []
        men.append(("New Game", lambda: post(Event(NEW_GAME))))
        if path.exists(
                path.join(user_data_dir(APP_NAME, APP_AUTHOR),
                          settings["save_file"])):
            men.append(("Continue", lambda: post(Event(CONTINUE))))
        men.append(("How to Play", lambda: post(Event(CONTROLS))))
        men.append(("Credits", lambda: post(Event(CREDITS))))
        men.append(("Quit", lambda: post(Event(QUIT))))

        for idx, m in enumerate(men):
            offset = -((len(men) * 60) // 2) + 140

            rect = pygame.Rect(0, 0, 200, 60)
            rect.centerx = background.get_width() // 2
            rect.centery = background.get_height() // 2 + (offset + (idx * 60))

            button = world.gen_entity()
            button.attach(ButtonComponent(
                rect,
                m[0].upper(),
                m[1],
            ))
コード例 #7
0
ファイル: test_play.py プロジェクト: thepinkturtle/gym
def test_keyboard_keyup_event():
    env = DummyPlayEnv()
    game = PlayableGame(env, dummy_keys_to_action())
    event = Event(pygame.KEYDOWN, {"key": RELEVANT_KEY_1})
    game.process_event(event)
    event = Event(pygame.KEYUP, {"key": RELEVANT_KEY_1})
    game.process_event(event)
    assert game.pressed_keys == []
コード例 #8
0
ファイル: TabPanel.py プロジェクト: hasii2011/albow-python-3
    def _augmentEvent(self, theEvent: Event, theIndex: int) -> Event:

        if theEvent is None:
            theEvent = Event(USEREVENT, {'index': theIndex})
        else:
            theEvent.dict['index'] = theIndex

        return theEvent
コード例 #9
0
def envoie_evenement(quoi, nom_parametre=None, valeur_parametre=None):
    if nom_parametre is None or valeur_parametre is None:
        pygame.event.post(Event(USEREVENT, {'quoi': quoi}))
    else:
        pygame.event.post(
            Event(USEREVENT, {
                'quoi': quoi,
                nom_parametre: valeur_parametre
            }))
コード例 #10
0
 def test_arrow_press_release(self, press=True):
     arrow_event = pygame.KEYDOWN if press else pygame.KEYUP
     pygame.event.post(Event(arrow_event, key=pygame.K_RIGHT))
     pygame.event.post(Event(arrow_event, key=pygame.K_LEFT))
     gf.check_events(self.ai_settings, self.stats, self.screen,
                     self.play_button, self.ship, self.aliens, self.bullets)
     actual = [self.ship.moving_right, self.ship.moving_left]
     expected = [press] * 2
     self.assertEqual(expected, actual)
     if press:
         self.test_arrow_press_release(press=False)
コード例 #11
0
 def test_play_button_click(self):
     """Test if game is activated and reset when the play button is clicked"""
     pygame.event.post(Event(pygame.KEYDOWN, key=pygame.K_SPACE))
     screen_rect = self.screen.get_rect()
     pygame.event.post(Event(pygame.MOUSEBUTTONDOWN))
     gf.check_events(self.ai_settings, self.screen, self.stats,
                     self.play_button, self.ship, self.aliens, self.bullets)
     full_fleet = Group()
     gf.create_fleet(self.ai_settings, self.screen, self.ship, full_fleet)
     actual = self.stats.game_active and (len(
         self.aliens) == len(full_fleet) and len(self.bullets) == 0)
     self.assertEqual(True, actual)
コード例 #12
0
ファイル: aiplayer.py プロジェクト: IanPlu/Terra
    def move_leftover_pieces(self, leftovers):
        for piece in leftovers:
            movement_range = piece.attr(Attribute.MOVEMENT_RANGE)
            movement_type = piece.attr(Attribute.MOVEMENT_TYPE)

            if movement_range > 0:
                if (piece.gx, piece.gy) in self.planned_occupied_coords:
                    valid_tiles = self.map.get_tiles_in_range(
                        piece.gx, piece.gy, 0, movement_range, movement_type)

                    # Remove planned coords from valid tiles
                    valid_tiles = list(
                        set(valid_tiles) - set(self.planned_occupied_coords))

                    # Pick an arbitrary tile and pathfind to it
                    # destination = valid_tiles[randint(0, len(valid_tiles) - 1)]
                    if len(valid_tiles) == 0:
                        # No possible valid destination! Just destroy ourselves
                        piece.set_order(
                            Event(USEREVENT, {
                                'option': Option.MENU_DEMOLISH_SELF,
                            }))
                    else:
                        destination = valid_tiles[0]
                        path = piece.get_path_to_target(
                            destination,
                            self.path_cache,
                            self.planned_occupied_coords,
                            movement_type=movement_type)
                        final_goal = piece.step_along_path(
                            path, self.planned_occupied_coords)

                        if final_goal == (piece.gx, piece.gy):
                            # We couldn't find a path to get out of the way, so delete ourselves
                            piece.set_order(
                                Event(USEREVENT, {
                                    'option': Option.MENU_DEMOLISH_SELF,
                                }))
                        else:
                            # Update the planned occupied coords, issue the order
                            self.planned_occupied_coords.append(final_goal)

                            piece.set_order(
                                Event(
                                    USEREVENT, {
                                        'option': Option.MENU_MOVE,
                                        'dx': final_goal[0],
                                        'dy': final_goal[1],
                                    }))
                else:
                    # Add ourselves to the planned occupied coords
                    self.planned_occupied_coords.append((piece.gx, piece.gy))
コード例 #13
0
ファイル: Alien.py プロジェクト: tobsan/whutshmup
    def update(self, *_):
        super(Bomber, self).update()

        if self.counter % 75 == 0:
            (x, y) = self.get_position()
            s_1 = self.__create_shot()
            s_1.set_position((x - self.get_width() / 3, y))
            s_2 = self.__create_shot()
            s_2.set_position((x + self.get_width() / 3, y))
            e_1 = Event(ENEMY_FIRE, ship=self, shot=s_1)
            e_2 = Event(ENEMY_FIRE, ship=self, shot=s_2)
            post(e_1)
            post(e_2)
コード例 #14
0
    def __init__(self, app, name: str):
        super().__init__(app, name)
        self.custom_level = CustomLevel()

        self.images = {'free_cell': Surface((128, 128), SRCALPHA),
                       'wall': Surface((128, 128), SRCALPHA),
                       'box_cell': Surface((128, 128), SRCALPHA),
                       'player': Surface((128, 128), SRCALPHA),
                       'box': Surface((128, 128), SRCALPHA)}

        self.images['free_cell'].blit(FREE_CELL_IMAGE, (0, 0))
        self.images['wall'].blit(WALL_IMAGE, (0, 0))
        self.images['box_cell'].blit(BOX_CELL_IMAGE, (0, 0))
        self.images['player'].blit(PLAYER_IMAGE, (0, 0))
        self.images['box'].blit(BOX_IMAGE, (0, 0))

        self.dragged_picture = None
        self.still_pictures = [StillPicture(' '),
                               StillPicture('b'),
                               StillPicture('p'),
                               StillPicture('x')]

        self.level_name_box = TextBox(
            self.application.screen,
            (self.application.screen.get_width() / 2 - TEXTBOX_SIZE[0] / 2, 10))
        self.level_name_box.str = _('my level')

        self.cell_size = None
        self.offset_x, self.offset_y = None, None
        self.symbols_to_images = {}
        self.calculate_cell_size()

        self.buttons = [
            Button(
                _('MENU'), self.application.screen,
                Event(pygame.USEREVENT,
                      {'app': self.application, 'name': '__main__'}), (0, 0)),
            Button(
                _('SAVE'),
                self.application.screen,
                Event(pygame.USEREVENT, {'app': self.application, 'name': 'save'}),
                (self.application.screen.get_width() - BUTTON_SIZE[0], 0)),
            Button(
                'OK',
                self.application.screen,
                Event(pygame.USEREVENT, {'app': self.application, 'name': 'ok'}),
                (self.level_name_box.rect_box.right + 10, self.level_name_box.rect.top),
                button_size=(40, 30))
        ]
コード例 #15
0
ファイル: menu.py プロジェクト: IdeasFactorie/SoleMates
 def handle_menu_click(self, menu_item):
     if menu_item.item_id == ITEM_NEW_GAME:
         self._cur_menu = MENU_DIFFICULTY
     elif menu_item.item_id == ITEM_LEVEL_SELECT:
         self._cur_menu = MENU_LEVEL_SELECT
     elif (menu_item.item_id == ITEM_EASY or
           menu_item.item_id == ITEM_HARD or
           menu_item.item_id == ITEM_MEDIUM):
         pygame.event.post(Event(START_LEVEL1_EVENT, dict()))
     elif menu_item.item_id == ITEM_LEVEL_1:
         pygame.event.post(Event(START_LEVEL1_EVENT, dict()))
     elif menu_item.item_id == ITEM_LEVEL_2:
         pygame.event.post(Event(START_LEVEL2_EVENT, dict()))
     elif menu_item.item_id == ITEM_BONUS_LEVEL:
         pygame.event.post(Event(START_BONUS_LEVEL_EVENT, dict()))
コード例 #16
0
ファイル: draggable.py プロジェクト: YannThorimbert/PyMap2D
 def _drag_move(self, event):
     ev_drag = Event(constants.THORPY_EVENT,
                     id=constants.EVENT_DRAG,
                     el=self)
     post(ev_drag)
     self.move((self._constraints[0] * event.rel[0],
                self._constraints[1] * event.rel[1]))
コード例 #17
0
ファイル: test_play.py プロジェクト: thepinkturtle/gym
def test_keyboard_quit_event():
    env = DummyPlayEnv()
    game = PlayableGame(env, dummy_keys_to_action())
    event = Event(pygame.KEYDOWN, {"key": pygame.K_ESCAPE})
    assert game.running is True
    game.process_event(event)
    assert game.running is False
コード例 #18
0
def handle():
    global running, moving
    for e in pygame.event.get():
        if e.type == QUIT:
            running = False
        elif e.type == KEYDOWN:
            if e.key in MOVES.keys():
                moving = (moving[0] + MOVES[e.key][0], moving[1] + MOVES[e.key][1]) 
        elif e.type == KEYUP:
            if e.key in MOVES.keys():
                moving = (moving[0] - MOVES[e.key][0], moving[1] - MOVES[e.key][1])
                
        elif e.type == MOUSEBUTTONDOWN:
            pos = slide_x + e.pos[0]/TILE, slide_y + e.pos[1]/TILE
            send(Event(GETINFO, {'pos':pos}))
            
        elif e.type == GOTO:
            goto(e.x, e.y)
        elif e.type == MESSAGE:
            settext(e.msg)
        elif e.type == SYSTEM:
            print e.msg
        elif e.type == SETOBJECT:
            objmap[e.y][e.x] = e.obj
        
        elif e.type == TWITTER:
            print "\nAmigos Online:"
            print e.msg
コード例 #19
0
ファイル: equip.py プロジェクト: octotep/icarus
    def update(self, events, world):
        settings = world.find_component("settings")

        for event in events:
            if event.type == EQUIP_QUIT:
                return SceneManager.new_root(scenes.title.TitleScene())
            if event.type == EQUIP_BUY_CLOUD_SLEEVES:
                self._shop(settings["cloudSleevesCost"], "cloud_sleeves", world)
                self.teardown(world)
                self.setup(world)
            if event.type == EQUIP_BUY_WINGS:
                self._shop(settings["wingsCost"], "wings", world)
                self.teardown(world)
                self.setup(world)
            if event.type == EQUIP_BUY_JET_BOOTS:
                self._shop(settings["jetBootsCost"], "jet_boots", world)
                self.teardown(world)
                self.setup(world)
            if event.type == EQUIP_SAVE_AND_START:
                self._save(settings["save_file"], world)
                self.teardown(world)
                post(Event(LOAD))
                return SceneManager.pop()

        world.process_all_systems(events)
コード例 #20
0
ファイル: 04-eventos.py プロジェクト: xjzpguob/pygame-mmorpg
def move((inc_x, inc_y)):
    if inc_x != 0 or inc_y != 0:
        e = Event(GOTO, {
            'x': slide_x + inc_x + MIDDLE[0],
            'y': slide_y + inc_y + MIDDLE[1]
        })
        pygame.event.post(e)
コード例 #21
0
ファイル: test_play.py プロジェクト: thepinkturtle/gym
def test_pygame_quit_event():
    env = DummyPlayEnv()
    game = PlayableGame(env, dummy_keys_to_action())
    event = Event(pygame.QUIT)
    assert game.running is True
    game.process_event(event)
    assert game.running is False
コード例 #22
0
def poll():
    """Get the next pending event if exists. Otherwise, return pygame.NOEVENT."""
    pump()
    try:
        return g_events.get(block=False)
    except Queue.Empty:
        return Event(pygame.NOEVENT)
コード例 #23
0
def POST_SPECIAL_FLAG_CHANGE(text):
    GUI_SCREEN_SPECIAL_FLAGS_CHANGED: Union[Event, None] = Event(
        pygame.USEREVENT, {
            'user_type': 'screen_flag_changed',
            'text': text
        })
    pygame.event.post(GUI_SCREEN_SPECIAL_FLAGS_CHANGED)
コード例 #24
0
 def event_handler(self, event):
     # When the menu is open, set the selected value and close the menu
     # When the menu is closed, open the menu
     for sprite in self.sprites():
         if sprite.rect.collidepoint(mouse.get_pos()) \
                 and event.type == MOUSEBUTTONDOWN:
             if self.menu_open:
                 if not sprite.value:
                     raise Exception(
                         "Invalid option clicked, Selector class does not have the property option"
                     )
                 self.value = sprite.value
                 PyEvent.post(
                     Event(
                         UIManager.BUTTON_EVENT_ID, {
                             'component_id': self.component_id,
                             'event': UIDropdownMenu.ON_VALUE_CHANGED,
                             'value': self.value
                         }))
                 self.close()
                 return
             else:
                 self.open()
                 return
     # close the menu when outside the menu is clicked
     if event.type == MOUSEBUTTONDOWN and self.menu_open:
         self.close()
コード例 #25
0
    def update(self, *_):
        """
        Overrides the update in Ship. For the player, as with the aliens, this
        mostly handles firing, but it also makes sure that the image displayed
        when blitting is the one currently active from the animation
        """

        # Maybe change the animation image
        self.__animation.update()
        # And in that case, this changes, too!
        self.set_image(self.__animation.get_image())
        self.mask = self.__hitmask

        super(Player, self).update()

        # Fires more when highpowered
        if self.__firing and not self.has_target():
            if self.__firecounter % 10 == 0:
                self.__firecounter = 1
                shots = min(2 + self.__power, 6)
                sound = True
                for i in range(shots):
                    shot = self.__create_shot(sound)
                    for _ in range(i):
                        shot.update()
                    post(Event(USER_FIRE, shot = shot))
                    sound = False
            else: self.__firecounter += 1
        elif self.__firecounter != 0:
            # Prevents abuse of the fire button
            self.__firecounter = (self.__firecounter + 1) % 10
コード例 #26
0
 def test_space_press_responce(self):
     """Check if a bullet gets fired when space is pressed"""
     pygame.event.post(Event(pygame.KEYDOWN, key=pygame.K_SPACE))
     gf.check_events(self.ai_settings, self.stats, self.screen,
                     self.play_button, self.ship, self.aliens, self.bullets)
     actual = len(self.bullets)
     expected = 1
     self.assertEqual(expected, actual)
コード例 #27
0
def poll():
    """Get the next pending event if exists. Otherwise, return pygame.NOEVENT."""
    pump()
    try:
        result = g_events.get(block=False)
        return _recordEvents([result])[0]
    except Queue.Empty:
        return Event(pygame.NOEVENT)
コード例 #28
0
 def _press(self):
     state_ok = self.current_state == self._states[STATE_NORMAL]
     if state_ok:
         self.change_state(STATE_PRESSED)
         self._hover()
         ev_press = Event(THORPY_EVENT, id=EVENT_PRESS, el=self)
         post(ev_press)
         self._remove_help()
コード例 #29
0
def build_event(event_type_id: int, **kwargs) -> Event:
    """
    Pass-through function to build a PyGame event
    :param event_type_id: int
    :param kwargs: mixed, key-value data passed to the event
    :return: Event
    """
    return Event(event_type_id, **kwargs)
コード例 #30
0
ファイル: main.py プロジェクト: tarcisiojr/battle-ship-game
 def _random_move(self):
     event = Event(
         pygame.USEREVENT,
         dict(value=CreateDelayedEvent(delay=random.randint(
             *self.config.movement_freq),
                                       element=self,
                                       event=ChangeDirectionEvent())))
     pygame.event.post(event)
コード例 #31
0
ファイル: root.py プロジェクト: Khroki/MCEdit-Unified
 def get_mouse_for(widget):
     last = last_mouse_event
     event = Event(0, last.dict)
     event.dict['local'] = widget.global_to_local(event.pos)
     add_modifiers(event)
     return event