Python pygame.event() Examples

The following are 30 code examples of pygame.event(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygame , or try the search function .
Example #1
Source File: earth.py    From code-jam-5 with MIT License 6 votes vote down vote up
def update(self, event: pg.event) -> None:
        """Update game logic with each game tick."""
        if game_vars.is_started:
            # Scroll the earth into view when the game starts
            if self.entry_y_offset > 0:
                self.entry_y_offset = max(self.entry_y_offset - self.entry_speed, 0)

            # If we are not doing a task - we can move the background
            if not game_vars.open_task:
                key_pressed = pg.key.get_pressed()

                if key_pressed[pg.K_a] or key_pressed[pg.K_LEFT]:
                    self.__scroll_left()
                if key_pressed[pg.K_d] or key_pressed[pg.K_RIGHT]:
                    self.__scroll_right()

                self.__update_tiles(event)
            else:
                game_vars.open_task.update(event)

        self.current_cloud_bg_pos += BG_CLOUDS_SCROLL_SPEED
        self.current_cloud_fg_pos += FG_CLOUDS_SCROLL_SPEED

        self.__update_positions()
        self.__update_indicators() 
Example #2
Source File: credits.py    From code-jam-5 with MIT License 6 votes vote down vote up
def draw(self, mouse_x: int, mouse_y: int, event: pg.event) -> None:
        """Hadle all options events and draw elements."""
        # draw the infinity background and credits layout
        draw_infinity_bg(self.screen, self.background, self.bg_rect_1, self.bg_rect_2)
        self.screen.blit(self.credits, (0, 0, WIDTH, HEIGHT))

        # check if back buttn is hovered
        if self.back_btn.rect.collidepoint(mouse_x, mouse_y):
            # draw its hover state
            self.back_btn.draw(hover=True)

            # if the back button is clicked play click sound and
            # return to the main menu
            if event.type == pg.MOUSEBUTTONDOWN:
                Sound.click.play()
                return WindowState.main_menu
        else:
            # if it is not hover draw its normal state
            self.back_btn.draw()
        return WindowState.credit 
Example #3
Source File: task.py    From code-jam-5 with MIT License 6 votes vote down vote up
def update(self, event: pg.event) -> None:
        """Check mouse collisions if player is in maze."""
        super().update()

        for cell in self.maze:
            mouse_hover = cell.rect.collidepoint(pg.mouse.get_pos())
            if (
                not self.started
                and cell.cell_type == self.CellType.START
                and mouse_hover
            ):
                self.started = True
            elif self.started and mouse_hover:
                if cell.cell_type == self.CellType.END:
                    self._complete(True)
                elif cell.cell_type == self.CellType.WALL:
                    self._complete(False) 
Example #4
Source File: game_view.py    From code-jam-5 with MIT License 6 votes vote down vote up
def _draw_buttons(self, event: pg.event) -> None:
        """Draw buttons for the pause window."""
        mouse_x, mouse_y = pg.mouse.get_pos()
        if self.resume_btn.rect.collidepoint(mouse_x, mouse_y):
            self.resume_btn.draw(hover=True)

            # Click resume button
            if event.type == pg.MOUSEBUTTONDOWN:
                Sound.click.play()
                game_vars.is_paused = False
        else:
            self.resume_btn.draw()

        if self.exit_btn.rect.collidepoint(mouse_x, mouse_y):
            self.exit_btn.draw(hover=True)

            # Click exit button; reset the game
            if event.type == pg.MOUSEBUTTONDOWN:
                Sound.click.play()
                game_vars.reset_game = True
        else:
            self.exit_btn.draw() 
Example #5
Source File: game_view.py    From code-jam-5 with MIT License 6 votes vote down vote up
def _draw_pause_window(self, event: pg.event) -> None:
        """Draw the pause window."""
        # Background
        self.screen.blit(self.window_image, self.window_rect)

        font = pg.font.Font(None, 60)
        font.set_bold(True)
        pause_text = font.render("PAUSED", True, Color.white)
        text_x = (
            self.window_rect.x
            + (self.window_rect.width // 2)
            - (pause_text.get_width() // 2)
        )
        text_y = self.window_rect.y + 25
        self.screen.blit(pause_text, (text_x, text_y))

        self._draw_buttons(event) 
Example #6
Source File: tile.py    From code-jam-5 with MIT License 6 votes vote down vote up
def update(self, event: pg.event) -> None:
        """Update tile size, tint; check if we clicked on task."""
        # Check if this task was completed
        if self.task is None:
            self.scale_n_current = 1

        # Get tile size to check for collision with mouse
        image_size = self._image_cache[self.scale_n_current].get_size()
        tile_rect = pg.Rect(
            (self.pos_x, self.pos_y), (image_size[0], image_size[1] // 2)
        )
        if not game_vars.open_task and tile_rect.collidepoint(pg.mouse.get_pos()):
            # We clicked on tile - start the task
            if event.type == pg.MOUSEBUTTONDOWN and self.task is not None:
                self.task.start()
            self.is_hovering = True
        else:
            self.is_hovering = False

        # Animation
        self._breathe() 
Example #7
Source File: game_functions.py    From alien-invasion-game with MIT License 6 votes vote down vote up
def check_keydown_events(event: EventType, ai_settings: Settings
                         , stats: GameStats, game_items: GameItems):
    """Respond when key is being pressed."""
    if event.key == pygame.K_RIGHT:
        # Move ship to the right.
        game_items.ship.moving_right = True

    elif event.key == pygame.K_LEFT:
        # Move ship to the left.
        game_items.ship.moving_left = True

    elif event.key == pygame.K_SPACE:
        fire_bullet(ai_settings, game_items)

    elif event.key == pygame.K_q:
        quit_game(stats)

    elif event.key == pygame.K_RETURN:  # ENTER key
        start_new_game(ai_settings, stats, game_items) 
Example #8
Source File: game_functions.py    From alien-invasion-game with MIT License 6 votes vote down vote up
def check_events(ai_settings: Settings, stats: GameStats, game_items: GameItems):
    """Respond to keypresses and mouse events."""

    # Watch for keyboard and mouse events.
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit_game(stats)

        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, stats, game_items)

        elif event.type == pygame.KEYUP:
            check_keyup_events(event, game_items.ship)

        elif event.type == pygame.MOUSEBUTTONDOWN:
            check_mousedown_events(ai_settings, stats, game_items) 
Example #9
Source File: fastevents.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        self.done = []
        self.stop = []
        for x in range(NUM_EVENTS_TO_POST):
            ee = event.Event(USEREVENT)
            try_post = 1

            # the pygame.event.post raises an exception if the event
            #   queue is full.  so wait a little bit, and try again.
            while try_post:
                try:
                    event_module.post(ee)
                    try_post = 0
                except:
                    pytime.sleep(0.001)
                    try_post = 1

            if self.stop:
                return
        self.done.append(1) 
Example #10
Source File: fastevents.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        self.done = []
        self.stop = []
        for x in range(NUM_EVENTS_TO_POST):
            ee = event.Event(USEREVENT)
            try_post = 1

            # the pygame.event.post raises an exception if the event
            #   queue is full.  so wait a little bit, and try again.
            while try_post:
                try:
                    event_module.post(ee)
                    try_post = 0
                except:
                    pytime.sleep(0.001)
                    try_post = 1

            if self.stop:
                return
        self.done.append(1) 
Example #11
Source File: fastevents.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        self.done = []
        self.stop = []
        for x in range(NUM_EVENTS_TO_POST):
            ee = event.Event(USEREVENT)
            try_post = 1

            # the pygame.event.post raises an exception if the event
            #   queue is full.  so wait a little bit, and try again.
            while try_post:
                try:
                    event_module.post(ee)
                    try_post = 0
                except:
                    pytime.sleep(0.001)
                    try_post = 1

            if self.stop:
                return
        self.done.append(1) 
Example #12
Source File: fastevents.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        self.done = []
        self.stop = []
        for x in range(NUM_EVENTS_TO_POST):
            ee = event.Event(USEREVENT)
            try_post = 1

            # the pygame.event.post raises an exception if the event
            #   queue is full.  so wait a little bit, and try again.
            while try_post:
                try:
                    event_module.post(ee)
                    try_post = 0
                except:
                    pytime.sleep(0.001)
                    try_post = 1

            if self.stop:
                return
        self.done.append(1) 
Example #13
Source File: root.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def schedule(delay, func):
    """Arrange for the given function to be called after the specified
    delay in seconds. Scheduled functions are called synchronously from
    the event loop, and only when the frame timer is running."""
    t = time() + delay
    insort(scheduled_calls, (t, func)) 
Example #14
Source File: root.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
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 
Example #15
Source File: root.py    From GDMC with ISC License 5 votes vote down vote up
def capture_mouse(self, widget):
        # put the mouse in "virtual mode" and pass mouse moved events to the
        # specified widget
        if widget:
            pygame.mouse.set_visible(False)
            pygame.event.set_grab(True)
            self.captured_widget = widget
        else:
            pygame.mouse.set_visible(True)
            pygame.event.set_grab(False)
            self.captured_widget = None 
Example #16
Source File: root.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def send_key(widget, name, event):
        widget.dispatch_key(name, event) 
Example #17
Source File: root.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def capture_mouse(self, widget):
        # put the mouse in "virtual mode" and pass mouse moved events to the
        # specified widget
        if widget:
            pygame.mouse.set_visible(False)
            pygame.event.set_grab(True)
            self.captured_widget = widget
        else:
            pygame.mouse.set_visible(True)
            pygame.event.set_grab(False)
            self.captured_widget = None 
Example #18
Source File: root.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def add_modifiers(event):
    d = event.dict
    d.update(modifiers)
    d['cmd'] = event.ctrl or event.meta 
Example #19
Source File: period.py    From code-jam-5 with MIT License 5 votes vote down vote up
def update(self, event: pg.event) -> None:
        """Update earth, sun and handle tasks spawns."""
        self.earth.update(event)
        self.sun.update(event)

        if game_vars.is_started:
            self.end_time = None
            if self.start_time is None:
                self.start_time = time.time()
            self.__handle_task_spawn()
        elif self.end_time is None:
            self.end_time = time.time() 
Example #20
Source File: task.py    From code-jam-5 with MIT License 5 votes vote down vote up
def update(self, event: pg.event) -> None:
        """Handles clicks, make computer choice and complete the task."""
        super().update()

        # iterate all human rect choices
        for i, rect in enumerate(self.choice_rects):
            mouse_hover = rect.collidepoint(pg.mouse.get_pos())
            mouse_click = event.type == pg.MOUSEBUTTONDOWN

            if (
                mouse_hover
                and mouse_click
                and self.choice not in [0, 1, 2]  # asserts that the human didn't chose
                and (time() - self.delay) > 0.3
            ):
                Sound.click.play()
                # if mouse clicked on button and not choosed yet
                self.choice = i
                self.mixing = True
                self.timer = time()
                # set timer for computer shuffling (animation)

        # make computer choose and evaluate if it is a win
        if not self.game_over and (time() - self.timer <= 0.5):
            self.computer_choice = randint(0, 2)

            # We win if the computer chose the same as we did
            self.win = self.choice == self.computer_choice
            self.game_over = True
            # set timer for lasting - not instant quit
            self.last = time()

        if self.game_over:
            if time() - self.last > 2:  # seconds of lasting
                if self.win:
                    return self._complete(True)
                else:
                    return self._complete(False) 
Example #21
Source File: game_view.py    From code-jam-5 with MIT License 5 votes vote down vote up
def update(self, event: pg.event) -> None:
        """Update period and handle pauses."""
        if (
            game_vars.is_started
            and game_vars.open_task is None
            and pg.key.get_pressed()[pg.K_ESCAPE]
            and time.time() > self.pause_start + 0.3
        ):
            game_vars.is_paused = not game_vars.is_paused
            self.pause_start = time.time()

        if not game_vars.is_paused:
            self.period.update(event) 
Example #22
Source File: sun.py    From code-jam-5 with MIT License 5 votes vote down vote up
def update(self, event: pg.event) -> None:
        """Update sun angle, position and heat value."""
        self.update_angle()

        if game_vars.is_started:
            # Increase heat based on uncompleted task count
            task_count = sum(b.tilemap.task_count for b in self.biomes)

            game_vars.current_heat += (
                self.heat_per_tick + self.heat_per_task * task_count
            )
            game_vars.current_heat = min(max(game_vars.current_heat, 0), MAX_HEAT) 
Example #23
Source File: earth.py    From code-jam-5 with MIT License 5 votes vote down vote up
def __update_tiles(self, event: pg.event) -> None:
        """Calls update method of every tile in the game."""
        for biome in self.biomes:
            tilemap = biome.tilemap
            for y, tile_row in enumerate(tilemap):
                for x, tile in enumerate(tile_row):
                    if tile.task is not None and tile.task.is_done:
                        tilemap.del_task_by_coords(y, x)
                    tile.update(event) 
Example #24
Source File: window.py    From moderngl-window with MIT License 5 votes vote down vote up
def mouse_exclusivity(self, value: bool):
        if self._cursor:
            self.cursor = False

        pygame.event.set_grab(value)
        self._mouse_exclusivity = value 
Example #25
Source File: game_functions.py    From alien-invasion-game with MIT License 5 votes vote down vote up
def check_keyup_events(event: EventType, ship: Ship):
    """Respond when key is stopped being pressed."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False 
Example #26
Source File: root.py    From GDMC with ISC License 5 votes vote down vote up
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 
Example #27
Source File: root.py    From GDMC with ISC License 5 votes vote down vote up
def send_key(widget, name, event):
        widget.dispatch_key(name, event) 
Example #28
Source File: root.py    From GDMC with ISC License 5 votes vote down vote up
def call_idle_handlers(self, event):
        def call(ref):
            widget = ref()
            if widget:
                widget.idleevent(event)
            else:
                print "Idle ref died!"
            return bool(widget)

        self.idle_handlers = filter(call, self.idle_handlers) 
Example #29
Source File: root.py    From GDMC with ISC License 5 votes vote down vote up
def add_modifiers(event):
    d = event.dict
    d.update(modifiers)
    d['cmd'] = event.ctrl or event.meta 
Example #30
Source File: fastevents.py    From fxxkpython with GNU General Public License v3.0 4 votes vote down vote up
def main():
    init()

    if use_fast_events:
        fastevent.init()

    c = time.Clock()

    win = display.set_mode((640, 480), RESIZABLE)
    display.set_caption("fastevent Workout")

    poster = post_them()

    t1 = pytime.time()
    poster.start()

    going = True
    while going:
#        for e in event.get():
        #for x in range(200):
        #    ee = event.Event(USEREVENT)
        #    r = event_module.post(ee)
        #    print (r)

        #for e in event_module.get():
        event_list = []
        event_list = event_module.get()

        for e in event_list:
            if e.type == QUIT:
                print (c.get_fps())
                poster.stop.append(1)
                going = False
            if e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    print (c.get_fps())
                    poster.stop.append(1)
                    going = False
        if poster.done:
            print (c.get_fps())
            print (c)
            t2 = pytime.time()
            print ("total time:%s" % (t2 - t1))
            print ("events/second:%s" % (NUM_EVENTS_TO_POST / (t2 - t1)))
            going = False
        if with_display:
            display.flip()
        if slow_tick:
            c.tick(40)


    pygame.quit()