-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.py
69 lines (55 loc) · 2.78 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
from settings import *
class Player(pygame.sprite.Sprite):
def __init__(self, pos, groups, collision_sprites) -> None:
super().__init__(groups)
self.load_images()
self.state, self.frame_index = "down", 0
self.image = pygame.image.load(join("Images","Player", "down", "0.png")).convert_alpha()
self.rect = self.image.get_frect(center = pos)
self.hitbox_rect = self.rect.inflate(-60,-90)
#movement
self.direction = pygame.Vector2(0,0)
self.speed = 500
self.collision_sprites = collision_sprites
def load_images(self):
self.frames = {'left' : [],'right' : [],'up' : [],'down' : []}
for state in self.frames.keys():
for folder_path, sub_folders, file_names in walk(join("Images","Player", state)):
if file_names:
for file_name in sorted(file_names, key= lambda name: int(name.split('.')[0])):
full_path = join(folder_path, file_name)
surf = pygame.image.load(full_path).convert_alpha()
self.frames[state].append(surf)
def input(self):
keys = pygame.key.get_pressed()
self.direction.x = int(keys[pygame.K_d]) - int(keys[pygame.K_q])
self.direction.y = int(keys[pygame.K_s]) - int(keys[pygame.K_z])
self.direction = self.direction.normalize() if self.direction else self.direction
def move(self, dt):
self.hitbox_rect.x += self.direction.x * self.speed * dt
self.collision('horizontal')
self.hitbox_rect.y += self.direction.y * self.speed * dt
self.collision('vertical')
self.rect.center = self.hitbox_rect.center
def collision(self, direction):
for sprite in self.collision_sprites:
if sprite.rect.colliderect(self.hitbox_rect):
if direction == 'horizontal':
if self.direction.x > 0: self.hitbox_rect.right = sprite.rect.left
if self.direction.x < 0: self.hitbox_rect.left = sprite.rect.right
else:
if self.direction.y < 0: self.hitbox_rect.top = sprite.rect.bottom
if self.direction.y > 0: self.hitbox_rect.bottom = sprite.rect.top
def animate(self, dt):
# get state
if self.direction.x != 0:
self.state = "right" if self.direction.x > 0 else "left"
if self.direction.y != 0:
self.state = "down" if self.direction.y > 0 else "up"
#animation
self.frame_index = self.frame_index + 5*dt if self.direction else 0
self.image = self.frames[self.state][int(self.frame_index) % len(self.frames[self.state])]
def update(self, dt) -> None:
self.input()
self.move(dt)
self.animate(dt)