-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
556 lines (467 loc) · 21.5 KB
/
Copy pathmain.py
File metadata and controls
556 lines (467 loc) · 21.5 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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
from raylib import *
from pyray import *
import random
import datetime
TILE_SIZE = 16
WINDOW_WIDTH, WINDOW_HEIGHT = 1280, 720 # Wider view
MAX_ENEMIES = 300 # More space, more enemies
MAX_ALLIES = 50 # Performance limit for allies
NEIGHBOUR_OFFSET = [
(-1, -1), (0, -1), (1, -1), # Top row
(-1, 0), (1, 0), # Middle row (skipping 0,0)
(-1, 1), (0, 1), (1, 1) # Bottom row
]
class Player:
def __init__(self, x, y):
self.x = x
self.y = y
self.trail = [(x, y)]
self.move_timer = 0
self.move_delay = 0.12 # Slightly slower player
self.last_dir = (0, 1) # Default shooting direction (Down)
def move(self, dx, dy, grid, width, height):
self.last_dir = (dx, dy) # Update shooting direction
new_x, new_y = self.x + dx, self.y + dy
# Check bounds and walls
if 0 <= new_x < width and 0 <= new_y < height:
# Check for SOLID walls (1) AND the existing trail.
# Fake walls (2) are ignored here so you can walk through them.
if grid.get((new_x, new_y)) != 1 and (new_x, new_y) not in self.trail:
self.x = new_x
self.y = new_y
self.trail.append((new_x, new_y))
return True
return False
def draw(self):
# Draw Trail
for i in range(len(self.trail) - 1):
p1 = self.trail[i]
p2 = self.trail[i+1]
draw_line_ex(
Vector2(p1[0] * TILE_SIZE + TILE_SIZE // 2, p1[1] * TILE_SIZE + TILE_SIZE // 2),
Vector2(p2[0] * TILE_SIZE + TILE_SIZE // 2, p2[1] * TILE_SIZE + TILE_SIZE // 2),
4, SKYBLUE
)
# Draw Player head
draw_rectangle(self.x * TILE_SIZE, self.y * TILE_SIZE, TILE_SIZE, TILE_SIZE, MAROON)
class Enemy:
def __init__(self, x, y, spawn_delay=8.0):
self.x = x
self.y = y
self.move_timer = 0
self.move_delay = 0.35 # Slightly slower chasing
self.spawn_timer = 0
self.spawn_delay = spawn_delay # Relaxed multiplication
def update(self, dt, player, grid, flow_field, fallback_flow_field, enemy_positions):
self.move_timer += dt
self.spawn_timer += dt
# Move towards player using flow field
if self.move_timer >= self.move_delay:
self.move_timer = 0
# Use main flow field if possible, otherwise fallback
target_field = flow_field
if (self.x, self.y) not in flow_field:
target_field = fallback_flow_field
current_dist = target_field.get((self.x, self.y), 999999)
# Collect all possible moves that decrease distance
possible_moves = []
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nx, ny = self.x + dx, self.y + dy
if (nx, ny) in target_field:
dist = target_field[(nx, ny)]
if dist < current_dist:
# Avoid other enemies if they are at the destination
# (Soft avoidance: still allow move if it's the only option)
is_occupied = (nx, ny) in enemy_positions
possible_moves.append(((nx, ny), dist, is_occupied))
if possible_moves:
# 1. Filter for non-occupied moves if possible
non_occupied = [m for m in possible_moves if not m[2]]
choices = non_occupied if non_occupied else possible_moves
# 2. Filter for minimum distance
min_dist = min(m[1] for m in choices)
best_choices = [m[0] for m in choices if m[1] == min_dist]
# 3. Pick randomly from best choices
self.x, self.y = random.choice(best_choices)
# Multiply
if self.spawn_timer >= self.spawn_delay:
self.spawn_timer = 0
# New enemies multiply much slower (Difficulty Ramp)
new_delay = max(2.0, self.spawn_delay * 0.98)
return Enemy(self.x, self.y, new_delay)
return None
def draw(self):
draw_rectangle(self.x * TILE_SIZE, self.y * TILE_SIZE, TILE_SIZE, TILE_SIZE, PURPLE)
class Ally:
def __init__(self, x, y, spawn_delay=30.0):
self.x = x
self.y = y
self.active = False # Starts unactivated
self.move_timer = 0
self.move_delay = 0.15 # Slightly slower than player
self.spawn_timer = 0
self.spawn_delay = spawn_delay # Multiplies very slowly
self.shoot_timer = 0
self.shoot_delay = 1.0 # Fires every second
def update(self, dt, player, enemies, flow_field, ally_positions):
if not self.active:
# Activate if player is nearby
if abs(self.x - player.x) <= 1 and abs(self.y - player.y) <= 1:
self.active = True
return None
self.move_timer += dt
self.spawn_timer += dt
self.shoot_timer += dt
# Follow player using flow field
if self.move_timer >= self.move_delay:
self.move_timer = 0
current_dist = flow_field.get((self.x, self.y), 999999)
# Allies want to be near player but not on top of player or each other
if current_dist > 2: # Keep a small distance from player
possible_moves = []
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nx, ny = self.x + dx, self.y + dy
if (nx, ny) in flow_field:
dist = flow_field[(nx, ny)]
if dist < current_dist:
is_occupied = (nx, ny) in ally_positions or (nx, ny) == (player.x, player.y)
possible_moves.append(((nx, ny), dist, is_occupied))
if possible_moves:
non_occupied = [m for m in possible_moves if not m[2]]
choices = non_occupied if non_occupied else possible_moves
min_dist = min(m[1] for m in choices)
best_choices = [m[0] for m in choices if m[1] == min_dist]
self.x, self.y = random.choice(best_choices)
# Shoot at nearest enemy
new_bullet = None
if self.shoot_timer >= self.shoot_delay and enemies:
nearest_enemy = min(enemies, key=lambda e: abs(e.x - self.x) + abs(e.y - self.y))
dist = abs(nearest_enemy.x - self.x) + abs(nearest_enemy.y - self.y)
if dist < 10: # Shooting range
self.shoot_timer = 0
dx = 1 if nearest_enemy.x > self.x else -1 if nearest_enemy.x < self.x else 0
dy = 1 if nearest_enemy.y > self.y else -1 if nearest_enemy.y < self.y else 0
if dx != 0 or dy != 0:
new_bullet = Bullet(self.x, self.y, dx, dy)
# Multiply
if self.spawn_timer >= self.spawn_delay:
self.spawn_timer = 0
return Ally(self.x, self.y, self.spawn_delay)
return new_bullet
def draw(self):
color = SKYBLUE if self.active else GRAY
draw_rectangle(self.x * TILE_SIZE, self.y * TILE_SIZE, TILE_SIZE, TILE_SIZE, color)
if self.active:
draw_rectangle_lines(self.x * TILE_SIZE, self.y * TILE_SIZE, TILE_SIZE, TILE_SIZE, BLUE)
class Bullet:
def __init__(self, x, y, dx, dy):
self.x = float(x)
self.y = float(y)
self.dx = dx
self.dy = dy
self.speed = 20.0 # Tiles per second
self.active = True
def update(self, dt, grid, width, height):
self.x += self.dx * self.speed * dt
self.y += self.dy * self.speed * dt
# Check bounds
if not (0 <= self.x < width and 0 <= self.y < height):
self.active = False
return
# Check walls
if grid.get((int(self.x), int(self.y))) == 1:
self.active = False
def draw(self):
draw_circle(int(self.x * TILE_SIZE + TILE_SIZE // 2),
int(self.y * TILE_SIZE + TILE_SIZE // 2),
3, ORANGE)
class Main:
def __init__(self):
init_window(WINDOW_WIDTH, WINDOW_HEIGHT, 'One line a day')
set_target_fps(60)
set_window_position(480, 60)
# Expanded Landscape
self.grid_width, self.grid_height = 150, 150
self.grid = {} # 1 = Solid, 2 = Fake Wall
self.player = None
self.enemies = []
self.allies = []
self.bullets = []
# Camera
self.camera = Camera2D()
self.camera.target = Vector2(0, 0)
self.camera.offset = Vector2(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)
self.camera.rotation = 0.0
self.camera.zoom = 1.0
self.flow_field = {} # Distance map to player (respects trails)
self.fallback_flow_field = {} # Distance map to player (ignores trails)
self.exit_pos = None
self.game_over = False
self.message = ""
# Use date as seed for daily challenge
self.seed = datetime.date.today().toordinal()
random.seed(self.seed)
self.generate_world()
def generate_world(self):
self.grid = {}
self.enemies = []
self.allies = []
self.bullets = []
self.flow_field = {}
self.fallback_flow_field = {}
self.game_over = False
self.message = ""
# 1. Initial random fill
for x in range(self.grid_width):
for y in range(self.grid_height):
if random.random() < 0.45:
self.grid[(x,y)] = 1
# 2. Smooth several times
for _ in range(5):
self.smooth()
# 3. Add Fake Walls (convert some floors near walls to fake walls)
self.add_fake_walls()
# 4. Spawn player, exit and entities
self.spawn_entities()
self.update_flow_field()
# Initial camera target
if self.player:
self.camera.target = Vector2(self.player.x * TILE_SIZE, self.player.y * TILE_SIZE)
def update_flow_field(self):
# 1. BFS for Main Flow Field (Respects trails)
self.flow_field = self._calculate_bfs(respect_trails=True)
# 2. BFS for Fallback Flow Field (Ignores trails)
self.fallback_flow_field = self._calculate_bfs(respect_trails=False)
def _calculate_bfs(self, respect_trails=True):
dist_map = {}
queue = [(self.player.x, self.player.y, 0)]
dist_map[(self.player.x, self.player.y)] = 0
trail_set = set(self.player.trail) if respect_trails else set()
head = 0
while head < len(queue):
cx, cy, dist = queue[head]
head += 1
# Use cardinal directions
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nx, ny = cx + dx, cy + dy
if 0 <= nx < self.grid_width and 0 <= ny < self.grid_height:
if (nx, ny) not in dist_map:
# Only floor or fake walls are passable
if self.grid.get((nx, ny)) != 1 and (nx, ny) not in trail_set:
dist_map[(nx, ny)] = dist + 1
queue.append((nx, ny, dist + 1))
return dist_map
def add_fake_walls(self):
# Find floor tiles that have at least one wall neighbor and turn them into fake walls
potential_fake_walls = []
for x in range(self.grid_width):
for y in range(self.grid_height):
if (x, y) not in self.grid:
# Check if it has a wall neighbor
has_wall_neighbor = False
for ox, oy in NEIGHBOUR_OFFSET:
nx, ny = x + ox, y + oy
if self.grid.get((nx, ny)) == 1:
has_wall_neighbor = True
break
if has_wall_neighbor and random.random() < 0.1: # 10% chance for a floor near a wall to be fake
potential_fake_walls.append((x, y))
for pos in potential_fake_walls:
self.grid[pos] = 2
def spawn_entities(self):
# Find player start (top left-ish)
found_player = False
for x in range(self.grid_width):
for y in range(self.grid_height):
if self.grid.get((x, y)) != 1:
self.player = Player(x, y)
found_player = True
break
if found_player: break
# CRITICAL: Calculate reachability immediately after placing player
# so that the exit and enemies can check if they can reach the player.
self.fallback_flow_field = self._calculate_bfs(respect_trails=False)
# Find exit (bottom right-ish)
found_exit = False
for x in range(self.grid_width - 1, -1, -1):
for y in range(self.grid_height - 1, -1, -1):
if self.grid.get((x, y)) != 1 and (x, y) != (self.player.x, self.player.y):
# Ensure the exit is actually reachable from the player's start
if (x, y) in self.fallback_flow_field:
self.exit_pos = (x, y)
found_exit = True
break
if found_exit: break
# Spawn initial enemies (far from player)
enemies_to_spawn = 6 # Reduced from 15
spawned_count = 0
attempts = 0
while spawned_count < enemies_to_spawn and attempts < 1000:
ex = random.randint(0, self.grid_width - 1)
ey = random.randint(0, self.grid_height - 1)
# Ensure it's floor and far from player
if self.grid.get((ex, ey)) != 1 and abs(ex - self.player.x) + abs(ey - self.player.y) > 50:
# Ensure it's not on top of another enemy
if not any(e.x == ex and e.y == ey for e in self.enemies):
# Ensure the enemy has a path to the player (reachable)
if (ex, ey) in self.fallback_flow_field:
self.enemies.append(Enemy(ex, ey))
spawned_count += 1
attempts += 1
# Spawn unactivated allies
allies_to_spawn = 12 # Increased from 8
spawned_count = 0
attempts = 0
while spawned_count < allies_to_spawn and attempts < 1000:
ax = random.randint(0, self.grid_width - 1)
ay = random.randint(0, self.grid_height - 1)
if self.grid.get((ax, ay)) != 1 and abs(ax - self.player.x) + abs(ay - self.player.y) > 15:
if (ax, ay) in self.fallback_flow_field:
self.allies.append(Ally(ax, ay))
spawned_count += 1
attempts += 1
def smooth(self):
new_grid = {}
for x in range(self.grid_width):
for y in range(self.grid_height):
neighbours = self.count_neighbours(x, y)
if neighbours > 4:
new_grid[(x, y)] = 1
elif neighbours < 4:
pass
else:
if self.grid.get((x, y)) == 1:
new_grid[(x, y)] = 1
self.grid = new_grid
def count_neighbours(self, x, y):
count = 0
for offset_x, offset_y in NEIGHBOUR_OFFSET:
neigh_x, neigh_y = x + offset_x, y + offset_y
if not (0 <= neigh_x < self.grid_width and 0 <= neigh_y < self.grid_height):
count += 1
elif self.grid.get((neigh_x, neigh_y)) == 1:
count += 1
return count
def update(self):
if self.game_over:
if is_key_pressed(KEY_R):
# Manual reset uses a new random seed
self.seed = random.randint(0, 1000000)
random.seed(self.seed)
self.generate_world()
return
dt = get_frame_time()
# Update Enemies
new_enemies = []
enemy_positions = {(e.x, e.y) for e in self.enemies}
for enemy in self.enemies:
# Note: enemy_positions includes the current enemy, but since it's checking
# nx, ny (neighbors), it only matters if a NEIGHBOR is occupied.
spawned = enemy.update(dt, self.player, self.grid, self.flow_field, self.fallback_flow_field, enemy_positions)
if spawned and len(self.enemies) + len(new_enemies) < MAX_ENEMIES:
new_enemies.append(spawned)
# Collision check
if enemy.x == self.player.x and enemy.y == self.player.y:
self.game_over = True
self.message = "CAUGHT BY THE VIRUS!"
self.enemies.extend(new_enemies)
# Update Allies
new_allies = []
ally_positions = {(a.x, a.y) for a in self.allies}
for ally in self.allies:
result = ally.update(dt, self.player, self.enemies, self.flow_field, ally_positions)
if isinstance(result, Bullet):
self.bullets.append(result)
elif isinstance(result, Ally):
if len(self.allies) + len(new_allies) < MAX_ALLIES:
new_allies.append(result)
self.allies.extend(new_allies)
# Update Bullets
if is_key_pressed(KEY_SPACE):
bx, by = self.player.x, self.player.y
bdx, bdy = self.player.last_dir
self.bullets.append(Bullet(bx, by, bdx, bdy))
for bullet in self.bullets:
bullet.update(dt, self.grid, self.grid_width, self.grid_height)
# Bullet-Enemy Collision
bx, by = int(bullet.x), int(bullet.y)
for enemy in self.enemies:
if enemy.x == bx and enemy.y == by:
self.enemies.remove(enemy)
bullet.active = False
break
# Clean up inactive bullets
self.bullets = [b for b in self.bullets if b.active]
# Movement with continuous support
self.player.move_timer += dt
dx, dy = 0, 0
if is_key_down(KEY_W) or is_key_down(KEY_UP): dy = -1
elif is_key_down(KEY_S) or is_key_down(KEY_DOWN): dy = 1
elif is_key_down(KEY_A) or is_key_down(KEY_LEFT): dx = -1
elif is_key_down(KEY_D) or is_key_down(KEY_RIGHT): dx = 1
if (dx != 0 or dy != 0) and self.player.move_timer >= self.player.move_delay:
moved = self.player.move(dx, dy, self.grid, self.grid_width, self.grid_height)
if moved:
self.player.move_timer = 0
self.update_flow_field()
# Update Camera
self.camera.target = Vector2(self.player.x * TILE_SIZE, self.player.y * TILE_SIZE)
# Check Win Condition
if (self.player.x, self.player.y) == self.exit_pos:
self.game_over = True
self.message = "DAILY GOAL REACHED!"
# Controls
if is_key_pressed(KEY_R):
self.generate_world()
def draw(self):
begin_drawing()
clear_background(DARKGRAY) # Background is now the wall color (infinite rock)
begin_mode_2d(self.camera)
# Draw Floors (with culling)
screen_min_x = int((self.camera.target.x - self.camera.offset.x) // TILE_SIZE) - 1
screen_max_x = int((self.camera.target.x + self.camera.offset.x) // TILE_SIZE) + 1
screen_min_y = int((self.camera.target.y - self.camera.offset.y) // TILE_SIZE) - 1
screen_max_y = int((self.camera.target.y + self.camera.offset.y) // TILE_SIZE) + 1
for x in range(max(0, screen_min_x), min(self.grid_width, screen_max_x)):
for y in range(max(0, screen_min_y), min(self.grid_height, screen_max_y)):
# If it's NOT in the grid, it's a floor.
# Walls (1) and Fake Walls (2) are in the grid and will be DARKGRAY (background).
if (x, y) not in self.grid:
draw_rectangle(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE, RAYWHITE)
# Draw Exit
if self.exit_pos:
draw_rectangle(self.exit_pos[0] * TILE_SIZE,
self.exit_pos[1] * TILE_SIZE,
TILE_SIZE, TILE_SIZE, GOLD)
# Draw Allies
for ally in self.allies:
ally.draw()
# Draw Enemies
for enemy in self.enemies:
enemy.draw()
# Draw Bullets
for bullet in self.bullets:
bullet.draw()
# Draw Player & Trail
if self.player:
self.player.draw()
end_mode_2d()
# UI
draw_text(f"Seed: {self.seed}", 10, 10, 20, RAYWHITE)
draw_text(f"Enemies: {len(self.enemies)}", 10, 40, 20, PINK)
if self.game_over:
draw_rectangle(0, WINDOW_HEIGHT // 2 - 50, WINDOW_WIDTH, 100, (0, 0, 0, 150))
text_color = GOLD if "REACHED" in self.message else RED
draw_text(self.message, WINDOW_WIDTH // 2 - measure_text(self.message, 40) // 2,
WINDOW_HEIGHT // 2 - 20, 40, text_color)
draw_text("Press R to play a random map", WINDOW_WIDTH // 2 - measure_text("Press R to play a random map", 20) // 2,
WINDOW_HEIGHT // 2 + 30, 20, RAYWHITE)
end_drawing()
def run(self):
while not window_should_close():
self.update()
self.draw()
close_window()
if __name__ == '__main__':
main = Main()
main.run()