-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayer.py
More file actions
61 lines (50 loc) · 2.17 KB
/
player.py
File metadata and controls
61 lines (50 loc) · 2.17 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
import pygame
from circleshape import CircleShape
from constants import LINE_WIDTH, PLAYER_RADIUS, PLAYER_SHOOT_COOLDOWN_SECONDS, PLAYER_SHOOT_SPEED, PLAYER_SPEED, PLAYER_TURN_SPEED
from shot import Shot
class Player(CircleShape):
def __init__(self, x, y):
super().__init__(x, y, PLAYER_RADIUS)
self.rotation = 0
self.turning_left = False
self.turning_right = False
self.moving_forward = False
self.moving_backward = False
self.shooting = False
self.shot_cooldown = 0
def triangle(self):
forward = pygame.Vector2(0, 1).rotate(self.rotation)
right = pygame.Vector2(0, 1).rotate(self.rotation + 90) * self.radius / 1.5
a = self.position + forward * self.radius
b = self.position - forward * self.radius - right
c = self.position - forward * self.radius + right
return [a, b, c]
def draw(self, screen):
pygame.draw.polygon(screen, "white", self.triangle(), LINE_WIDTH)
def rotate(self, dt):
self.rotation += PLAYER_TURN_SPEED * dt
def move(self, dt):
unit_vector = pygame.Vector2(0, 1)
rotated_vector = unit_vector.rotate(self.rotation)
rotated_with_speed_vector = rotated_vector * PLAYER_SPEED * dt
self.position += rotated_with_speed_vector
def shoot(self):
if self.shot_cooldown > 0:
return
shot = Shot(self.position.x, self.position.y)
shot.velocity = pygame.Vector2(0, 1).rotate(self.rotation) * PLAYER_SHOOT_SPEED
self.shot_cooldown = PLAYER_SHOOT_COOLDOWN_SECONDS
def update(self, dt):
pygame.event.pump()
keys = pygame.key.get_pressed()
self.shot_cooldown -= dt
if self.turning_left or keys[pygame.K_a] or keys[pygame.K_LEFT]:
self.rotate(dt * -1)
if self.turning_right or keys[pygame.K_d] or keys[pygame.K_RIGHT]:
self.rotate(dt)
if self.moving_forward or keys[pygame.K_w] or keys[pygame.K_UP]:
self.move(dt)
if self.moving_backward or keys[pygame.K_s] or keys[pygame.K_DOWN]:
self.move(dt * -1)
if self.shooting or keys[pygame.K_SPACE]:
self.shoot()