-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
380 lines (335 loc) · 14.4 KB
/
client.py
File metadata and controls
380 lines (335 loc) · 14.4 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
import pygame
import random
import socket
import pickle
import math
# Constants
WIDTH, HEIGHT = 800, 600
CENTER = pygame.Vector2(WIDTH // 2, HEIGHT // 2)
BULLET_RADIUS = 4
PLAYER_RADIUS = 20
HIT_RADIUS = 30
class Wall:
__slots__ = ('rect', 'corners')
def __init__(self, x, y, w, h):
self.rect = pygame.Rect(x, y, w, h)
self.corners = [
pygame.Vector2(x, y),
pygame.Vector2(x + w, y),
pygame.Vector2(x + w, y + h),
pygame.Vector2(x, y + h)
]
def draw(self, screen, p_pos, p_angle, center_point):
projected = []
cos_a = math.cos(math.radians(p_angle))
sin_a = math.sin(math.radians(p_angle))
for corner in self.corners:
rel = corner - p_pos
rx = rel.x * cos_a + rel.y * sin_a
ry = -rel.x * sin_a + rel.y * cos_a
projected.append(center_point + pygame.Vector2(rx, ry))
pygame.draw.polygon(screen, (70, 70, 80), projected)
pygame.draw.polygon(screen, (100, 100, 110), projected, 2)
class Bullet:
__slots__ = ('pos', 'vel', 'owner_id', 'alive', 'lifetime', 'id')
def __init__(self, pos, angle, owner_id, bullet_id):
self.pos = pygame.Vector2(pos)
self.vel = pygame.Vector2(0, -600).rotate(angle)
self.owner_id = owner_id
self.alive = True
self.lifetime = 2.0
self.id = bullet_id
def update(self, dt, walls):
self.pos += self.vel * dt
self.lifetime -= dt
if self.lifetime <= 0:
self.alive = False
return
# Line segment collision with walls
start = self.pos - self.vel * dt
for wall in walls:
if self._line_rect_collision(start, self.pos, wall.rect):
self.alive = False
break
def _line_rect_collision(self, p1, p2, rect):
if (min(p1.x, p2.x) > rect.right or
max(p1.x, p2.x) < rect.left or
min(p1.y, p2.y) > rect.bottom or
max(p1.y, p2.y) < rect.top):
return False
if rect.collidepoint(p1) or rect.collidepoint(p2):
return True
edges = [(rect.left, rect.top, rect.right, rect.top),
(rect.right, rect.top, rect.right, rect.bottom),
(rect.right, rect.bottom, rect.left, rect.bottom),
(rect.left, rect.bottom, rect.left, rect.top)]
for (x1, y1, x2, y2) in edges:
if self._segments_intersect(p1.x, p1.y, p2.x, p2.y, x1, y1, x2, y2):
return True
return False
@staticmethod
def _segments_intersect(x1, y1, x2, y2, x3, y3, x4, y4):
def cross(ax, ay, bx, by):
return ax * by - ay * bx
dx1 = x2 - x1
dy1 = y2 - y1
dx2 = x4 - x3
dy2 = y4 - y3
d = cross(dx1, dy1, dx2, dy2)
if d == 0:
return False
t = cross(x3 - x1, y3 - y1, dx2, dy2) / d
u = cross(x3 - x1, y3 - y1, dx1, dy1) / d
return 0 <= t <= 1 and 0 <= u <= 1
def draw(self, screen, p_pos, p_angle, center_point):
rel = (self.pos - p_pos).rotate(-p_angle)
draw_pos = center_point + rel
pygame.draw.circle(screen, (255, 255, 0), (int(draw_pos.x), int(draw_pos.y)), BULLET_RADIUS)
class Player:
__slots__ = ('pos', 'angle', 'hp', 'speed', 'turn_speed', 'shoot_timer',
'shoot_delay', 'new_bullets', 'damage_flash', 'shake_offset')
def __init__(self):
self.pos = pygame.Vector2(0, 0)
self.angle = 0
self.hp = 100
self.speed = 300
self.turn_speed = 200
self.shoot_timer = 0
self.shoot_delay = 0.2
self.new_bullets = []
self.damage_flash = 0
self.shake_offset = pygame.Vector2(0, 0)
def respawn(self, walls):
self.hp = 100
while True:
rx = random.randint(-550, 550)
ry = random.randint(-550, 550)
test_pos = pygame.Vector2(rx, ry)
if not self._collides_with_wall(test_pos, walls):
self.pos = test_pos
break
def _collides_with_wall(self, pos, walls):
player_rect = pygame.Rect(pos.x - PLAYER_RADIUS, pos.y - PLAYER_RADIUS,
PLAYER_RADIUS * 2, PLAYER_RADIUS * 2)
for w in walls:
if player_rect.colliderect(w.rect):
return True
return False
def _resolve_wall_collision(self, pos, walls):
"""Adjust position to be outside walls."""
player_rect = pygame.Rect(pos.x - PLAYER_RADIUS, pos.y - PLAYER_RADIUS,
PLAYER_RADIUS * 2, PLAYER_RADIUS * 2)
for w in walls:
if player_rect.colliderect(w.rect):
# Determine the least displacement to separate
overlap_left = (pos.x - PLAYER_RADIUS) - w.rect.right
overlap_right = w.rect.left - (pos.x + PLAYER_RADIUS)
overlap_top = (pos.y - PLAYER_RADIUS) - w.rect.bottom
overlap_bottom = w.rect.top - (pos.y + PLAYER_RADIUS)
# Find the smallest absolute overlap (the direction to move)
overlaps = [overlap_left, overlap_right, overlap_top, overlap_bottom]
# Positive means we need to move in that direction
# For left/up, we have negative if inside, so we want the one with largest positive? Actually we want the minimum displacement
# Better: compute how much we need to move to get out
if overlap_left > 0:
pos.x = w.rect.right + PLAYER_RADIUS
elif overlap_right > 0:
pos.x = w.rect.left - PLAYER_RADIUS
elif overlap_top > 0:
pos.y = w.rect.bottom + PLAYER_RADIUS
elif overlap_bottom > 0:
pos.y = w.rect.top - PLAYER_RADIUS
else:
# Overlap from all sides, push away in the direction of least overlap
# Determine which side to push (the one with largest positive overlap)
pushes = {'left': overlap_left, 'right': overlap_right, 'top': overlap_top, 'bottom': overlap_bottom}
best = max(pushes, key=pushes.get)
if best == 'left':
pos.x = w.rect.right + PLAYER_RADIUS
elif best == 'right':
pos.x = w.rect.left - PLAYER_RADIUS
elif best == 'top':
pos.y = w.rect.bottom + PLAYER_RADIUS
elif best == 'bottom':
pos.y = w.rect.top - PLAYER_RADIUS
# Recreate rect after adjustment
player_rect = pygame.Rect(pos.x - PLAYER_RADIUS, pos.y - PLAYER_RADIUS,
PLAYER_RADIUS * 2, PLAYER_RADIUS * 2)
return pos
def update(self, dt, walls, other_players):
# Input
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.angle -= self.turn_speed * dt
if keys[pygame.K_RIGHT]:
self.angle += self.turn_speed * dt
self.angle %= 360
# Movement vector
forward = pygame.Vector2(0, -1).rotate(self.angle)
right = pygame.Vector2(1, 0).rotate(self.angle)
move = pygame.Vector2(0, 0)
if keys[pygame.K_w]:
move += forward
if keys[pygame.K_s]:
move -= forward
if keys[pygame.K_a]:
move -= right
if keys[pygame.K_d]:
move += right
if move.length() > 0:
move.normalize_ip()
velocity = move * self.speed * dt
# X axis movement
new_x = self.pos.x + velocity.x
new_pos_x = pygame.Vector2(new_x, self.pos.y)
if not self._collides_with_wall(new_pos_x, walls):
self.pos.x = new_x
else:
# Slide along wall (cancel x movement)
velocity.x = 0
# Y axis movement
new_y = self.pos.y + velocity.y
new_pos_y = pygame.Vector2(self.pos.x, new_y)
if not self._collides_with_wall(new_pos_y, walls):
self.pos.y = new_y
else:
velocity.y = 0
# Resolve player-player collisions
for p_id, p_info in other_players.items():
other_pos = p_info["pos"]
dist = (self.pos - other_pos).length()
if dist < PLAYER_RADIUS * 2:
# Separate
overlap = PLAYER_RADIUS * 2 - dist
direction = (self.pos - other_pos).normalize()
self.pos += direction * overlap
# Re-check walls after player separation (in case separation pushed into wall)
if self._collides_with_wall(self.pos, walls):
self.pos = self._resolve_wall_collision(self.pos, walls)
# Shooting
if self.shoot_timer > 0:
self.shoot_timer -= dt
if keys[pygame.K_SPACE] and self.shoot_timer <= 0:
forward = pygame.Vector2(0, -1).rotate(self.angle)
spawn_pos = self.pos + forward * 25
bullet_id = f"{id(self)}_{pygame.time.get_ticks()}_{random.random()}"
self.new_bullets.append({"pos": list(spawn_pos), "angle": self.angle, "id": bullet_id})
self.shoot_timer = self.shoot_delay
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
walls = [
Wall(-600, -600, 1200, 20), Wall(-600, 600, 1200, 20),
Wall(-600, -600, 20, 1200), Wall(600, -600, 20, 1200),
Wall(-50, -50, 100, 100),
Wall(-400, -400, 150, 40), Wall(300, -400, 40, 150),
Wall(-400, 300, 40, 150), Wall(300, 300, 150, 40)
]
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect(("localhost", 5555))
my_id = int(client.recv(1024).decode())
except:
print("Run server.py first!")
return
player = Player()
player.respawn(walls)
bullets = []
other_players = {}
known_bullet_ids = set()
running = True
while running:
dt = clock.tick(60) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# ---- SEND & RECEIVE ----
try:
network_bullets = player.new_bullets
for b_info in network_bullets:
if b_info["id"] not in known_bullet_ids:
new_b = Bullet(b_info["pos"], b_info["angle"], my_id, b_info["id"])
bullets.append(new_b)
known_bullet_ids.add(b_info["id"])
packet = {"pos": player.pos, "angle": player.angle, "bullets": network_bullets, "hp": player.hp}
client.send(pickle.dumps(packet))
player.new_bullets = []
other_players = pickle.loads(client.recv(16384))
except:
break
# ---- CREATE BULLETS FROM OTHER PLAYERS ----
for p_id, p_info in other_players.items():
for b_info in p_info.get("bullets", []):
b_id = b_info["id"]
if b_id not in known_bullet_ids:
new_b = Bullet(b_info["pos"], b_info["angle"], p_id, b_id)
bullets.append(new_b)
known_bullet_ids.add(b_id)
# ---- UPDATE LOCAL PLAYER ----
player.update(dt, walls, other_players)
# ---- UPDATE BULLETS AND HANDLE COLLISIONS ----
bullets_to_remove = []
for b in bullets:
b.update(dt, walls)
# Check bullet vs player collisions
hit = False
# Check local player
if b.owner_id != my_id:
if (b.pos - player.pos).length() < HIT_RADIUS:
player.hp -= 25
player.damage_flash = 0.2
player.shake_offset = pygame.Vector2(random.randint(-10, 10),
random.randint(-10, 10))
hit = True
# Check other players (for all bullets)
if not hit:
for p_id, p_info in other_players.items():
if b.owner_id == p_id:
continue # Don't hit yourself
if (b.pos - p_info["pos"]).length() < HIT_RADIUS:
hit = True
break
if hit:
b.alive = False
if not b.alive:
bullets_to_remove.append(b)
for b in bullets_to_remove:
bullets.remove(b)
# Trim known_bullet_ids
if len(known_bullet_ids) > 5000:
known_bullet_ids = set(list(known_bullet_ids)[-5000:])
if player.hp <= 0:
player.respawn(walls)
# ---- RENDER ----
screen.fill((30, 30, 30))
cur_center = CENTER + player.shake_offset
player.shake_offset *= 0.9
for w in walls:
w.draw(screen, player.pos, player.angle, cur_center)
for p_id, p_info in other_players.items():
rel = (p_info["pos"] - player.pos).rotate(-player.angle)
draw_p = cur_center + rel
aim = pygame.Vector2(0, -150).rotate(p_info["angle"] - player.angle)
pygame.draw.line(screen, (200, 0, 0), draw_p, draw_p + aim, 1)
pygame.draw.circle(screen, (200, 50, 50), (int(draw_p.x), int(draw_p.y)), PLAYER_RADIUS)
pygame.draw.rect(screen, (255, 0, 0), (draw_p.x - 20, draw_p.y - 35, 40, 5))
pygame.draw.rect(screen, (0, 255, 0), (draw_p.x - 20, draw_p.y - 35,
p_info["hp"] * 0.4, 5))
for b in bullets:
b.draw(screen, player.pos, player.angle, cur_center)
pygame.draw.circle(screen, (0, 200, 100), (int(cur_center.x), int(cur_center.y)), PLAYER_RADIUS)
pygame.draw.line(screen, (255, 255, 255), cur_center,
cur_center + pygame.Vector2(0, -30), 4)
if player.damage_flash > 0:
player.damage_flash -= dt
s = pygame.Surface((WIDTH, HEIGHT))
s.set_alpha(100)
s.fill((255, 0, 0))
screen.blit(s, (0, 0))
pygame.draw.rect(screen, (0, 255, 100), (WIDTH // 2 - 100, HEIGHT - 40,
player.hp * 2, 15))
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()