-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgame.py
More file actions
266 lines (214 loc) · 8.55 KB
/
Copy pathgame.py
File metadata and controls
266 lines (214 loc) · 8.55 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
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
"""Game module"""
import pygame
import random
import os
from bullet import Bullet
from enums import KeyType
from inputs import InputManager, PLAYER_KEYMAPS
from player import Player
from enemy_unicorns import UnicornEnemy
from assets import Assets
from config import GAME_FPS
ENEMY_SPAWN_ORDER = [
(0, 10, [UnicornEnemy]),
(10, 20, [UnicornEnemy]),
(20, 9999, [UnicornEnemy]),
]
class AbstractGame:
def __init__(self, **kwargs):
self.screen = kwargs["screen"] # ✅ MUST be set before using
self.input_manager = InputManager()
# ✅ Load and scale background
bg_path = os.path.join("assets", "sprites", "background", "heli.png")
original_bg = pygame.image.load(bg_path).convert()
screen_width = self.screen.get_width()
screen_height = self.screen.get_height()
self.background = pygame.transform.scale(original_bg, (screen_width, screen_height))
self.clock = pygame.time.Clock()
self.running = True
self.tick = 1 * GAME_FPS
self.players = {}
self.npcs = []
self.bullets = []
self.player_bullets = []
self.npc_bullets = []
self.npc_last_shot_times = {}
self.npc_shoot_cooldown = 500
self.score = 0
self.last_spawn_time = pygame.time.get_ticks()
self.spawn_interval_range = (3000, 5000)
self.game_result = None
def spawn_random_npc(self):
sw, sh = self.screen.get_width(), self.screen.get_height()
margin = 10
corners = [
(margin, margin),
(sw - margin, margin),
(margin, sh - margin),
(sw - margin, sh - margin),
]
x, y = random.choice(corners)
for min_score, max_score, enemy_classes in ENEMY_SPAWN_ORDER:
if min_score <= self.score < max_score:
enemy_cls = random.choice(enemy_classes)
self.npcs.append(enemy_cls(x, y))
break
def try_spawn_npc(self):
now = pygame.time.get_ticks()
if now - self.last_spawn_time > self.next_spawn_interval:
self.spawn_random_npc()
self.last_spawn_time = now
self.next_spawn_interval = random.randint(*self.spawn_interval_range)
def try_npc_shoot(self, npc):
now = pygame.time.get_ticks()
npc_id = id(npc)
if now - self.npc_last_shot_times.get(npc_id, 0) < self.npc_shoot_cooldown:
return
target = npc.get_shot_target([p for p in self.players.values() if p.health > 0])
if not target:
return
bullet_image = getattr(npc, "bullet_image", None)
bullet = Bullet(
npc.rect.centerx, npc.rect.centery,
target.rect.centerx, target.rect.centery,
shooter=npc,
image=bullet_image if bullet_image else None,
color=(255, 0, 0) if not bullet_image else (0, 0, 0) # backup only
)
self.npc_bullets.append(bullet)
self.npc_last_shot_times[npc_id] = now
def check_bullet_collisions(self):
for bullet in self.npc_bullets[:]:
for npc in self.npcs:
if bullet.shooter == npc:
for player in self.players.values():
if bullet.rect.colliderect(player.rect):
player.health -= npc.damage
self.npc_bullets.remove(bullet)
break
break
for bullet in self.player_bullets[:]:
for npc in self.npcs[:]:
if bullet.rect.colliderect(npc.rect):
npc.health -= player.damage
if npc.health <= 0:
self.npcs.remove(npc)
self.score += npc.score
self.player_bullets.remove(bullet)
break
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
print("Pressed quitting!")
self.running = False
def handle_key_events(self):
raise NotImplementedError
def update_players(self, **kwargs):
for player in self.players.values():
if player.health <= 0:
continue
inputs = self.input_manager.get_inputs(player.uid)
player.update(inputs=inputs, **kwargs)
if KeyType.SHOOT.name in inputs:
bullet = player.shoot(self.npcs)
if bullet is not None:
self.player_bullets.append(bullet)
self.input_manager.clear_inputs(player.uid)
def update_npcs(self, **kwargs):
for npc in self.npcs[:]:
npc.update(players=self.players, **kwargs)
self.try_npc_shoot(npc)
for player in self.players.values():
if player.health <= 0:
continue
if npc.rect.colliderect(player.rect):
player.health -= npc.damage * 2
self.npcs.remove(npc)
break
def render_all(self):
self.screen.blit(self.background, (0, 0))
for player in self.players.values():
if player.health > 0:
player.draw(self.screen)
for npc in self.npcs:
npc.draw(self.screen)
for bullet in self.player_bullets:
bullet.draw(self.screen)
for bullet in self.npc_bullets:
bullet.draw(self.screen)
font = pygame.font.SysFont(None, 30)
score_surface = font.render(f"Score: {self.score}", True, (255, 255, 255))
self.screen.blit(score_surface, (10, 10))
def update_bullets(self):
for bullet_list in [self.player_bullets, self.npc_bullets]:
for bullet in bullet_list[:]:
bullet.update()
if bullet.is_off_screen():
bullet_list.remove(bullet)
def check_game_end(self):
alive_players = [p for p in self.players.values() if p.health > 0]
if not alive_players:
if self.score >= 200:
self.game_result = "win"
else:
self.game_result = "lost"
self.running = False
def run(self):
self.next_spawn_interval = random.randint(*self.spawn_interval_range)
while self.running:
self.handle_events()
self.handle_key_events()
self.try_spawn_npc()
self.update_players()
self.update_npcs()
self.update_bullets()
self.render_all()
pygame.display.flip()
self.clock.tick(self.tick)
self.check_bullet_collisions()
self.check_game_end()
print("Closing game ....")
return self.game_result
class SingleGame(AbstractGame):
PLAYER1 = "Player1"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.assets = Assets()
center_x = self.screen.get_width() // 2
center_y = self.screen.get_height() // 2
pl1 = Player(self.PLAYER1, assets=self.assets)
pl1.set_coords(center_x - 30, center_y)
self.players[self.PLAYER1] = pl1
self.input_manager.add_keymap(self.PLAYER1, PLAYER_KEYMAPS["wasd"])
self.spawn_random_npc()
def handle_key_events(self):
keys = pygame.key.get_pressed()
for key in PLAYER_KEYMAPS["wasd"].keys():
if keys[key]:
self.input_manager.add_input(self.PLAYER1, key)
class CoopGame(AbstractGame):
PLAYER1 = "Player1"
PLAYER2 = "Player2"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.assets = Assets()
center_x = self.screen.get_width() // 2
center_y = self.screen.get_height() // 2
pl1 = Player(self.PLAYER1, assets=self.assets)
pl1.set_coords(center_x - 30, center_y)
self.players[self.PLAYER1] = pl1
self.input_manager.add_keymap(self.PLAYER1, PLAYER_KEYMAPS["wasd"])
pl2 = Player(self.PLAYER2, assets=self.assets)
pl2.set_coords(center_x + 30, center_y)
pl2.color = (0, 0, 255)
self.players[self.PLAYER2] = pl2
self.input_manager.add_keymap(self.PLAYER2, PLAYER_KEYMAPS["arrows"])
self.spawn_random_npc()
def handle_key_events(self):
keys = pygame.key.get_pressed()
for key in PLAYER_KEYMAPS["wasd"].keys():
if keys[key]:
self.input_manager.add_input(self.PLAYER1, key)
for key in PLAYER_KEYMAPS["arrows"].keys():
if keys[key]:
self.input_manager.add_input(self.PLAYER2, key)