-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer.py
86 lines (70 loc) · 2.71 KB
/
player.py
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
80
81
82
83
84
85
86
import pygame
from circleshape import CircleShape
from constants import PLAYER_RADIUS, PLAYER_SHOT_COOLDOWN, PLAYER_SHOT_SPEED, PLAYER_TURN_SPEED, PLAYER_SPEED, SHOT_RADIUS
from shot import Shot
class Player(CircleShape):
def __init__(self, x, y):
"""
Initializes a new Player instance.
Args:
x (float): The x-coordinate of the player's initial position.
y (float): The y-coordinate of the player's initial position.
"""
super().__init__(x, y, PLAYER_RADIUS)
self.rotation = 0
self.cooldown = 0
# in the player class
def triangle(self):
"""
Calculates the vertices of the triangle representing the player on the screen.
Returns:
list: A list of three pygame.Vector2 points representing the triangle vertices.
"""
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):
"""
Draws the player on the screen as a white triangle.
Args:
screen (pygame.Surface): The surface to draw the player on.
"""
pygame.draw.polygon(screen, (255, 255, 255), self.triangle(), 2)
def rotate(self, dt):
"""
Rotates the player based on the player's turning speed and the elapsed time.
Args:
dt (float): The time difference since the last frame, in seconds.
"""
self.rotation += PLAYER_TURN_SPEED * dt
def update(self, dt):
"""
Updates the player's state. Processes input to rotate the player if needed.
Args:
dt (float): The time difference since the last frame, in seconds.
"""
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
self.rotate(-dt)
if keys[pygame.K_d]:
self.rotate(dt)
if keys[pygame.K_w]:
self.move(dt)
if keys[pygame.K_s]:
self.move(-dt)
if keys[pygame.K_SPACE]:
self.shoot()
self.cooldown -= dt
def move(self, dt):
forward = pygame.Vector2(0, 1).rotate(self.rotation)
self.position += forward * PLAYER_SPEED * dt
def shoot(self):
# don't shoot if there is still a cooldown
if self.cooldown > 0:
return
shot = Shot(self.position.x, self.position.y)
shot.velocity = pygame.Vector2(0, 1).rotate(self.rotation) * PLAYER_SHOT_SPEED
self.cooldown = PLAYER_SHOT_COOLDOWN