-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
369 lines (301 loc) · 14.9 KB
/
client.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
361
362
363
364
365
366
367
368
369
import pygame
import socket
import json
from threading import Thread
import collections
import time
from src import megalib
global width
global height
global screen
global player_image
global camera_x
global camera_y
global offset
global player_dead_image
class ClientSocket:
def __init__(self, host=None, port=None):
self.host = host
self.port = port
self.send_socket = None
# self.recv_socket = None
def connect(self, host=None, port=None, name="jbrock", game_state: dict = None):
self.send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if host:
self.host = host
if port:
self.port = port
host_name = socket.gethostname()
ip_address = socket.gethostbyname(host_name)
self.send_socket.bind((ip_address, 0))
return self.connect_ack(name, game_state=game_state)
def connect_ack(self, name, game_state: dict):
msg = json.dumps({"method": "connect", "args": {"username": name, "recv_port": self.send_socket.getsockname()[1], "address": socket.gethostname()}})
msg = f"{len(msg.encode()):>16}{msg}"
self.send_socket.sendto(msg.encode(), (self.host, int(self.port)))
data, addr = self.send_socket.recvfrom(65536)
data = data[16:]
data = json.loads(data.decode())
if data["status"] == "reject":
return False
game_state = {'me': "", 'tanks': collections.defaultdict(lambda: None), 'players': collections.defaultdict(lambda: None)}
for user in data['players']:
if user == name:
try:
game_state['me'] = megalib.Player(name=name, x=data['players'][user]['x'], y=data['players'][user]['y'])
game_state['me'].O2_level = data['players'][user]['O2']
game_state['me'].dead = data['players'][user]['dead']
except:
game_state['me'] = megalib.Player(name=name, x=data['players'][user]['x'], y=data['players'][user]['y'])
else:
game_state['players'][user] = (megalib.Player(name=user, x = data['players'][user]['x'], y = data['players'][user]['y']))
game_state['players'][user].dead = data['players'][user]['dead']
for tank in data['tanks']:
game_state['tanks'][tank] = megalib.O2Tank(x=data['tanks'][tank]['x'], y=data['tanks'][tank]['y']);
return game_state
def recv_mesg(self, game_state: dict):
while True:
data, addr = self.send_socket.recvfrom(65536)
data = json.loads(data.decode())
if data['players']:
for player, info in data['players'].items():
try:
if info['status'] == "offline":
if player != game_state['me'].name:
game_state['players'].pop(player)
except KeyError:
pass
try:
if player == game_state['me'].name:
game_state['me'].x, game_state['me'].y, game_state['me'].O2_level, game_state['me'].dead, game_state['me'].death_counter = info['x'], info['y'], info['O2'], info['dead'], info['score']
else:
if not game_state['players'][player]:
game_state['players'][player] = megalib.Player(name=player, x=info['x'], y=info['x'])
else:
game_state['players'][player].x, game_state['players'][player].y, game_state['players'][player].dead = info['x'], info['y'], info['dead']
except KeyError:
pass
if data['tanks']:
game_state['tanks'] = {}
for tank in data['tanks']:
game_state['tanks'][tank] = megalib.O2Tank(x=data['tanks'][tank]['x'], y=data['tanks'][tank]['y']);
time.sleep(0.00833)
return
def send_data(self, move, game_state):
if move == "respawn":
msg = json.dumps({"method": "respawn", "args": {"username": game_state['me'].name, "x": game_state['me'].x, "y": game_state['me'].y}})
msg = f"{len(msg.encode()):>16}{msg}"
self.send_socket.sendto(msg.encode(), (self.host, int(self.port)))
return None
name = game_state['me'].name
if(move == "up"):
game_state['me'].move_up()
elif(move == "down"):
game_state['me'].move_down()
elif(move == "left"):
game_state['me'].move_left()
elif(move == "right"):
game_state['me'].move_right()
msg = json.dumps({"method": "send_player_update", "args": {"username": name, "x": game_state['me'].x, "y": game_state['me'].y}})
msg = f"{len(msg.encode()):>16}{msg}"
self.send_socket.sendto(msg.encode(), (self.host, int(self.port)))
return None
def disconnect(self, game_state):
msg = json.dumps({"method": "disconnect", "args": {"username": game_state['me'].name}})
msg = f"{len(msg.encode()):>16}{msg}"
self.send_socket.sendto(msg.encode(), (self.host, int(self.port)))
game_state['disconnect'] = True
def render_map(game_state: dict):
screen.blit(game_state['background'], (camera_x - width/2 - offset , camera_y - height/2 - offset))
return
def display_characters(game_state: dict):
smallfont = pygame.font.SysFont('Corbel',35)
game_state['me']: megalib.Player
for tank in game_state['tanks']:
screen.blit(tank_image, (game_state['tanks'][tank].x + camera_x, game_state['tanks'][tank].y+camera_y))
### ME
if game_state['me'].dead:
screen.blit(game_state['wasted'], (width/9, height/7))
mouse = pygame.mouse.get_pos()
screen.blit(smallfont.render('respawn' , True , (255,255,255) ) , (width/2-70, 5*height/7))
if width/2 <= mouse[0] <= width/2+140 and 5*height/7 <= mouse[1] <= 5*height/7+100:
pygame.draw.rect(screen,(170,170,170) ,[width/2-70,5*height/7,140,100])
else:
pygame.draw.rect(screen,(100,100,100) ,[width/2-70,5*height/7,140,100])
screen.blit(smallfont.render('respawn' , True , (255,255,255) ) , (width/2-40, 5*height/7))
else:
screen.blit(player_image, (game_state['me'].x + camera_x, game_state['me'].y + camera_y))
screen.blit(smallfont.render(game_state['me'].name, True, (100,100,100)), (game_state['me'].x + camera_x + 25, game_state['me'].y + camera_y - 10))
pygame.draw.rect(screen, (50,205,50), (game_state['me'].x + camera_x, game_state['me'].y + camera_y - 25, game_state['me'].O2_level, 5))
for player in game_state['players']:
if not game_state['players'][player]:
continue
screen.blit(smallfont.render(game_state['players'][player].name, True, (100,100,100)), (game_state['players'][player].x + camera_x + 25, game_state['players'][player].y + camera_y - 10))
if game_state['players'][player].dead:
screen.blit(player_dead_image, (game_state['players'][player].x + camera_x, game_state['players'][player].y + camera_y))
else:
screen.blit(player_image, (game_state['players'][player].x + camera_x, game_state['players'][player].y + camera_y))
#for tank in game_state['tanks']:
return
def get_host_and_client():
color = (255,255,255)
color_light = (170,170,170)
color_dark = (100,100,100)
smallfont = pygame.font.SysFont('Corbel',35)
text_connected = smallfont.render('connected' , True , color)
text_not_connected = smallfont.render('not connected' , True , color)
client = ClientSocket()
server = ""
port = ""
name = ""
connected = False
option = 1
while True:
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
if ev.type == pygame.MOUSEBUTTONDOWN:
if not connected:
if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
game_state = client.connect(server, port, name=name, game_state={})
if not game_state:
continue
connected = True
me = game_state['me']
if ev.type == pygame.KEYDOWN:
key_pressed = pygame.key.get_pressed()
if ev.key == pygame.K_BACKSPACE:
if option == 1:
server = server[:-1]
elif option == 2:
port = port[:-1]
elif option == 3:
name = name[:-1]
elif key_pressed[pygame.K_UP]:
option -= 1
elif key_pressed[pygame.K_DOWN]:
option += 1
else:
if option > 3:
option = 3
if option < 1:
option = 1
if option == 1:
server += ev.unicode
elif option == 2:
port += ev.unicode
elif option == 3:
name += ev.unicode
# fills the screen with a color
screen.fill((60,25,60))
# stores the (x,y) coordinates into
# the variable as a tuple
mouse = pygame.mouse.get_pos()
# if mouse is hovered on a button it
# changes to lighter shade
if not connected:
if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
pygame.draw.rect(screen,color_light,[width/2-50,height/2,140,40])
else:
pygame.draw.rect(screen,color_dark,[width/2-50,height/2,140,40])
# superimposing the text onto our button
if not connected:
screen.blit(text_not_connected , (width/2-50,height/2))
else:
screen.blit(text_connected , (width/2-50,height/2))
screen.blit(smallfont.render(server, True, color), (width/2-50, 1*height/10))
screen.blit(smallfont.render(port, True, color), (width/2-50, 2*height/10))
screen.blit(smallfont.render(name, True, color), (width/2-50, 3*height/10))
screen.blit(smallfont.render("1 server", True, color), (width/2-200, height/10))
screen.blit(smallfont.render("2 port", True, color), (width/2-200, 2*height/10))
screen.blit(smallfont.render("3 name", True, color), (width/2-200, 3*height/10))
pygame.display.update()
if connected:
break
in_game_loop(client, me, game_state=game_state)
def in_game_loop(client: ClientSocket, me: megalib.Player, game_state: dict):
global player_image
global tank_image
global camera_x
global camera_y
global offset
global player_dead_image
game_state['background'] = pygame.image.load("./src/among-us-map.jpg").convert_alpha()
game_state['background'] = pygame.transform.rotozoom(game_state['background'], 0, 3.5)
game_state['wasted'] = pygame.image.load("./src/wasted.png").convert_alpha()
game_state['wasted'] = pygame.transform.rotozoom(game_state['wasted'], 0, 1)
game_state['disconnect'] = False
clock = pygame.time.Clock()
player_image = pygame.image.load("./src/among_us.png").convert_alpha()
player_image.set_colorkey((0, 0, 0))
# player_image = player_image.get_rect()
player_image = pygame.transform.rotozoom(player_image, 0, 1/5)
player_dead_image = pygame.transform.rotozoom(player_image, 90, 1)
tank_image = pygame.image.load("./src/oxygen.webp");
tank_image = pygame.transform.rotozoom(tank_image, 0, 1/5);
mov_types = {"up": False, "down": False, "left": False, "right": False}
t = Thread(target=client.recv_mesg, daemon=True, args=[game_state])
t.start()
offset = - 50
camera_x = width / 2 + offset
camera_y = height / 2 + offset
while True:
screen.fill((255,255,255))
render_map(game_state)
if game_state['disconnect']:
pygame.quit()
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
client.disconnect(game_state)
if not game_state['me'].dead:
if ev.type == pygame.KEYDOWN:
if ev.unicode == "w":
mov_types['down'] = True
elif ev.unicode == "a":
mov_types['left'] = True
elif ev.unicode == "s":
mov_types['up'] = True
elif ev.unicode == "d":
mov_types['right'] = True
if ev.type == pygame.KEYUP:
if ev.unicode == "w":
mov_types['down'] = False
elif ev.unicode == "a":
mov_types['left'] = False
elif ev.unicode == "s":
mov_types['up'] = False
elif ev.unicode == "d":
mov_types['right'] = False
else:
for mov in mov_types:
mov_types[mov] = False
mouse = pygame.mouse.get_pos()
if ev.type == pygame.MOUSEBUTTONDOWN:
if width/2 <= mouse[0] <= width/2+140 and 5*height/7 <= mouse[1] <= 5*height/7+100:
client.send_data("respawn", game_state)
for mov in mov_types:
if mov_types[mov]:
client.send_data(mov, game_state)
if (game_state['me'].x + camera_x) > width/2 + 30:
camera_x -= (game_state['me'].x + camera_x) - (width/2 + 30)
if (game_state['me'].x + camera_x) < width/2 - 100:
camera_x += -(game_state['me'].x + camera_x) + (width/2 - 100)
if (game_state['me'].y + camera_y) > height/2 + 30:
camera_y -= (game_state['me'].y + camera_y) - (height/2 + 30)
if (game_state['me'].y + camera_y) < height/2 - 100:
camera_y += -(game_state['me'].y + camera_y) + (height/2 - 100)
display_characters(game_state=game_state)
clock.tick(60)
pygame.display.update()
def main():
pygame.init()
res = (1000, 720)
global width
global height
global screen
screen = pygame.display.set_mode(res)
width = screen.get_width()
height = screen.get_height()
get_host_and_client()
if __name__ == "__main__":
main()