-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent_handler.py
More file actions
82 lines (57 loc) · 2.44 KB
/
event_handler.py
File metadata and controls
82 lines (57 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import pygame
import sys
from pygame.math import Vector2
from bullet import Bullet
class EventHandler:
def __init__(self,ai_game,ship,bullets):
pygame.init()
self.screen = ai_game.screen
self.aliens = ai_game.aliens
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.ship = ship
self.dt = 0
self.stats = ai_game.stats
self.bullets = bullets
self.ai_game = ai_game
def _fire_bullet(self):
if len(self.bullets) <= self.settings.bullet_amount:
new_bullet = Bullet(self.ai_game)
self.bullets.add(new_bullet)
def check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.ai_game.game_running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
self._check_play_button(mouse_pos)
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
self._fire_bullet()
elif event.key == pygame.K_ESCAPE:
self.ai_game.game_running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
self.ship.rect_pos.y -= self.settings.ship_speed*self.dt
if keys[pygame.K_s]:
self.ship.rect_pos.y += self.settings.ship_speed*self.dt
if keys[pygame.K_a]:
self.ship.rect_pos.x -= self.settings.ship_speed*self.dt
if keys[pygame.K_d]:
self.ship.rect_pos.x += self.settings.ship_speed*self.dt
self.ship.rect.topleft =self.ship.rect_pos
self.ship.rect.clamp_ip(self.screen_rect)
self.ship.rect_pos = Vector2(self.ship.rect.topleft)
def _check_play_button(self,mouse_pos):
button_clicked = self.ai_game.play_button.rect.collidepoint(mouse_pos)
if button_clicked and not self.stats.game_active:
pygame.mouse.set_visible(False)
self.stats.reset_stats()
self.bullets.empty()
self.aliens.empty()
self.stats.game_active = True
self.ai_game.spawn_timer = self.ai_game.spawn_interval
def blitme(self):
self.ship.rect.topleft = self.ship.rect_pos
"""draw the ship at current location"""
self.screen.blit(self.ship.image,self.ship.rect)