示例#1
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
示例#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)
 def set_hearts(self, num):
     if 0 < num <= self.max_hp:
         if self.hp - 1 == num:
             event.post(event.Event(53, {}))
         self.hp = num
         self.heart_sprites.empty()
         for i in range(self.max_hp):
             spr = sprite.Sprite()
             if i < self.hp:
                 spr.image = self.heart
             else:
                 spr.image = self.heart_pass
             spr.image.set_colorkey((255, 255, 255))
             spr.rect = spr.image.get_rect()
             spr.rect.center = (int(self.rect_size * 1.5) * (i + 1),
                                self.rect_size)
             self.heart_sprites.add(spr)
     elif num <= 0:
         self.hp = num
         self.heart_sprites.empty()
         for i in range(self.max_hp):
             spr = sprite.Sprite()
             if i < self.hp:
                 spr.image = self.heart
             else:
                 spr.image = self.heart_pass
             spr.image.set_colorkey((255, 255, 255))
             spr.rect = spr.image.get_rect()
             spr.rect.center = (int(self.rect_size * 1.5) * (i + 1),
                                self.rect_size)
             self.heart_sprites.add(spr)
         event.post(event.Event(31, {}))
示例#4
0
    def unlaunch(self, what):
        ev = event.Event(constants.THORPY_EVENT, id=constants.EVENT_UNLAUNCH,
                        launcher=self, what=what)
        event.post(ev)
##        print(ev, "posted")
        self.remove_from_current_menu()
        self.postlaunch()
示例#5
0
文件: game.py 项目: bry/pybomber2
    def exchangeInput(self):
        """Exchange a round of inputs in a network-safe
           manner.
        """
        inputs = []
        for player in self.playerList:
            inp = self.getPlayerInput(player)
            debug("Player " + str(player.name) +\
                  " input: " + inp + "\n")
            if self.record and inp != NOOP:
                self.playerInputFileList[int(player.name)].write( \
                  str(self.totalGameLoops) +\
                  ',' + inp + '\n')

            # Check players input
            if len(inp) != len(UP):
                print "Bad input from player", player.getHandle()
                inp = DISCONNECT

            # Can quit the game from end splash screen
            if inp == QUITCOMMAND:
                sys.exit()

            inputs.append((player.name, inp))
            for netplayer in self.playerList:
                netplayer.sendCommand(player.getBroadcastable())

        self.totalGameLoops += 1
        # Clear all useless events
        eventsWeWant = events.get([KEYDOWN, KEYUP, JOYBUTTONDOWN,\
                                   JOYAXISMOTION])
        events.clear()
        for event in eventsWeWant:
            events.post(event)
        return inputs
示例#6
0
文件: util.py 项目: trbail01/Jeopardy
 def _end(self):
     """
     Reset the timer and post self.event to the queue. Called when time reaches
     self._endTime.
     """
     self.reset()
     pgevent.post(pgevent.Event(self.event))
示例#7
0
def post_event(event: Event) -> None:
    """
    Post an event into the PyGame event queue (SDL process)
    :param event: Event
    :return: None
    """
    post(event)
示例#8
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)
示例#9
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)
 def get_damage(self):
     if not self.invulnerable:
         event.post(event.Event(50, {}))
         self.hp = self.hp - 1
         self.invulnerable = True
     else:
         event.post(event.Event(51, {}))
示例#11
0
文件: main.py 项目: mjs/ldnpydojo
def start_game():

    #needs to be called before pygame.init
    pygame.mixer.pre_init(22050, -16, 2, 1024)

    window = Window()
    window.init()

    pygame.init()

    sounds = Sounds()
    sounds.init()
    window.sounds = sounds
    pygame.mixer.set_num_channels(32)

    # meta game loop
    while True:
        sounds.play_music("intro", loop=1)
        intro_main(window, handle_events)

        # so we can mix more channels at once.  pygame defaults to 8.
        #sounds.play("jump1")
        #sounds.play("hit1")
        #sounds.play("goal1")
        sounds.set_music_tracks(['track-one', 'track-two'])

        world = World()
        world.stage = 2
        populate(world, window)

        def count_leaves():
            no_leaves = 0
            for item in world.items:
                if item.role == "Bough":
                    no_leaves = no_leaves + 1
            return no_leaves

        CleanUp_Event = pygame.event.Event(CLEANUP,
                                           message="Cleaning Up Your shit")
        pygame.time.set_timer(CLEANUP, 1000)

        TickTock = pygame.event.Event(
            TICK_TOCK, message="TickTock goes the Ticking Clock")
        pygame.time.set_timer(TICK_TOCK, int(90000 / count_leaves()))

        AddCherry = pygame.event.Event(ADDCHERRY, message="Ooooo Cherry")
        pygame.time.set_timer(ADDCHERRY, int(90000 / 5))

        AddOwange = pygame.event.Event(ADDOWANGE, message="Ooooo owange")
        pygame.time.set_timer(ADDOWANGE, int(1000 * 5))

        for i in range(3):
            event.post(AddOwange)

        pygame.time.set_timer(BIRDY, 1000 * 7)

        render = Render(window, world)
        quit = runloop(window, world, render)
        if quit:
            return
示例#12
0
 def launch(self):
     ev = event.Event(constants.THORPY_EVENT,
                      id=constants.EVENT_LAUNCH,
                      launcher=self)
     event.post(ev)
     self.prelaunch()
     self.add_to_current_menu()
示例#13
0
文件: game.py 项目: bry/pybomber2
    def exchangeInput(self):
        """Exchange a round of inputs in a network-safe
           manner.
        """
        inputs = []
        for player in self.playerList:
            inp = self.getPlayerInput(player)
            debug("Player " + str(player.name) +\
                  " input: " + inp + "\n")
            if self.record and inp != NOOP:
                self.playerInputFileList[int(player.name)].write( \
                  str(self.totalGameLoops) +\
                  ',' + inp + '\n')

            # Check players input
            if len(inp) != len(UP):
                print "Bad input from player",player.getHandle()
                inp = DISCONNECT

            # Can quit the game from end splash screen
            if inp == QUITCOMMAND:
                sys.exit()

            inputs.append((player.name,inp))
            for netplayer in self.playerList:
                netplayer.sendCommand(player.getBroadcastable())

        self.totalGameLoops += 1
        # Clear all useless events
        eventsWeWant = events.get([KEYDOWN, KEYUP, JOYBUTTONDOWN,\
                                   JOYAXISMOTION])
        events.clear()
        for event in eventsWeWant:
            events.post(event)
        return inputs
示例#14
0
 def check_died(self, scene):
     """
     Check whether this enemy has died.
     """
     if self.hp <= 0:
         scene.enemyGroup.remove(self)
         event.post(event.Event(USEREVENT, code=CAESARDEAD))
示例#15
0
    def get(self):
        events.pump()
        notmine = []
        inp = NOOP
        for event in events.get():
            if event.type == QUIT:
                inp = QUITCOMMAND
            if ((event.type == KEYDOWN or event.type == KEYUP)
                and self.keyDict.has_key(event.key)):
                if event.type == KEYDOWN:
                    inp = self.keyDict[event.key]
                elif event.type == KEYUP:
                    keyDown = key.get_pressed()
                    if(keyDown[self.commandDict[UP]]):
                        inp = UP
                    elif(keyDown[self.commandDict[DOWN]]):
                        inp = DOWN
                    elif(keyDown[self.commandDict[LEFT]]):
                        inp = LEFT
                    elif(keyDown[self.commandDict[RIGHT]]):
                        inp = RIGHT
                    else:
                        inp = STOP
                else:
                    raise UnexpectedInput
            else:
                notmine.append(event)

        for yours in notmine:
            events.post(yours)

        return inp
示例#16
0
 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
 def _end(self):
     """
     Reset the timer and post self.event to the queue. Called when time reaches
     self._endTime.
     """
     self.reset()
     pgevent.post(pgevent.Event(self.event))
示例#18
0
    def get(self):
        events.pump()
        notmine = []
        inp = NOOP
        for event in events.get():
            if event.type == QUIT:
                inp = QUITCOMMAND
            if ((event.type == KEYDOWN or event.type == KEYUP)
                    and self.keyDict.has_key(event.key)):
                if event.type == KEYDOWN:
                    inp = self.keyDict[event.key]
                elif event.type == KEYUP:
                    keyDown = key.get_pressed()
                    if (keyDown[self.commandDict[UP]]):
                        inp = UP
                    elif (keyDown[self.commandDict[DOWN]]):
                        inp = DOWN
                    elif (keyDown[self.commandDict[LEFT]]):
                        inp = LEFT
                    elif (keyDown[self.commandDict[RIGHT]]):
                        inp = RIGHT
                    else:
                        inp = STOP
                else:
                    raise UnexpectedInput
            else:
                notmine.append(event)

        for yours in notmine:
            events.post(yours)

        return inp
示例#19
0
def emulate_ok_press(element=None, inserters=None):
    if inserters:
        for i in inserters:
            i.K_RETURN_pressed()
    e = event.Event(constants.THORPY_EVENT, id=constants.EVENT_DONE, el=element)
    event.post(e)
    functions.quit_menu_func()
示例#20
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],
            ))
示例#21
0
    def train(self):
        # initialize the initial observation of the agent
        obs = self.state
        for t in range(1, self.train_nums):
            best_action, q_values = self.model.action_value(obs[None])  # input the obs to the network model
            action = self.get_action(best_action)   # get the real action
            if best_action == 1:
                event.post(self.JUMP)
            self.step()
            next_obs, reward, done = self.state, self.reward, not self.game_active    # take the action in the env to return s', r, done
            self.store_transition(obs, action, reward, next_obs, done)  # store that transition into replay butter
            self.num_in_buffer = min(self.num_in_buffer + 1, self.buffer_size)

            if t > self.start_learning:  # start learning
                losses = self.train_step()
                if t % 1000 == 0:
                    print('losses each 1000 steps: ', losses)

            if t % self.target_update_iter == 0:
                self.update_target_model()
            if done:
                self.reset()
                self.game_active = True
                obs = self.state
            else:
                obs = next_obs
示例#22
0
    def drop(self, borderLineHeight):
        # TODO add a fast drop function...
        if self.stuck: return
        vector = Vector(0, BLOCK_SIZE)

        for polygon in self.polygons:
            polygon.move(vector)

        self.rotationPoint += vector

        # TODO find a better solution to this. we cant use infinity
        linePoints = [(-100, borderLineHeight), (10000, borderLineHeight)]
        for polygon in self.polygons:
            for point in polygon.points:
                pVec = Vector(*point)
                lVec = Vector(0, borderLineHeight)
                delta = pVec - lVec
                if abs(delta.posY) == 0:
                    self.stuck = True
        # TODO fix unessecery filter
        otherTetros = list(
            filter(lambda tetro: tetro != self, self.otherTetrosOnScreen))
        print(otherTetros)
        for otherTetro in otherTetros:
            if collision.checkCollision(self, otherTetro):
                self.stuck = True
        if self.stuck:
            event.post(event.Event(SPAWN_EVENT))
示例#23
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()
示例#24
0
    def shoot(self):
        if not self.alive():
            return

        if random() < self.shoot_chance:
            event.post(event.Event(CUSTOM_EVENTS['ADD_ALIEN_BULLET'], {
                'particle': self.get_bullet()
            }))
示例#25
0
    def pressKey(self, newEvent, controller):
        # Quit everything
        if (newEvent.key == gc.USER_KEYS_DES.get('ESCAPE', None)):
            event.post(event.Event(pgc.QUIT))

        # Send a move event to an attached NTController
        elif ('HAT_' in gc.USER_KEYS_NUM.get(newEvent.key, None)):
            controller.modHat(gc.CONTR_BINDS.get(newEvent.key, None), 1.0)
示例#26
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()
示例#27
0
 def _reaction_drag(self, event):
     if self.current_state_key == constants.STATE_PRESSED:
         if self.will_be_inside(event.rel[0]):
             self.dragmove(event.rel[0])
             drag_event = pygevent.Event(constants.THORPY_EVENT,
                                         name=constants.EVENT_SLIDE,
                                         el=self.father)
             pygevent.post(drag_event)
示例#28
0
    def _force_unpress(self):
        self._count = 0
        Clickable._unpress(self)
##        self._unhover_noblit()
        ev_untog = Event(constants.THORPY_EVENT,
                        id=constants.EVENT_UNTOGGLE, el=self)
        post(ev_untog)
        self.toggled = False
示例#29
0
  def broadcast(self, event_type, event_values):
    real_type = USEREVENT if type(event_type) == str else event_type

    if real_type == USEREVENT:
      event_values['_name'] = event_type 

    event = Event(real_type, event_values)
    post(event)
示例#30
0
    def _force_unpress(self):
        self._count = 0
        Clickable._unpress(self)
##        self._unhover_noblit()
        ev_untog = Event(constants.THORPY_EVENT,
                        id=constants.EVENT_UNTOGGLE, el=self)
        post(ev_untog)
        self.toggled = False
示例#31
0
 def _reaction_drag(self, event):
     if self.current_state_key == constants.STATE_PRESSED:
         if self.will_be_inside(event.rel[0]):
             self.dragmove(event.rel[0])
             drag_event = pygevent.Event(constants.THORPY_EVENT,
                                         id=constants.EVENT_SLIDE,
                                         el=self.father.father)
             pygevent.post(drag_event)
示例#32
0
 def _press(self):
     Clickable._press(self)
     self._count += 1
     if not self.toggled:
         ev_tog = Event(constants.THORPY_EVENT, id=constants.EVENT_TOGGLE,
                         el=self)
         post(ev_tog)
         self.toggled = True
示例#33
0
 def clicked(self, mouse_event):
     if self.rect.collidepoint(mouse_event.pos):
         event.post(
             event.Event(self.event, {
                 "name": self.name,
                 "command": "push",
                 "scene": self.next_scene
             }))
示例#34
0
 def onStep(self):
     c1, c2, dd = self.getKeyframes()
     from pygame import event
     if (dd > 0.5):
         event.post(c2)
     else:
         event.post(c1)
     pass
示例#35
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()
示例#36
0
 def _press(self):
     Clickable._press(self)
     self._count += 1
     if not self.toggled:
         ev_tog = Event(constants.THORPY_EVENT, id=constants.EVENT_TOGGLE,
                         el=self)
         post(ev_tog)
         self.toggled = True
示例#37
0
文件: Alien.py 项目: tobsan/whutshmup
    def update(self, *_):
        super(Alien, self).update()

        # Should we fire?
        if self.counter % 30 == 0:
            shot = self.__create_shot()
            fire = Event(ENEMY_FIRE, ship=self, shot=shot)
            post(fire)
示例#38
0
 def _press(self):
     self.unblit()
     self.change_state(constants.STATE_PRESSED)
     self.blit()
     self.update()
     ev_press = Event(constants.THORPY_EVENT,
                      id=constants.EVENT_PRESS,
                      el=self)
     post(ev_press)
示例#39
0
 def _press(self):
     self.unblit()
     self.change_state(constants.STATE_PRESSED)
     self.blit()
     self.update()
     ev_press = Event(constants.THORPY_EVENT,
                      name=constants.EVENT_PRESS,
                      el=self)
     post(ev_press)
示例#40
0
 def _unpress(self):
     state_ok = (self.current_state_key == constants.STATE_PRESSED)
     if state_ok:
         self.unblit()
         self.change_state(constants.STATE_NORMAL)
         self.blit()
         self.update()
         ev_unpress = Event(constants.THORPY_EVENT, id=constants.EVENT_UNPRESS, el=self)
         post(ev_unpress)
示例#41
0
 def quit_save(self):
     ev = Event(constants.THORPY_EVENT,
                name=constants.EVENT_DONE,
                el=self)
     post(ev)
     for (varset, varname), handler in iter(self.handlers.items()):
         # si varset
         self.varsets[varset].set_value(varname, handler.get_value())
         # sinon si link
         # sinon si fonction
     functions.quit_menu_func()
示例#42
0
 def _press(self):
     state_ok = self.current_state == self._states[constants.STATE_NORMAL]
     if state_ok:
         self.unblit()
         self.change_state(constants.STATE_PRESSED)
         self.blit()
         self.update()
         ev_press = Event(constants.THORPY_EVENT,
                          id=constants.EVENT_PRESS,
                          el=self)
         post(ev_press)
示例#43
0
    def shutdown_gate(self):

        if self.gate_active:
            print "Shutting gate down"
            self.gate_active = False
            self.dialed_symbols = []
            event.post(Event(EventType.SOUND_STOP, {
                "value": "gate-loop"
            }))
            event.post(Event(EventType.SOUND_PLAY, {
                "value": "gate-close"
            }))
示例#44
0
    def get(self):
        events.pump()
        notmine = []
        inp = NOOP
        for event in events.get():
            if event.type == QUIT:
                inp = QUITCOMMAND

            elif (event.dict
                and event.dict.has_key('joy')
                and event.dict['joy'] == self.joyEnabled.get_id()):
                if event.type == JOYBUTTONDOWN:
                    if self.joyEnabled.get_button(0):
                        inp = BOMB
                    elif self.joyEnabled.get_button(1):
                        inp = ACTION
                elif event.type == JOYAXISMOTION:
                    if self.joyEnabled.get_numaxes() >= 6:
                        if self.joyEnabled.get_axis(5) > 0.2:
                            inp = DOWN
                        elif self.joyEnabled.get_axis(5) < -0.2:
                            inp = UP
                        elif self.joyEnabled.get_axis(4) < -0.2:
                            inp = LEFT
                        elif self.joyEnabled.get_axis(4) > 0.2:
                            inp = RIGHT
                        elif self.joyEnabled.get_axis(5) <= 0.1 and\
                                 self.joyEnabled.get_axis(5) >= -0.1 and\
                                 self.joyEnabled.get_axis(4) <= 0.1 and\
                                 self.joyEnabled.get_axis(4) >= -0.1:
                            inp = STOP
                    
                    if self.joyEnabled.get_axis(1) > 0.2:
                        inp = DOWN
                    elif self.joyEnabled.get_axis(1) < -0.2:
                        inp = UP
                    elif self.joyEnabled.get_axis(0) < -0.2:
                        inp = LEFT
                    elif self.joyEnabled.get_axis(0) > 0.2:
                        inp = RIGHT
                    elif self.joyEnabled.get_axis(0) <= 0.1 and\
                             self.joyEnabled.get_axis(0) >= -0.1 and\
                             self.joyEnabled.get_axis(1) <= 0.1 and\
                             self.joyEnabled.get_axis(1) >= -0.1:
                        inp = STOP
            else:
                notmine.append(event)

        for yours in notmine:
            events.post(yours)

        return inp
示例#45
0
    def test_get(self):
        # __doc__ (as of 2008-08-02) for pygame.fastevent.get:
    
          # pygame.fastevent.get() -> list of Events
          # get all events from the queue

        for _ in range(1, 11):
            event.post(event.Event(pygame.USEREVENT))
        
        self.assertEquals (
            [e.type for e in fastevent.get()], [pygame.USEREVENT] * 10,
            race_condition_notification
        )
示例#46
0
文件: mesh.py 项目: rparrapy/maze
    def __init__(self, tube, is_initiator, tube_id):
        super(PygameTube, self).__init__(tube, DBUS_PATH)
        log.info( 'PygameTube init' )
        self.tube = tube
        self.is_initiator = is_initiator
        self.entered = False
        self.ordered_bus_names = []
        PEvent.post(PEvent.Event(CONNECT, id=tube_id))

        if not self.is_initiator:
            self.tube.add_signal_receiver(self.new_participant_cb, 'NewParticipants', DBUS_IFACE, path=DBUS_PATH)
        self.tube.watch_participants(self.participant_change_cb)
        self.tube.add_signal_receiver(self.broadcast_cb, 'Broadcast', DBUS_IFACE, path=DBUS_PATH, sender_keyword='sender')
示例#47
0
 def test_wait(self):
 
     # __doc__ (as of 2008-08-02) for pygame.fastevent.wait:
 
       # pygame.fastevent.wait() -> Event
       # wait for an event
       # 
       # Returns the current event on the queue. If there are no messages
       # waiting on the queue, this will not return until one is
       # available. Sometimes it is important to use this wait to get
       # events from the queue, it will allow your application to idle
       # when the user isn't doing anything with it.
     
     event.post(pygame.event.Event(1))
     self.assertEquals(fastevent.wait().type, 1, race_condition_notification)
示例#48
0
 def exit(self):
     key_set_repeat(parameters.KEY_DELAY, parameters.KEY_INTERVAL)
     if self._activated:
         functions.debug_msg("Leaving inserter ", self)
         self._inserted = self._value
         self._urbu()
         mouse_set_visible(True)
         self.cursor.exit()
         self._activated = False
         event_quit = event.Event(constants.THORPY_EVENT,
                                id=constants.EVENT_INSERT,
                                el=self,
                                value=self._value)
         event.post(event_quit)
         if self._varlink_func:
             self._varlink_func(self._value)
示例#49
0
def _endmusic_callback():
    global _current_music, _queue_music, _music_pos, _music_pos_time
    if _endmusic_event is not None and sdl.SDL_WasInit(sdl.SDL_INIT_AUDIO):
        event.post(event.Event(_endmusic_event))

    if _queue_music:
        if _current_music:
            sdl.Mix_FreeMusic(_current_music)
        _current_music = _queue_music
        _queue_music = None
        sdl.Mix_HookMusicFinished(_endmusic_callback)
        _music_pos = 0
        sdl.Mix_PlayMusic(_current_music, 0)
    else:
        _music_pos_time = -1
        sdl.Mix_SetPostMix(ffi.NULL, ffi.NULL)
示例#50
0
 def _ddlf_reaction_press(self, event):
     x, y = self._get_dirviewer_coords(event.pos)
     lift = False
     if self._lift:
         lift = self._lift.collide(event.pos)
     if x < self._dv.size[0] and not lift:
         self._clicked = self._dv.get_txt_at_pix(x, y)
         if self._clicked:
             if self._menu:
                 self._menu.set_leave()
             else:
                 event_ddl = pygevent.Event(constants.THORPY_EVENT,
                                         id=constants.EVENT_DDL,
                                         el=self,
                                         value=self._clicked)
                 pygevent.post(event_ddl)
                 return self._clicked
示例#51
0
 def update(self, delay):
     for e in self.entities:
         self.addToFamily(e.getFamily(), e)
         e.update(delay, self)
         
     emptyFamilies = []
     for family in self.families.iterkeys():
         family.update(delay, self)
         if family.getMemberCount() == 0:
             emptyFamilies.append(family)
             
     for emptyFamily in emptyFamilies:
         del self.families[emptyFamily]
     del emptyFamilies
             
     if not self.entities:
         print "Everyone's dead!"
         event.post(Event(pygame.QUIT, {}))
示例#52
0
文件: mesh.py 项目: rparrapy/maze
    def participant_change_cb(self, added, removed):
        log.debug( 'participant_change_cb: %s %s', added, removed )
        for handle, bus_name in added:
            dbus_handle = self.tube.participants[handle]
            self.ordered_bus_names.append(dbus_handle)
            PEvent.post(PEvent.Event(PARTICIPANT_ADD, handle=dbus_handle))

        for handle in removed:
            dbus_handle = self.tube.participants[handle]
            self.ordered_bus_names.remove(dbus_handle)
            PEvent.post(PEvent.Event(PARTICIPANT_REMOVE, handle=dbus_handle))

        if self.is_initiator:
            if not self.entered:
                # Initiator will broadcast a new ordered_bus_names each time
                # a participant joins.
                self.ordered_bus_names = [self.tube.get_unique_name()]
            self.NewParticipants(self.ordered_bus_names)

        self.entered = True
 def graphical_main(self):
     # program loop #
     done = False
     while not done:
         # events #
         for e in event.get():
             if e.type == QUIT: done = True
             elif e.type == KEYDOWN:
                 if e.key == K_ESCAPE: event.post(event.Event(QUIT))
                 else:
                     character = str(e.unicode).lower()
                     if character in self.board.RCHARS:
                         self.set_color(self.board.RCHARS[character])
             elif e.type == MOUSEMOTION:
                 old_pos = self.selected_pos
                 self.selected_pos = self.to_board(e.pos)
                 if self.selected_pos != old_pos: # dragged to a new spot
                     if e.buttons[0]: # left button held
                         self.set_color(BLACK)
                     elif e.buttons[1]: # middle button held
                         self.set_color(UNKNOWN)
                     elif e.buttons[2]: # right button held
                         self.set_color(WHITE)
             elif e.type == MOUSEBUTTONDOWN:
                 self.selected_pos = self.to_board(e.pos)
                 if e.button == 1: # left click
                     self.set_color(BLACK)
                 elif e.button == 2: # middle click
                     self.set_color(UNKNOWN)
                 elif e.button == 3: # right click
                     self.set_color(WHITE)
 
         # draw #
         self.screen.fill(bg_color)
         self.draw()
         pygame.display.flip()
 
     pygame.quit()    
示例#54
0
def poll_inputs( screen):
  # All pending events should be read with a single invocation of this method
  while True:
    readable, ignore, ignore = select( open_files, [], [], 0)
    if [] == readable: break
    for f in readable:
      packed_event = f.read( sizeof_Event)
      secs, usecs, event_type, code, value = unpack( Event_format, packed_event)
      time = float(secs) + float(usecs)/1000000.0
      #print "t:%i, c:%i, v:%i" % ( event_type, code, value)
      if EV_KEY == event_type:
        #act = "pressed" if 1 == value else "released"
        #print act+ ": %i"% code
        if 330 == code:
          evt = MOUSEBUTTONDOWN if 1 == value else MOUSEBUTTONUP
          state = State.for_touchscreen
          sdl_event.post( Event(evt, pos=(state.x,state.y), button=0) )
          print state.x,state.y
        else:
          evt = KEYDOWN if 1 == value else KEYUP
          sdl_event.post( Event(evt, key=key_for_button[code], unicode="", mod=0) )
      elif EV_REL == event_type:
        # The joypad is mapped to the arrow keys
        state = state_for_file[ f]
        if 0 == code:  # 0 means X axis
          state.x = screen.get_rect().w * value >> 10
          #print "moved to %i,%i"% ( state.x, state.y)
        elif 1 == code:
          state.y = screen.get_rect().h * value >> 10
        #print "moved to %i,%i"% ( state.x, state.y)
      elif EV_ABS == event_type:
        state = state_for_file[ f]
        touchscreen_state = state
        if 0 == code:  # 0 means X axis
          state.x = screen.get_rect().w * value >> 10
          #print "moved to %i,%i"% ( state.x, state.y)
        elif 1 == code:
          state.y = screen.get_rect().h * value >> 10
          #print "moved to %i,%i"% ( state.x, state.y)
        sdl_event.post( Event(MOUSEMOTION, pos = (state.x,state.y), rel = [], buttons = []) )
示例#55
0
 def key_down(self, evt):
     self.dismiss()
     event.post(evt)
示例#56
0
 def mouse_down(self, evt):
     if evt not in self:
         self.dismiss(-1)
         if evt.button != 1:
             event.post(evt)
    def waker (self, func):
        """T.waker (...) -> None

        Used in threadedselectreactor.interleave.
        """
        event.post (event.Event (SIG_TWISTED, data=func))
示例#58
0
 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]))
示例#59
0
 def pop_handler(self):
     post(Event(USEREVENT, code=EV_POP_HANDLER))