-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer.py
112 lines (94 loc) · 3.17 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import pygame
from utils import load_sprite_sheets, flip
class Player(pygame.sprite.Sprite):
COLOR = (255, 0, 0)
GRAVITY = 1
ANIMATION_DELAY = 3
def __init__(self, x, y, width, height):
super().__init__()
self.rect = pygame.Rect(x, y, width, height)
self.x_vel = 0
self.y_vel = 0
self.mask = None
self.direction = "left"
self.animation_count = 0
self.fall_count = 0
self.jump_count = 0
self.hit = False
self.hit_count = 0
self.cherries_eaten = 0
self.lives = 3
self.invincible = False
self.invincible_count = 0
self.SPRITES = load_sprite_sheets("MainCharacters", "NinjaFrog", 32, 32, True)
def jump(self):
self.y_vel = -self.GRAVITY * 8
self.animation_count = 0
self.jump_count += 1
if self.jump_count == 1:
self.fall_count = 0
def move(self, dx, dy):
self.rect.x += dx
self.rect.y += dy
def make_hit(self):
if not self.invincible:
self.hit = True
self.lives -= 1
self.invincible = True
def move_left(self, vel):
self.x_vel = -vel
if self.direction != "left":
self.direction = "left"
self.animation_count = 0
def move_right(self, vel):
self.x_vel = vel
if self.direction != "right":
self.direction = "right"
self.animation_count = 0
def loop(self, fps):
self.y_vel += min(1, (self.fall_count / fps) * self.GRAVITY)
self.move(self.x_vel, self.y_vel)
if self.hit:
self.hit_count += 1
if self.hit_count > fps * 2:
self.hit = False
self.hit_count = 0
if self.invincible:
self.invincible_count += 1
if self.invincible_count > fps * 2:
self.invincible = False
self.invincible_count = 0
self.fall_count += 1
self.update_sprite()
def landed(self):
self.fall_count = 0
self.y_vel = 0
self.jump_count = 0
def hit_head(self):
self.count = 0
self.y_vel *= -1
def update_sprite(self):
sprite_sheet = "idle"
if self.hit:
sprite_sheet = "hit"
elif self.y_vel < 0:
if self.jump_count == 1:
sprite_sheet = "jump"
elif self.jump_count == 2:
sprite_sheet = "double_jump"
elif self.y_vel > self.GRAVITY * 2:
sprite_sheet = "fall"
elif self.x_vel != 0:
sprite_sheet = "run"
sprite_sheet_name = sprite_sheet + "_" + self.direction
sprites = self.SPRITES[sprite_sheet_name]
sprite_index = (self.animation_count //
self.ANIMATION_DELAY) % len(sprites)
self.sprite = sprites[sprite_index]
self.animation_count += 1
self.update()
def update(self):
self.rect = self.sprite.get_rect(topleft=(self.rect.x, self.rect.y))
self.mask = pygame.mask.from_surface(self.sprite)
def draw(self, win, offset_x, offset_y):
win.blit(self.sprite, (self.rect.x - offset_x, self.rect.y - offset_y))