-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathserver.py
More file actions
1665 lines (1436 loc) · 78.6 KB
/
server.py
File metadata and controls
1665 lines (1436 loc) · 78.6 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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import socket
import threading
import time
import numpy as np
import pygame
import os
from engine.weapons.weapons import WEAPONS, get_weapon
from engine.spawners.gun_spawner import GunSpawner, PlayerInventory
from engine.spawners.medkit_spawner import MedkitSpawner
import config
class Server:
def grenade_effect_active_after_explosion(self, grenade_slot):
"""True when a grenade slot is no longer active but its lingering effect still exists."""
if 48 <= grenade_slot <= 54 and self.world_data[grenade_slot, 0] == 1:
return False
return any(
effect.get('source_slot') == grenade_slot and effect.get('duration', 0) > 0
for effect in self.gas_effects.values()
)
def grenade_damage(self, distance, max_damage, radius, falloff=2):
if distance >= radius:
return 0.0
damage = max_damage * (1 - (distance / radius))
return damage
def throw_grenade(self, player_id, grenade_id, throw_angle, throw_power):
"""
Spawns a grenade with gravity-based arc.
- player_id: int, the player throwing
- grenade_id: int, type of grenade (from weapons.py)
- throw_angle: float, angle in radians
- throw_power: float, initial speed
"""
from engine.weapons.weapons import get_grenade
# Find a free grenade slot (rows 48-54)
for i in range(48, 55):
if self.world_data[i, 0] == 0:
# Get player position
px, py = self.world_data[player_id, 1], self.world_data[player_id, 2]
vx = throw_power * np.cos(throw_angle)
vy = throw_power * np.sin(throw_angle)
grenade = get_grenade(grenade_id)
if grenade is None:
return False
# Fill world_data for grenade
self.world_data[i, 0] = 1 # active
self.world_data[i, 1] = px
self.world_data[i, 2] = py
self.world_data[i, 3] = throw_angle # store angle if needed
self.world_data[i, 4] = vx # vx
self.world_data[i, 5] = vy # vy
self.world_data[i, 6] = grenade.blast_radius
self.world_data[i, 7] = grenade.damage
self.world_data[i, 8] = grenade.effect_time
self.world_data[i, 9] = player_id
self.world_data[i, 10] = grenade_id
# Store fuse timer in a dict for each grenade slot
if not hasattr(self, 'grenade_fuse_timers'):
self.grenade_fuse_timers = {}
# proxy grenades should arm after 2 seconds regardless of their config
if grenade.is_proxy:
self.grenade_fuse_timers[i] = 2.0
# ensure we have an armed-state tracker
if not hasattr(self, 'proxy_armed'):
self.proxy_armed = set()
else:
self.grenade_fuse_timers[i] = grenade.fuse_time
return True
return False # No free slot
def __init__(self):
PORT = config.SERVER_PORT
if not self._start_server(PORT):
return
self.setup_game()
thread = threading.Thread(target=self.add_players, daemon=True)
thread.start()
self.player_lock = threading.Lock()
self.run_game()
def _start_server(self, PORT):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
HOST_NAME = socket.gethostname()
SERVER_IP = socket.gethostbyname(HOST_NAME)
try:
self.server_socket.bind((SERVER_IP, PORT))
except socket.error as e:
print(str(e))
print("[SERVER] Server could not start")
return False
self.server_socket.listen()
print(f"[SERVER] Server Started with local ip {SERVER_IP}")
return True
def setup_game(self):
self.match_ended = False
self.match_start_time = None
self.match_duration = config.MATCH_DURATION
self.player_names = [""] * 8
# Grenade cooldown per player (seconds)
self.player_grenade_cooldown = np.zeros(8, dtype=np.float64)
self.player_respawn_cooldown = np.zeros(8, dtype=np.float64)
self.player_count = 0
# [kills, deaths] per player. K/D delta is computed as kills - deaths.
self.player_stats = np.zeros((8, 2), dtype=np.int32)
# world_data columns (per row):
# 0:is_alive, 1:x, 2:y, 3:theta, 4:v, 5:omega_or_traveled, 6:fuel, 7:health_or_damage, 8:score, 9:current_ammo, 10:total_ammo_or_weapon_id
# for tanks: column 6 = fuel, 7 = health, 8 = score, 9 = current_ammo, 10 = total_ammo
# for bullets: column 5 = distance traveled, 7 = snapshot damage, 9 = owner id, 10 = weapon id
self.world_data = np.zeros((55, 11), dtype=np.float64)
self.player_inputs = np.zeros((8, 14), dtype=np.int32) # inputs: W,A,D,UP,DOWN,LEFT,RIGHT,SPACE,R,S,G,C,P,KNEEL
self.grenade_data = np.zeros((10, 4), dtype=np.float64) # separate array for grenades (slots 48-54 in world_data)
self.grenade_data[:8, 0] = 1 # default selected grenade type: frag
self.grenade_data[:8, 1] = config.FRAG_GRENADE_COUNT
self.grenade_data[:8, 2] = config.PROXY_GRENADE_COUNT
self.grenade_data[:8, 3] = config.GAS_GREANADE_COUNT
# Load constants from config
TANK_V = config.TANK_SPEED
TANK_OMEGA = config.TANK_ROTATION_SPEED
BULLET_V = config.BULLET_SPEED
self.world_data[:8, 4] = TANK_V
self.world_data[:8, 5] = TANK_OMEGA
self.world_data[8:, 4] = BULLET_V
# per-player vertical velocity for gravity (tanks only)
self.player_vy = np.zeros(8, dtype=np.float64)
self.player_stuck_frames = np.zeros(8, dtype=np.int32)
# screen and tank constants for ground handling
self.SCREEN_W = 800
self.SCREEN_H = 600
self.TANK_RADIUS = config.TANK_VISUAL_RADIUS
self.COLLISION_RADIUS = config.TANK_COLLISION_RADIUS
self.PLAYER_HITBOX_W = float(getattr(config, 'PLAYER_HITBOX_WIDTH', 40.0))
self.PLAYER_HITBOX_H = float(getattr(config, 'PLAYER_HITBOX_HEIGHT', 40.0))
self.PLAYER_HALF_W = self.PLAYER_HITBOX_W * 0.5
self.PLAYER_HALF_H = self.PLAYER_HITBOX_H * 0.5
self.KNEEL_HEIGHT_DELTA = float(getattr(config, 'KNEEL_HEIGHT_DELTA', 5.0))
self.KNEEL_HALF_H = max(2.0, self.PLAYER_HALF_H - (self.KNEEL_HEIGHT_DELTA * 0.5))
self.KNEEL_SPEED_MULTIPLIER = float(getattr(config, 'KNEEL_SPEED_MULTIPLIER', 0.6))
self.player_is_kneeling = np.zeros(8, dtype=bool)
self.player_half_h = np.full(8, self.PLAYER_HALF_H, dtype=np.float64)
self.GROUND_Y = self.SCREEN_H - self.PLAYER_HALF_H
self.GRAVITY = config.GRAVITY
# Jetpack system
self.player_fuel = np.full(8, config.MAX_FUEL, dtype=np.float64)
self.MAX_FUEL = config.MAX_FUEL
self.FUEL_CONSUMPTION = config.FUEL_CONSUMPTION
self.FUEL_RECHARGE = config.FUEL_RECHARGE
self.JETPACK_THRUST = config.JETPACK_THRUST
self.KNEEL_JUMP_IMPULSE = float(getattr(config, 'KNEEL_JUMP_IMPULSE', 3.0))
self.KNEEL_GROUND_TOLERANCE = float(getattr(config, 'KNEEL_GROUND_TOLERANCE', 1.5))
# Use column 6 (info) to store fuel for tanks
self.world_data[:8, 6] = self.player_fuel
# Health and score per tank
self.MAX_HEALTH = config.MAX_HEALTH
self.HEALTH_REGEN_ENABLED = bool(getattr(config, 'HEALTH_REGEN_ENABLED', False))
self.HEALTH_REGEN_PER_SECOND = float(getattr(config, 'HEALTH_REGEN_PER_SECOND', 0.0))
self.RESPAWN_DELAY = getattr(config, 'RESPAWN_DELAY', 5.0)
self.world_data[:8, 7] = self.MAX_HEALTH # health
self.world_data[:8, 8] = 0.0 # score
# Weapon system - player inventories with dual gun support
secondary_default = getattr(config, 'DEFAULT_SECONDARY_WEAPON', 2)
self.player_inventories = [
PlayerInventory(
starting_weapon_id=config.get_random_starting_weapon(),
secondary_weapon_id=secondary_default,
)
for _ in range(8)
]
# Fire rate cooldown per player (in seconds, tracks time since last shot)
self.player_fire_cooldown = np.zeros(8, dtype=np.float64)
self.saw_charge_end_time = np.zeros(8, dtype=np.float64)
# Reload cooldown per player (in seconds, tracks time remaining for reload)
self.player_reload_cooldown = np.zeros(8, dtype=np.float64)
# Track previous frame's input state for edge detection
self.previous_inputs = np.zeros((8, 14), dtype=np.int32)
self.last_frame_time = time.time()
# Collision map system - grid-based obstacles
self.GRID_SIZE = config.GRID_SIZE
# Load map from file - this will set GRID_W, GRID_H, and collision_map
self.current_map_name = config.DEFAULT_MAP
self.load_map(self.current_map_name)
# Gas grenade effect tracking - stores active gas zones
# Format: {effect_id: {'x': x, 'y': y, 'radius': radius, 'damage': damage, 'duration': remaining_time}}
self.gas_effects = {}
self.gas_effect_counter = 0 # Unique ID for each gas effect
# Initialize gun spawner system
self.gun_spawner = GunSpawner()
self.gun_spawner.initialize_map(self.current_map_name)
# Initialize medkit spawner system
self.medkit_spawner = MedkitSpawner()
self.medkit_spawner.set_collision_map(self.collision_map, self.GRID_SIZE, self.GRID_W, self.GRID_H)
self.medkit_spawner.initialize_map(self.current_map_name)
# Update screen dimensions based on loaded map
self.SCREEN_W = self.GRID_W * self.GRID_SIZE
self.SCREEN_H = self.GRID_H * self.GRID_SIZE
self.GROUND_Y = self.SCREEN_H - self.PLAYER_HALF_H
# Build safe spawn positions from map geometry so players never spawn outside terrain.
self._rebuild_spawn_candidates()
# Convert map to bytes for transmission
self.collision_map_bytes = self.collision_map.tobytes()
def _record_player_death(self, victim_idx, killer_idx=None):
"""Register one death and optional kill attribution, then schedule respawn."""
if self.world_data[victim_idx, 0] != 1:
return False
self.player_stats[victim_idx, 1] += 1
if killer_idx is not None and 0 <= killer_idx < 8 and killer_idx != victim_idx:
self.player_stats[killer_idx, 0] += 1
self.world_data[killer_idx, 8] = float(self.player_stats[killer_idx, 0])
self.world_data[victim_idx, 7] = 0
self.respawn(victim_idx, delay=self.RESPAWN_DELAY)
return True
def _apply_damage_to_player(self, victim_idx, damage, killer_idx=None):
"""Apply damage and attribute kill to attacker only if this is the lethal hit."""
if self.world_data[victim_idx, 0] != 1:
return False
if damage <= 0:
return False
self.world_data[victim_idx, 7] -= float(damage)
if self.world_data[victim_idx, 7] <= 0:
return self._record_player_death(victim_idx, killer_idx)
return False
def _apply_health_regeneration(self, delta_time):
"""Apply slow linear health regeneration to alive players."""
if not self.HEALTH_REGEN_ENABLED:
return
if self.HEALTH_REGEN_PER_SECOND <= 0.0:
return
regen_amount = self.HEALTH_REGEN_PER_SECOND * float(delta_time)
if regen_amount <= 0.0:
return
for idx in range(8):
if self.world_data[idx, 0] != 1:
continue
health = self.world_data[idx, 7]
if health <= 0.0 or health >= self.MAX_HEALTH:
continue
self.world_data[idx, 7] = min(self.MAX_HEALTH, health + regen_amount)
def _build_leaderboard_array(self):
"""Return top-8 leaderboard rows: [player_idx, kills, deaths, kills_minus_deaths]."""
rows = []
for idx in range(8):
kills = int(self.player_stats[idx, 0])
deaths = int(self.player_stats[idx, 1])
kd_delta = kills - deaths
name = self.player_names[idx].strip() if idx < len(self.player_names) else ""
include = bool(name) or self.world_data[idx, 0] != 0 or kills > 0 or deaths > 0
if include:
rows.append((idx, kills, deaths, kd_delta))
rows.sort(key=lambda r: (-r[1], -r[3], r[0]))
board = np.full((8, 4), -1, dtype=np.int32)
for i, row in enumerate(rows[:8]):
board[i] = np.array(row, dtype=np.int32)
return board
def _rebuild_spawn_candidates(self):
"""Collect valid standable points from map collision tiles."""
self.spawn_candidates = []
min_x = self.PLAYER_HALF_W
max_x = self.SCREEN_W - self.PLAYER_HALF_W
min_y = self.PLAYER_HALF_H
max_y = self.SCREEN_H - self.PLAYER_HALF_H
for gy in range(1, self.GRID_H):
for gx in range(self.GRID_W):
# 0 = obstacle/floor tile, 1 = passable tile
if self.collision_map[gy, gx] != 0:
continue
if self.collision_map[gy - 1, gx] != 1:
continue
x = gx * self.GRID_SIZE + (self.GRID_SIZE // 2)
y = gy * self.GRID_SIZE - self.PLAYER_HALF_H
if x < min_x or x > max_x or y < min_y or y > max_y:
continue
if not self.is_player_colliding_with_obstacle(x, y):
self.spawn_candidates.append((float(x), float(y)))
def _get_safe_spawn_position(self):
"""Return a safe spawn point inside map bounds and away from solid tiles."""
if getattr(self, 'spawn_candidates', None):
idx = np.random.randint(0, len(self.spawn_candidates))
return self.spawn_candidates[idx]
min_x = int(np.ceil(self.PLAYER_HALF_W))
max_x = int(np.floor(self.SCREEN_W - self.PLAYER_HALF_W))
if max_x <= min_x:
return float(self.SCREEN_W // 2), float(max(self.PLAYER_HALF_H, self.SCREEN_H - self.PLAYER_HALF_H))
for _ in range(64):
spawn_x = float(np.random.randint(min_x, max_x + 1))
ground_y = self.find_ground_below(spawn_x, 0)
spawn_y = float(self.GROUND_Y if ground_y is None else ground_y)
spawn_y = float(np.clip(spawn_y, self.PLAYER_HALF_H, self.SCREEN_H - self.PLAYER_HALF_H))
if not self.is_player_colliding_with_obstacle(spawn_x, spawn_y):
return spawn_x, spawn_y
return float(self.SCREEN_W // 2), float(np.clip(self.GROUND_Y, self.PLAYER_HALF_H, self.SCREEN_H - self.PLAYER_HALF_H))
def load_map(self, map_name):
"""Load map from maps/ folder or create default if not found"""
map_path = os.path.join("maps", f"{map_name}.npy")
if os.path.exists(map_path):
try:
self.collision_map = np.load(map_path)
# Extract dimensions from loaded map
self.GRID_H, self.GRID_W = self.collision_map.shape
print(f"[SERVER] Loaded map: {map_name} (dimensions: {self.GRID_W}x{self.GRID_H})")
return True
except Exception as e:
print(f"[SERVER] Error loading map {map_name}: {e}")
# Create default map if file not found
print(f"[SERVER] Map '{map_name}' not found, creating default map")
# Use default dimensions if not already set
if not hasattr(self, 'GRID_W'):
self.GRID_W = 80
self.GRID_H = 60
self.collision_map = np.ones((self.GRID_H, self.GRID_W), dtype=np.int32)
# Simple default layout
self.collision_map[-1, :] = 0 # Ground floor
if self.GRID_H > 20:
self.collision_map[20, 5:min(15, self.GRID_W)] = 0 # Left platform
if self.GRID_H > 15:
self.collision_map[15, 25:min(35, self.GRID_W)] = 0 # Right platform
if self.GRID_H > 10:
self.collision_map[10, 10:min(20, self.GRID_W)] = 0 # Top platform
return False
def is_colliding_with_obstacle(self, x, y, radius):
"""Check if a circle at (x, y) with given radius collides with any obstacle"""
# Check all grid cells that the circle overlaps
min_grid_x = max(0, int((x - radius) / self.GRID_SIZE))
max_grid_x = min(self.GRID_W - 1, int((x + radius) / self.GRID_SIZE))
min_grid_y = max(0, int((y - radius) / self.GRID_SIZE))
max_grid_y = min(self.GRID_H - 1, int((y + radius) / self.GRID_SIZE))
for gy in range(min_grid_y, max_grid_y + 1):
for gx in range(min_grid_x, max_grid_x + 1):
if self.collision_map[gy, gx] == 0: # obstacle
# Check if circle intersects this grid cell
cell_x = gx * self.GRID_SIZE
cell_y = gy * self.GRID_SIZE
# Find closest point in rectangle to circle center
closest_x = max(cell_x, min(x, cell_x + self.GRID_SIZE))
closest_y = max(cell_y, min(y, cell_y + self.GRID_SIZE))
# Check distance
dist = np.sqrt((x - closest_x)**2 + (y - closest_y)**2)
if dist < radius:
return True
return False
def is_rect_colliding_with_obstacle(self, cx, cy, half_w, half_h):
"""Check if axis-aligned rectangle centered at (cx, cy) overlaps any obstacle tile."""
left = cx - half_w
right = cx + half_w
top = cy - half_h
bottom = cy + half_h
min_grid_x = max(0, int(np.floor(left / self.GRID_SIZE)))
max_grid_x = min(self.GRID_W - 1, int(np.floor(right / self.GRID_SIZE)))
min_grid_y = max(0, int(np.floor(top / self.GRID_SIZE)))
max_grid_y = min(self.GRID_H - 1, int(np.floor(bottom / self.GRID_SIZE)))
for gy in range(min_grid_y, max_grid_y + 1):
for gx in range(min_grid_x, max_grid_x + 1):
if self.collision_map[gy, gx] != 0:
continue
cell_left = gx * self.GRID_SIZE
cell_top = gy * self.GRID_SIZE
cell_right = cell_left + self.GRID_SIZE
cell_bottom = cell_top + self.GRID_SIZE
if right > cell_left and left < cell_right and bottom > cell_top and top < cell_bottom:
return True
return False
def _get_player_half_h(self, player_idx):
if player_idx is None:
return self.PLAYER_HALF_H
return float(self.player_half_h[player_idx])
def _get_target_half_h(self, kneeling):
return self.KNEEL_HALF_H if kneeling else self.PLAYER_HALF_H
def is_player_colliding_with_obstacle(self, x, y, player_idx=None):
return self.is_rect_colliding_with_obstacle(x, y, self.PLAYER_HALF_W, self._get_player_half_h(player_idx))
def _push_player_out_of_obstacle(self, x, y, player_idx=None, push_x=0.0, push_y=0.0):
"""Try to move a player rectangle out of terrain using short directional nudges."""
if not self.is_player_colliding_with_obstacle(x, y, player_idx):
return x, y
directions = []
pref_len = np.hypot(push_x, push_y)
if pref_len > 1e-6:
directions.append((push_x / pref_len, push_y / pref_len))
directions.extend([
(1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0),
(0.707, 0.707), (0.707, -0.707), (-0.707, 0.707), (-0.707, -0.707)
])
for distance in range(1, self.GRID_SIZE + 6):
for dx, dy in directions:
test_x = x + dx * distance
test_y = y + dy * distance
if not self.is_player_colliding_with_obstacle(test_x, test_y, player_idx):
return test_x, test_y
return x, y
def _distance_point_to_player_hitbox(self, px, py, player_idx):
"""Distance from point to nearest point on player's rectangle hitbox."""
cx = self.world_data[player_idx, 1]
cy = self.world_data[player_idx, 2]
half_h = self._get_player_half_h(player_idx)
left = cx - self.PLAYER_HALF_W
right = cx + self.PLAYER_HALF_W
top = cy - half_h
bottom = cy + half_h
nearest_x = max(left, min(px, right))
nearest_y = max(top, min(py, bottom))
return float(np.hypot(px - nearest_x, py - nearest_y))
def _point_hits_player_hitbox(self, px, py, player_idx, padding=0.0):
cx = self.world_data[player_idx, 1]
cy = self.world_data[player_idx, 2]
half_h = self._get_player_half_h(player_idx)
return (
(cx - self.PLAYER_HALF_W - padding) <= px <= (cx + self.PLAYER_HALF_W + padding)
and (cy - half_h - padding) <= py <= (cy + half_h + padding)
)
def _segment_hits_player_hitbox(self, x0, y0, x1, y1, player_idx, padding=0.0, max_step=2.0):
"""Swept segment hit test against player rectangle to prevent bullet tunneling."""
cx = self.world_data[player_idx, 1]
cy = self.world_data[player_idx, 2]
half_h = self._get_player_half_h(player_idx)
left = cx - self.PLAYER_HALF_W - padding
right = cx + self.PLAYER_HALF_W + padding
top = cy - half_h - padding
bottom = cy + half_h + padding
seg_min_x = min(x0, x1)
seg_max_x = max(x0, x1)
seg_min_y = min(y0, y1)
seg_max_y = max(y0, y1)
if seg_max_x < left or seg_min_x > right or seg_max_y < top or seg_min_y > bottom:
return False
dx = x1 - x0
dy = y1 - y0
length = float(np.hypot(dx, dy))
if length <= 1e-8:
return self._point_hits_player_hitbox(x0, y0, player_idx, padding=padding)
steps = max(1, int(np.ceil(length / max_step)))
for i in range(steps + 1):
t = i / steps
px = x0 + dx * t
py = y0 + dy * t
if left <= px <= right and top <= py <= bottom:
return True
return False
def _push_out_of_obstacle(self, x, y, radius, push_x=0.0, push_y=0.0):
"""Try to move a grenade out of solid geometry using small radial offsets."""
if not self.is_colliding_with_obstacle(x, y, radius):
return x, y
directions = []
pref_len = np.hypot(push_x, push_y)
if pref_len > 1e-6:
directions.append((push_x / pref_len, push_y / pref_len))
directions.extend([
(1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0),
(0.707, 0.707), (0.707, -0.707), (-0.707, 0.707), (-0.707, -0.707)
])
for distance in range(1, self.GRID_SIZE + 3):
for dx, dy in directions:
test_x = x + dx * distance
test_y = y + dy * distance
if not self.is_colliding_with_obstacle(test_x, test_y, radius):
return test_x, test_y
return x, y
def _update_bouncy_grenade(self, grenade_slot, radius=4.0):
"""Stepwise movement with bounce, rolling friction, and anti-stuck resolution."""
x = self.world_data[grenade_slot, 1]
y = self.world_data[grenade_slot, 2]
vx = self.world_data[grenade_slot, 4]
vy = self.world_data[grenade_slot, 5] + self.GRAVITY
wall_bounce = 0.10
floor_bounce = 0.10
roll_friction = 0.95
speed = max(abs(vx), abs(vy), 1.0)
steps = min(8, max(1, int(np.ceil(speed / 4.0))))
dx = vx / steps
dy = vy / steps
hit_horizontal = False
hit_vertical = False
for _ in range(steps):
next_x = x + dx
if self.is_colliding_with_obstacle(next_x, y, radius):
hit_horizontal = True
vx = -vx * wall_bounce
dx = vx / steps
x, y = self._push_out_of_obstacle(x, y, radius, push_x=np.sign(vx), push_y=0.0)
else:
x = next_x
next_y = y + dy
if self.is_colliding_with_obstacle(x, next_y, radius):
hit_vertical = True
falling = vy > 0.0
vy = -vy * (floor_bounce if falling else wall_bounce)
if falling:
vx *= roll_friction
dy = vy / steps
x, y = self._push_out_of_obstacle(x, y, radius, push_x=0.0, push_y=-np.sign(vy if vy != 0 else 1.0))
else:
y = next_y
on_ground = self.is_colliding_with_obstacle(x, y + 1.5, radius)
if on_ground:
vx *= 0.97
if abs(vx) < 0.08:
vx = 0.0
if abs(vy) < 0.35:
vy = 0.0
if not hasattr(self, 'grenade_stuck_frames'):
self.grenade_stuck_frames = {}
if (hit_horizontal or hit_vertical) and abs(vx) < 0.12 and abs(vy) < 0.12 and self.is_colliding_with_obstacle(x, y, radius):
self.grenade_stuck_frames[grenade_slot] = self.grenade_stuck_frames.get(grenade_slot, 0) + 1
else:
self.grenade_stuck_frames[grenade_slot] = 0
if self.grenade_stuck_frames.get(grenade_slot, 0) > 3:
# Nudge upward and sideways so grenades never stay embedded in corners.
nudge = -1.0 if (grenade_slot % 2 == 0) else 1.0
x, y = self._push_out_of_obstacle(x + nudge * 1.5, y - 2.0, radius, push_x=nudge, push_y=-1.0)
vx = nudge * max(0.8, abs(vx) + 0.5)
vy = -1.6
self.grenade_stuck_frames[grenade_slot] = 0
self.world_data[grenade_slot, 1] = x
self.world_data[grenade_slot, 2] = y
self.world_data[grenade_slot, 4] = vx
self.world_data[grenade_slot, 5] = vy
def _update_non_bouncy_grenade(self, grenade_slot, radius=4.0):
"""Stepwise movement without bounce; grenade stops on first collision."""
x = self.world_data[grenade_slot, 1]
y = self.world_data[grenade_slot, 2]
vx = self.world_data[grenade_slot, 4]
vy = self.world_data[grenade_slot, 5]
steps = max(1, int(np.ceil(max(abs(vx), abs(vy), 1.0))))
dx = vx / steps
dy = vy / steps
for _ in range(steps):
next_x = x + dx
next_y = y + dy
if self.is_colliding_with_obstacle(next_x, next_y, radius):
# Keep grenade just outside geometry and fully stop it.
x, y = self._push_out_of_obstacle(x, y, radius, push_x=-np.sign(dx), push_y=-np.sign(dy if dy != 0 else 1.0))
vx = 0.0
vy = 0.0
break
x = next_x
y = next_y
x = float(np.clip(x, radius, self.SCREEN_W - radius))
y = float(np.clip(y, radius, self.SCREEN_H - radius))
self.world_data[grenade_slot, 1] = x
self.world_data[grenade_slot, 2] = y
self.world_data[grenade_slot, 4] = vx
self.world_data[grenade_slot, 5] = vy
def find_ground_below(self, x, y, player_idx=None):
"""Find standable center-y below a player rectangle centered at (x, y)."""
half_h = self._get_player_half_h(player_idx)
left_x = x - self.PLAYER_HALF_W
right_x = x + self.PLAYER_HALF_W
min_grid_x = max(0, int(np.floor(left_x / self.GRID_SIZE)))
max_grid_x = min(self.GRID_W - 1, int(np.floor(right_x / self.GRID_SIZE)))
if min_grid_x > max_grid_x:
return None
feet_y = y + half_h
start_grid_y = int(np.floor(feet_y / self.GRID_SIZE))
if start_grid_y < 0:
start_grid_y = -1
for gy in range(start_grid_y + 1, self.GRID_H):
if np.any(self.collision_map[gy, min_grid_x:max_grid_x + 1] == 0):
return gy * self.GRID_SIZE - half_h
return None
def _get_barrel_distance(self, weapon_id):
"""Get distance from player center to gun barrel tip for bullet spawning"""
barrel_distances = {
1: 35, 2: 35, 6: 36, # Pistols
7: 34, 8: 33, 9: 34, # SMGs
0: 38, 4: 39, 12: 38, 13: 39, # Assault Rifles
3: 42, 5: 45, # Snipers
10: 37, 11: 41, 14: 40, # Special weapons
}
return barrel_distances.get(weapon_id, 37)
def _get_bullet_spawn_offset(self, weapon_id):
"""Get x,y offset adjustments for bullet spawn (in pixels)"""
offsets = {
8: (6, 4), # UZI: 6px forward, 4px perpendicular down
}
return offsets.get(weapon_id, (0, 0))
def get_extended_game_state(self):
"""Package world_data, gun spawns, medkit spawns, player inventories, gas effects, and grenade data for client"""
# Gun spawn data: [[x, y, weapon_id, is_active], ...]
spawn_data = self.gun_spawner.get_spawn_data_for_client()
# Medkit spawn data: [[x, y, is_active], ...]
medkit_data = self.medkit_spawner.get_spawn_data_for_client()
# Player inventory data: [[gun1_id, gun2_id, current_slot], ...] for 8 players
inventory_data = np.zeros((8, 3), dtype=np.int32)
for i in range(8):
gun_ids = self.player_inventories[i].get_gun_ids()
inventory_data[i, 0] = gun_ids[0]
inventory_data[i, 1] = gun_ids[1]
inventory_data[i, 2] = self.player_inventories[i].current_slot
# Update ammo in world_data for current gun
current_gun = self.player_inventories[i].get_current_gun()
if current_gun is not None:
self.world_data[i, 9] = current_gun.current_ammo
self.world_data[i, 10] = current_gun.total_ammo
else:
self.world_data[i, 9] = 0
self.world_data[i, 10] = 0
# Gas effects data: [[x, y, radius, duration], ...] for all active gas zones
gas_data = np.array([
[effect['x'], effect['y'], effect['radius'], effect['duration']]
for effect in self.gas_effects.values()
], dtype=np.float64) if self.gas_effects else np.zeros((0, 4), dtype=np.float64)
# Grenade data per player: [selected_type, frag_count, proxy_count, gas_count]
grenade_data = self.grenade_data[:8].copy()
return self.world_data, spawn_data, medkit_data, inventory_data, gas_data, grenade_data
def _update_player_kneel_states(self):
"""Apply kneel input and resize active player hitboxes by 10px in height."""
for i in range(8):
if self.world_data[i, 0] == 0:
self.player_is_kneeling[i] = False
self.player_half_h[i] = self.PLAYER_HALF_H
continue
wants_kneel = self.player_inputs[i, 13] == 1
if wants_kneel == self.player_is_kneeling[i]:
continue
x = self.world_data[i, 1]
y = self.world_data[i, 2]
old_half_h = self.player_half_h[i]
new_half_h = self._get_target_half_h(wants_kneel)
# Keep feet level when toggling stance by adjusting center y.
feet_y = y + old_half_h
new_y = feet_y - new_half_h
if self.is_rect_colliding_with_obstacle(x, new_y, self.PLAYER_HALF_W, new_half_h):
# Prevent standing up inside a ceiling.
if not wants_kneel:
continue
new_y = y
self.player_is_kneeling[i] = wants_kneel
self.player_half_h[i] = new_half_h
self.world_data[i, 2] = new_y
def run_game(self):
MAX_BULLET_DIST = config.MAX_BULLET_DISTANCE
SAW_WEAPON_ID = config.SAW_WEAPON_ID
SAW_FIRE_DELAY = getattr(config, 'SAW_FIRE_DELAY', 2.0)
SAW_LIFETIME = config.SAW_LIFETIME
SAW_EXPLOSION_RADIUS = config.SAW_EXPLOSION_RADIUS
SAW_EXPLOSION_DAMAGE = config.SAW_EXPLOSION_DAMAGE
if not hasattr(self, 'saw_bullet_timers'):
self.saw_bullet_timers = {}
clock = pygame.time.Clock()
while True:
clock.tick(config.SERVER_FPS)
# Calculate delta_time for cooldowns
current_time = time.time()
delta_time = current_time - self.last_frame_time
self.last_frame_time = current_time
# Match timer
if self.match_start_time is None:
# Timer hasn't started yet - skip timer logic
self.time_remaining = self.match_duration
else:
elapsed = current_time - self.match_start_time
self.time_remaining = max(0.0, self.match_duration - elapsed)
if self.time_remaining <= 0:
self.time_remaining = 0
if not self.match_ended:
leaderboard_data = self._build_leaderboard_array()
print("[SERVER] Match ended")
print("Leaderboard:", leaderboard_data)
self.match_ended = True
# freeze gameplay
continue
# Decrement grenade cooldowns
self.player_grenade_cooldown = np.maximum(0, self.player_grenade_cooldown - delta_time)
# Update fire cooldowns
self.player_fire_cooldown = np.maximum(0, self.player_fire_cooldown - delta_time)
# Update respawn cooldowns and respawn players when ready
for idx in range(8):
if self.player_respawn_cooldown[idx] > 0:
self.player_respawn_cooldown[idx] -= delta_time
if self.player_respawn_cooldown[idx] <= 0:
self.player_respawn_cooldown[idx] = 0
self.respawn(idx, delay=0) # instant respawn after timer expires
self._apply_health_regeneration(delta_time)
self._update_player_kneel_states()
# Tank movement: left/right using A/D keys (index 1=A, 2=D).
# Kneeling reduces movement speed.
movement_speed = self.world_data[:8, 4].copy()
movement_speed[self.player_is_kneeling] *= self.KNEEL_SPEED_MULTIPLIER
horizontal_move = (self.player_inputs[:, 2] - self.player_inputs[:, 1]) * movement_speed
# --- Grenade physics and fuse update ---
if not hasattr(self, 'grenade_fuse_timers'):
self.grenade_fuse_timers = {}
for g in range(48, 55):
if self.world_data[g, 0] == 1:
grenade_type = int(self.world_data[g, 10])
blast_radius = self.world_data[g, 6]
damage = self.world_data[g, 7]
if grenade_type == 2:
self._update_non_bouncy_grenade(g, radius=4.0)
else:
self._update_bouncy_grenade(g, radius=4.0)
gx, gy = self.world_data[g, 1], self.world_data[g, 2]
if grenade_type == 1: # normal timed grenade with bounce physics
if g in self.grenade_fuse_timers:
self.grenade_fuse_timers[g] -= 1.0 / config.SERVER_FPS
if g in self.grenade_fuse_timers and self.grenade_fuse_timers[g] <= 0:
# explode
owner = int(self.world_data[g, 9])
for t in range(8):
if self.world_data[t, 0] == 1:
distance = self._distance_point_to_player_hitbox(gx, gy, t)
if distance < blast_radius:
dealt = self.grenade_damage(distance, max_damage=damage, radius=blast_radius)
self._apply_damage_to_player(t, dealt, killer_idx=owner)
self.world_data[g, 0] = 0
del self.grenade_fuse_timers[g]
if hasattr(self, 'grenade_stuck_frames'):
self.grenade_stuck_frames.pop(g, None)
elif grenade_type == 2: # proxy grenade – arms after delay then explodes on contact
# decrement whichever timer is active (arming or lifetime)
if g in self.grenade_fuse_timers:
self.grenade_fuse_timers[g] -= 1.0 / config.SERVER_FPS
# ensure armed-state tracking exists
if not hasattr(self, 'proxy_armed'):
self.proxy_armed = set()
if g in self.proxy_armed:
# already armed – timer now represents remaining life
if self.grenade_fuse_timers.get(g, 0) <= 0:
# lifetime expired without contact, just remove
self.world_data[g, 0] = 0
self.proxy_armed.discard(g)
self.grenade_fuse_timers.pop(g, None)
if hasattr(self, 'grenade_stuck_frames'):
self.grenade_stuck_frames.pop(g, None)
else:
# check for player contact and detonate if seen
detonated = False
for t in range(8):
if self.world_data[t, 0] == 1:
if self._distance_point_to_player_hitbox(gx, gy, t) < blast_radius / 3.0:
detonated = True
break
if detonated:
owner = int(self.world_data[g, 9])
for t in range(8):
if self.world_data[t, 0] == 1:
distance = self._distance_point_to_player_hitbox(gx, gy, t)
if distance < blast_radius:
dealt = self.grenade_damage(distance, max_damage=damage, radius=blast_radius)
self._apply_damage_to_player(t, dealt, killer_idx=owner)
self.world_data[g, 0] = 0
self.proxy_armed.discard(g)
self.grenade_fuse_timers.pop(g, None)
if hasattr(self, 'grenade_stuck_frames'):
self.grenade_stuck_frames.pop(g, None)
else:
# still in arming phase
if g in self.grenade_fuse_timers and self.grenade_fuse_timers[g] <= 0:
# move into armed state with 45‑second lifetime
self.proxy_armed.add(g)
self.grenade_fuse_timers[g] = 45.0
elif grenade_type == 3: # gas grenade - creates persistent damage zone
if g in self.grenade_fuse_timers:
self.grenade_fuse_timers[g] -= 1.0 / config.SERVER_FPS
if self.grenade_fuse_timers[g] <= 0:
# Create persistent gas effect zone
effect_id = self.gas_effect_counter
self.gas_effect_counter += 1
self.gas_effects[effect_id] = {
'x': gx,
'y': gy,
'radius': blast_radius,
'damage': damage,
'duration': 12.0,
'owner_id': int(self.world_data[g, 9]),
'source_slot': g
}
print(f"[SERVER] Gas effect created at ({gx:.1f}, {gy:.1f}) with radius {blast_radius}, damage {damage}/frame")
self.world_data[g, 0] = 0
del self.grenade_fuse_timers[g]
if hasattr(self, 'grenade_stuck_frames'):
self.grenade_stuck_frames.pop(g, None)
# --- Process active gas effects ---
effects_to_remove = []
for effect_id, effect in self.gas_effects.items():
# Decrement gas duration
effect['duration'] -= 1.0 / config.SERVER_FPS
# Apply damage to players in the gas zone
for t in range(8):
if self.world_data[t, 0] == 1:
distance = self._distance_point_to_player_hitbox(effect['x'], effect['y'], t)
if distance < effect['radius']:
dealt = (effect['damage'] / max(distance, 1.0))
killer = int(effect.get('owner_id', -1))
if self._apply_damage_to_player(t, dealt, killer_idx=killer):
print(f"[SERVER] Player {t} killed by gas grenade")
# Remove effect if duration expired
if effect['duration'] <= 0:
effects_to_remove.append(effect_id)
# Clean up expired gas effects
for effect_id in effects_to_remove:
del self.gas_effects[effect_id]
# Check horizontal collisions before moving - allow movement away from obstacles
for i in range(8):
if self.world_data[i, 0] == 0:
continue
old_x = self.world_data[i, 1]
new_x = old_x + horizontal_move[i]
# Check if currently colliding
currently_colliding = self.is_player_colliding_with_obstacle(old_x, self.world_data[i, 2], i)
will_collide = self.is_player_colliding_with_obstacle(new_x, self.world_data[i, 2], i)
# Only accept horizontal movement when destination is non-colliding.
if not will_collide:
self.world_data[i, 1] = new_x
# Aim control using all 4 arrow keys for continuous rotation
# UP=3, DOWN=4, LEFT=5, RIGHT=6
AIM_ROTATION_SPEED = config.AIM_ROTATION_SPEED
# Handle gun switching (S key = input[9]) - only on key press (rising edge)
for i in range(8):
if self.world_data[i, 0] == 0:
continue
# Only switch if S key is pressed now but wasn't pressed last frame
if self.player_inputs[i, 9] == 1 and self.previous_inputs[i, 9] == 0:
self.player_inventories[i].switch_gun()
# Handle reload (R key = input[8])
for i in range(8):
if self.world_data[i, 0] == 0:
continue
if self.player_inputs[i, 8] == 1: # R key pressed
weapon = self.player_inventories[i].get_current_gun()
if weapon is None:
continue
# Only start reload if not already reloading and if reload is needed
if self.player_reload_cooldown[i] <= 0 and weapon.current_ammo < weapon.magazine_capacity and weapon.total_ammo > 0:
self.player_reload_cooldown[i] = weapon.reload_time
for i in range(8):
if self.world_data[i, 0] == 0:
continue
# Continuous rotation based on arrow keys
if self.player_inputs[i, 5] == 1: # LEFT arrow
self.world_data[i, 3] -= AIM_ROTATION_SPEED
if self.player_inputs[i, 6] == 1: # RIGHT arrow
self.world_data[i, 3] += AIM_ROTATION_SPEED
if self.player_inputs[i, 3] == 1: # UP arrow
self.world_data[i, 3] -= AIM_ROTATION_SPEED
if self.player_inputs[i, 4] == 1: # DOWN arrow
self.world_data[i, 3] += AIM_ROTATION_SPEED
# Jetpack system (W key = keyboard_input[0])
jetpack_active = self.player_inputs[:, 0].astype(bool)
for i in range(8):
if self.world_data[i, 0] == 0: # skip inactive players
continue
if self.player_is_kneeling[i]:
# While kneeling, disable flying. Only allow a small jump on W press.
if jetpack_active[i] and self.previous_inputs[i, 0] == 0:
ground_y = self.find_ground_below(self.world_data[i, 1], self.world_data[i, 2], i)
on_ground = (
ground_y is not None
and abs(self.world_data[i, 2] - ground_y) <= self.KNEEL_GROUND_TOLERANCE
and self.player_vy[i] >= 0
)
if on_ground:
self.player_vy[i] = -self.KNEEL_JUMP_IMPULSE
# Recharge fuel while kneeling.
self.player_fuel[i] = min(self.MAX_FUEL, self.player_fuel[i] + self.FUEL_RECHARGE)
elif jetpack_active[i] and self.player_fuel[i] > 0:
# Apply upward thrust
self.player_vy[i] -= self.JETPACK_THRUST
# Consume fuel
self.player_fuel[i] = max(0, self.player_fuel[i] - self.FUEL_CONSUMPTION)
else:
# Recharge fuel when not using jetpack