-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrill.py
360 lines (307 loc) · 12.4 KB
/
drill.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
"""
A 2D vertical endless runner in pygame.
"""
import pygame
from sys import exit
from random import randint
from shared import *
from enum import Enum
class Drill(Player):
def __init__(self, frames : list, scale : int):
super().__init__(frames, scale)
self.dimensions = (self.image.get_size())
self.x_input = False
self.vel_x = 0
self.start_coord = (WINDOW_WIDTH/2 - self.dimensions[0], game_settings["max_y_ofs_up"])
self.rect = self.image.get_rect(topleft=self.start_coord)
# Animation logic on hit
self.lives = 3
self.hit = False
self.num_iframes = 0
self.damage_frames = []
self.dmg_frame_index = 0
for img in self.frames:
cpy = img.copy()
cpy_t = cpy.copy()
cpy_t.set_alpha(40)
self.damage_frames.extend([cpy, cpy_t])
def init(self):
self.rect = self.image.get_rect(topleft=self.start_coord)
self.lives = 3
self.hit = False
self.vel_x = 0
def player_input(self):
# UP, DOWN: move player position directly
# LEFT, RIGHT: update player velocity
curr_y_ofs = self.rect.y - self.start_coord[1]
y_limit_up = game_settings["max_y_ofs_up"]
y_limit_down = game_settings["max_y_ofs_down"]
vel_limit = game_settings["vel_limit"]
vel_increment = game_settings["vel_increment"]
y_increment = game_settings["y_pos_increment"]
keys = pygame.key.get_pressed()
if keys[pygame.K_w] or keys[pygame.K_UP]:
if (curr_y_ofs > -1*y_limit_up):
self.rect.y -= y_increment
if keys[pygame.K_s] or keys[pygame.K_DOWN]:
if (curr_y_ofs < y_limit_down):
self.rect.y += y_increment
if keys[pygame.K_a] or keys[pygame.K_LEFT]:
if (self.vel_x > -1*vel_limit):
self.vel_x -= vel_increment
self.x_input = True
if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
if (self.vel_x < vel_limit):
self.vel_x += vel_increment
self.x_input = True
def decelerate(self):
# Reduce velocity when player is not controlling it
if (not self.x_input):
dec = game_settings["vel_decrement"]
if (self.vel_x < 0):
self.vel_x += dec
else:
self.vel_x -= dec
self.x_input = False
def apply_velocity(self):
self.rect.x += self.vel_x
if self.rect.left < LEFT_BOUND:
self.rect.left = LEFT_BOUND
if self.rect.right > RIGHT_BOUND:
self.rect.right = RIGHT_BOUND
def animation_apply_rotate(self):
# Rotate drill based on its x velocity
angle = int(50 * (self.vel_x / game_settings["vel_limit"]))
if (abs(angle) > 1): # Avoid jitter
self.image = pygame.transform.rotate(self.image, angle)
def dmg_animation_state(self):
self.dmg_frame_index += 0.1 * int(len(self.damage_frames) / len(self.frames))
if self.dmg_frame_index >= len(self.damage_frames):
self.dmg_frame_index = 0
img = self.damage_frames[int(self.dmg_frame_index)]
self.image = pygame.transform.scale_by(img, self.scale)
self.num_iframes -= 1
if (self.num_iframes <= 0): self.hit = False
def update(self):
self.player_input()
self.decelerate()
self.apply_velocity()
if (self.hit):
self.dmg_animation_state()
else:
self.idle_animation_state()
self.animation_apply_rotate()
class Enemy(Player):
max_y_ofs = 50
move_speed = 1
osc_freq = 50
def __init__(self, frames : list, scale : int, e_type : str,
spawn_coord : tuple, facing : str):
super().__init__(frames, scale)
self.type = e_type
self.origin = spawn_coord
self.facing = facing
self.rect = self.image.get_rect(center=spawn_coord)
# Only for mole:
self.movement_counter = 0
self.vert_speed = 2
def flip_self(self):
if (self.facing == "right"):
self.image = pygame.transform.flip(self.image, flip_x=True, flip_y=False)
def movement(self):
direction = -1 if (self.facing == "left") else 1
if self.type == "worm":
self.rect.x += direction * Enemy.move_speed
self.rect.y -= game_settings["scroll_speed"]
else:
if (self.movement_counter >= Enemy.osc_freq):
self.movement_counter = 0
self.vert_speed *= -1
self.rect.x += direction * Enemy.move_speed
self.rect.y += self.vert_speed
self.movement_counter += 1
self.rect.y -= game_settings["scroll_speed"]
def destroy(self):
if self.rect.y <= -100:
self.kill()
def update(self):
self.idle_animation_state()
self.flip_self()
self.movement()
self.destroy()
class Gemtype(Enum):
AMETHYST = 0
SAPPHIRE = 1
EMERALD = 2
RUBY = 4
class Gem(PointObject):
emerald = pygame.image.load("lib/graphics/drill-game/gem1.png").convert_alpha()
amethyst = pygame.image.load("lib/graphics/drill-game/gem2.png").convert_alpha()
ruby = pygame.image.load("lib/graphics/drill-game/gem3.png").convert_alpha()
sapphire = pygame.image.load("lib/graphics/drill-game/gem4.png").convert_alpha()
gems = [amethyst, sapphire, emerald, ruby]
def __init__(self, scale : int, gemtype : Gemtype):
frames = [Gem.gems[gemtype]] # Singular Frame
super().__init__(frames, scale)
w, h = self.image.get_size()
origin = (randint(w, WINDOW_WIDTH - w), WINDOW_HEIGHT + 2*h)
self.rect = self.image.get_rect(topleft=origin)
self.gemtype = gemtype
def destroy(self):
if (self.rect.y <= -100):
self.kill()
def update(self):
self.rect.y -= game_settings["scroll_speed"]
def spawn_enemy(e_type : str, facing : str) -> Enemy:
frames = [mole_1, mole_2] if e_type == "mole" else [worm_1, worm_2]
if (facing == "right"):
coords = (-100, randint(WINDOW_HEIGHT - 50, WINDOW_HEIGHT + 300))
else:
coords = (WINDOW_WIDTH + 100, randint(WINDOW_HEIGHT - 50, WINDOW_HEIGHT + 300))
return Enemy(frames, scale, e_type, coords, facing)
def collide_enemy():
if (player.sprite.hit): return
# We want more precise hit detection for this (using masks)
hits = pygame.sprite.spritecollide(player.sprite, enemies, dokill=False)
for sprite in hits:
if (pygame.sprite.collide_mask(player.sprite, sprite)):
drill = player.sprite
# Update vars associated with player damage
drill.hit = True
# TODO: Figure out a better way to give 3 seconds of invulnerability:
drill.num_iframes = 60 * 3
drill.dmg_frame_index = int(drill.frame_index * 2)
drill.lives -= 1
return
def collide_valuable():
hits = pygame.sprite.spritecollide(player.sprite, valuables, dokill=True)
for gem in hits:
game_tracker["score"] += (gem.gemtype + 1) * 50
def game_over_input(game_tracker):
keys = pygame.key.get_pressed()
if keys[pygame.K_RETURN] or keys[pygame.K_SPACE]:
# CONTINUE
init_game(game_tracker)
elif keys[pygame.K_ESCAPE]:
if (__name__ == "__main__"):
pygame.quit()
exit()
else:
return -1
def init_game(game_tracker):
game_tracker["score"] = 0
game_tracker["depth"] = 0
game_tracker["game_active"] = True
game_tracker["game_paused"] = False
background.init_background()
enemies.empty()
valuables.empty()
drill.init()
# Track game states and other info
game_tracker = {
"game_active": True,
"game_paused": False,
"score": 0,
"high_score": 0,
"depth": 0
}
# Game settings
default_game_settings = {
"vel_limit" : 7,
"vel_increment" : 0.35,
"vel_decrement" : 0.15,
"max_y_ofs_up" : 50,
"max_y_ofs_down" : 350,
"y_pos_increment" : 5,
"scroll_speed" : 1
}
game_settings = default_game_settings.copy()
# Player init
drill_1 = pygame.image.load("lib/graphics/drill-game/drill1.png").convert_alpha()
drill_2 = pygame.image.load("lib/graphics/drill-game/drill2.png").convert_alpha()
drill_3 = pygame.image.load("lib/graphics/drill-game/drill3.png").convert_alpha()
drill_frames = [drill_1, drill_2, drill_3]
scale = 2.5
drill = Drill(drill_frames, scale=scale)
player = pygame.sprite.GroupSingle(drill)
LEFT_BOUND = drill.dimensions[0]
RIGHT_BOUND = WINDOW_WIDTH - drill.dimensions[0]
# Enemies & Valuabes init
mole_1 = pygame.image.load("lib/graphics/drill-game/mole1.png").convert_alpha()
mole_2 = pygame.image.load("lib/graphics/drill-game/mole2.png").convert_alpha()
worm_1 = pygame.image.load("lib/graphics/drill-game/worm1.png").convert_alpha()
worm_2 = pygame.image.load("lib/graphics/drill-game/worm2.png").convert_alpha()
enemies = pygame.sprite.Group()
valuables = pygame.sprite.Group()
# Background init
block_1 = pygame.image.load("lib/graphics/drill-game/dirt1.png").convert_alpha()
block_2 = pygame.image.load("lib/graphics/drill-game/dirt2.png").convert_alpha()
block_3 = pygame.image.load("lib/graphics/drill-game/dirt3.png").convert_alpha()
block_4 = pygame.image.load("lib/graphics/drill-game/dirt4.png").convert_alpha()
background = GridBackground(block_1.get_size()[0], 3)
background.add_blocks((block_1, 80), (block_2, 30), (block_3, 40), (block_4, 5))
background.init_background()
pause_screen = PauseScreen(screen)
# Timers
obstacle_timer = pygame.USEREVENT + 1
pygame.time.set_timer(obstacle_timer, 2000)
def drill_game():
init_game(game_tracker)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if game_tracker["game_active"] and not game_tracker["game_paused"]:
if event.type == obstacle_timer:
for i in range(
0, int(game_tracker["depth"] / 3000) + 1):
print(i)
facing = "left" if randint(0, 1) else "right"
enemy = "worm" if randint(0, 3) else "mole"
enemies.add(spawn_enemy(enemy, facing))
valuables.add(Gem(scale, randint(0, len(Gem.gems)-1)))
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE or event.key == pygame.K_p:
game_tracker["game_paused"] = True
if game_tracker["game_active"]:
if not game_tracker["game_paused"]:
game_tracker["depth"] += 1
darkness = int(game_tracker["depth"] / 500) * 7.5
if darkness > 200: darkness = 200
background.update_darkness(darkness)
background.draw(screen)
background.update()
valuables.draw(screen)
valuables.update()
enemies.draw(screen)
enemies.update()
player.draw(screen)
player.update()
draw_score(game_tracker, offset=65)
# Collisions
collide_valuable()
collide_enemy()
l_image = pixel_font_small.render(f"Lives: {drill.lives}", False, "gray")
l_rect = l_image.get_rect(center=(WINDOW_WIDTH/2 - 20, 25))
screen.blit(l_image, l_rect)
if drill.lives == 0: game_tracker["game_active"] = False
wall = pygame.Surface((drill.dimensions[0], WINDOW_HEIGHT))
wall_rect = wall.get_rect(bottomright=(LEFT_BOUND, WINDOW_HEIGHT))
wall_rect2 = wall.get_rect(bottomleft=(RIGHT_BOUND, WINDOW_HEIGHT))
wall.fill("black")
screen.blit(wall, wall_rect)
screen.blit(wall, wall_rect2)
else:
if (pause_screen.update(game_tracker) == -1): return
else:
# Game over
if (game_tracker["score"] > game_tracker["high_score"]):
game_tracker["high_score"] = game_tracker["score"]
draw_gameover(screen, "white")
if (game_over_input(game_tracker) == -1): return
pygame.display.update()
clock.tick(60)
if __name__ == "__main__":
pygame.display.set_caption("Drill Rush")
drill_game()