forked from huu-bo/micg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnet.py
459 lines (378 loc) · 13.6 KB
/
net.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
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
# net, short for networking
import socket
import threading
import pygame.constants
import math
import time
import block
class net:
def __init__(self, s: socket.socket):
self.messages = []
self.last = ''
self.s = s
def recv(self, data: bytes):
data = data.decode('utf-8')
if ';' not in data:
self.last += data
else:
split = data.split(';')
for i in range(len(split)):
if i == 0:
self.messages.append(self.last + split[i])
self.last = ''
elif i != len(split) - 1:
self.messages.append(split[i])
else:
self.last = split[i]
m = self.messages
self.messages = []
return m
def send(self, packet: str):
if ';' in packet[:-1]:
for p in packet.split(';'):
self.send(p + ';')
else:
if packet[-1] != ';':
packet += ';'
self.s.send(packet.encode('utf-8'))
# packets:
# first letter type, information/action
# second letter data
# IN:
# name
# IB:
# x y type
# IC: get chunk
# AK:
# wasd changed
# 0000 binary for wasd
# AP:
# x y type
# place block, also for deleting block since you're basically placing air
# AM:
# x y
# IM:
# x y name
# sent from server_client to client to let client know about other clients moving
# maybe this could be used as AM
# IQ: (not implemented yet)
# name
# let other clients know about other clients disconnecting
# AQ:
# quit
# EN:
# name contains space
class player:
def __init__(self):
self.x = 0
self.y = 0
self.xv = 0
self.yv = 0
self.queue = [] # placing/breaking blocks
self.key = [False, False, False, False] # up, left, down, right
self.name = None
def physics(self, world):
if self.key[3]:
self.xv += .1
if self.key[1]:
self.xv -= .1
self.yv += .1
self.y += self.yv
floor = False
while world.get(math.floor(self.x), math.ceil(self.y)).solid or\
world.get(math.ceil(self.x), math.ceil(self.y)).solid:
self.yv = 0
self.y -= .1
floor = True
if floor and self.key[0]:
self.yv = -.55
self.x += self.xv
self.xv /= 2
class server:
def __init__(self, world, ip='localhost'):
self.threads = []
self.run = True
self.world = world
self.players = []
self.pipes = []
self.ip = ip
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.settimeout(.5)
self.server.bind((ip, 60000))
self.server.listen()
self.accept_thread = threading.Thread(target=self._accept, name='accept')
self.accept_thread.start()
self.threads.append(self.accept_thread)
def _accept(self):
while self.run:
try:
c, address = self.server.accept()
print('accepted', c, address)
p = player()
self.players.append(p)
pi = pipe()
self.pipes.append(pi)
self.threads.append(threading.Thread(target=server_client, args=[c, self, p, pi]))
self.threads[-1].start()
except socket.timeout:
pass
def update(self, world):
for p in self.players:
p.physics(world)
def exit(self):
self.run = False
for t in self.threads:
print('joining', t)
t.join(1)
if t.is_alive():
print(t, 'is still alive')
def remove(self, s_c):
self.players.remove(s_c.player)
def send_all(self, data):
for p in self.pipes:
p.send(data)
def send_all_except(self, data, exception): # TODO: broken
for p in self.pipes:
if p != exception:
p.send(data)
class server_client:
def __init__(self, c: socket.socket, s: server, p: player, pi):
self.c = c
self.s = s
self.r = True # TODO: what is 'r'
self.name = 'NAME_NOT_SENT'
self.player = p
self.pipe = pi
self.net = net(c)
self.world = self.s.world
self.c.settimeout(.02)
self.run()
def packet_recv(self, packet: str):
# data = packet.decode('utf-8')
data = packet
print("client: '" + self.name + "' packet: '" + data + "'")
if data[0] == 'I':
if data[1] == 'N':
had_name = self.name != 'NAME_NOT_SENT'
if ' ' not in data[2:]:
self.name = data[2:]
else:
print('incorrect name', data[2:])
if self.r:
self.net.send('EN')
if not had_name:
# let all the other clients that are not this client know that this client exists
self.s.send_all_except('IN' + self.name, self.pipe)
print(self.name, 'joined')
elif data[1] == 'B':
split = data[2:].split(' ')
print('block info', split, 'deprecated')
if self.world is not None:
if len(split) == 2:
x = int(split[0])
y = int(split[1])
packet = 'IB' + str(x) + ' ' + str(y) + ' ' + self.world.get(x, y).name
self.net.send(packet)
print(packet)
else:
raise ValueError(data)
else:
raise ValueError('server_client.world is None')
elif data[1] == 'C':
split = data[2:].split(' ')
if len(split) == 2:
c = self.world.serialize_chunk(int(split[0]), int(split[1]))
# print('IC' + split[0] + ' ' + split[1] + ' ' + c[:50])
self.net.send('IC' + split[0] + ' ' + split[1] + ' ' + c)
else:
print('unknown info packet:', data)
elif data[0] == 'A':
if data[1] == 'K':
for i in range(4):
self.player.key[i] = data[i + 2] == '1'
elif data[1] == 'P':
split = data[2:].split(' ')
if len(split) != 3:
return
self.world.set(int(split[0]), int(split[1]), block.block(split[2], self.world.blocks))
self.s.send_all(data) # let all the other clients know,
# will cause the packet to be sent back to the client that sent it
elif data[1] == 'Q':
self.close()
else:
print('unknown action packet:', data)
else:
print('unknown packet type:', data)
def run(self):
while self.r:
# print('waiting for packet:', self.name)
try:
for p in self.net.recv(self.c.recv(1024)):
self.packet_recv(p)
except socket.timeout:
pass
data = self.pipe.recv()
if data is not None:
for packet in data:
# if data[:2] == 'AP':
self.net.send(packet)
data = self.pipe.recv()
if self.r:
if self.player.xv != 0 or self.player.yv != 0:
packet = 'AM' + str(self.player.x) + ' ' + str(self.player.y)
self.net.send(packet)
packet = 'IM' + str(self.player.x) + ' ' + str(self.player.y) + ' ' + self.name
self.s.send_all(packet)
def close(self):
self.c.close()
self.s.remove(self)
self.r = False
class client:
def __init__(self, world, ip='localhost'):
self.ip = ip
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.net = net(self.server)
self.world = world
self.chunk_requests = {} # chunks for which requests have been sent to the server
self.name = 'test'
self.players = {}
self.connected = False
self.last_move = 'AK0000'
self.x = 0
self.y = 0
self.connect_thread = threading.Thread(target=self._connect)
self.connect_thread.start()
# print(self.name, 'started connect thread')
self.recv_thread = threading.Thread(target=self.recv)
self.recv_thread.start()
def update(self, key, world):
out = ['A', 'K']
if key[pygame.K_w] or key[pygame.K_UP]:
out.append('1')
else:
out.append('0')
if key[pygame.K_a] or key[pygame.K_LEFT]:
out.append('1')
else:
out.append('0')
if key[pygame.K_s] or key[pygame.K_DOWN]:
out.append('1')
else:
out.append('0')
if key[pygame.K_d] or key[pygame.K_RIGHT]:
out.append('1')
else:
out.append('0')
out = ''.join(out)
if self.connected:
if self.connect_thread.is_alive():
self.connect_thread.join(1)
if self.connect_thread.is_alive():
self.connected = False
else:
self.net.send('IN' + 'timeout') # ?
if self.connected and out != self.last_move:
self.net.send(out)
self.last_move = out
return self.x, self.y
def _connect(self):
self.server.connect((self.ip, 60000))
print('connected')
self.connected = True
self.net.send('IN' + self.name)
def recv(self):
while not self.connected:
print('waiting to connect')
time.sleep(1)
while self.connected:
for p in self.net.recv(self.server.recv(1024)):
self.recv_packet(p)
def recv_packet(self, data):
if data:
if data[0] == 'A':
if data[1] == 'M':
split = data[2:].split(' ')
if len(split) == 2:
x = self.x
y = self.y
try:
self.x = float(split[0])
self.y = float(split[1])
except ValueError as error:
print(error)
self.x = x # reset position to before packet to not only update x in error
self.y = y
elif data[1] == 'P':
split = data[2:].split(' ')
if len(split) == 3:
self.world.set(int(split[0]), int(split[1]), block.block(split[2], self.world.blocks),
update=False)
else:
print('incorrect packet') # TODO: keep track of amount of incorrect packets
else:
print('incorrect action packet:', data)
elif data[0] == 'I':
if data[1] == 'C':
split = data[2:].split(' ')
self.world.deserialise_chunk(data[2:-1])
self.chunk_requests[(int(split[0]), int(split[1]))] = True
elif data[1] == 'N':
if data[2:] not in self.players:
self.players[data[2:]] = player()
print(f'player {data[2:]} joined')
else:
print(f'player {data[2:]} joined multiple times') # TODO: let clients know about other clients disconnecting
elif data[1] == 'M':
split = data[2:].split(' ')
name = split[2]
if name in self.players:
self.players[name].x = float(split[0])
self.players[name].y = float(split[1])
else:
print(f"player '{name}' moved but does not exist")
else:
print('incorrect information packet type:', data)
else:
print('incorrect packet type:', data)
def get_chunk(self, x, y):
if (x, y) not in self.chunk_requests:
packet = 'IC' + str(x) + ' ' + str(y)
self.net.send(packet)
self.chunk_requests[(x, y)] = False
t = 0
while not self.chunk_requests[(x, y)]:
time.sleep(.1)
t += 1
if t > 1000 and not self.chunk_requests[(x, y)]:
print('chunk request timeout')
packet = 'IC' + str(x) + ' ' + str(y)
self.net.send(packet)
self.chunk_requests[(x, y)] = True
t = 0
def set_block(self, x, y, value):
self.net.send('AP' + str(x) + ' ' + str(y) + ' ' + value.name)
def exit(self):
self.net.send('AQ')
self.connected = False
print('connecting connect_thread')
self.connect_thread.join(1)
if self.connect_thread.is_alive():
print('connect_thread is still alive')
else:
print('connect_tread joined')
self.recv_thread.join(1)
if self.recv_thread.is_alive():
print('recv_thread lives on')
self.server.close()
class pipe:
def __init__(self):
self.data = []
def recv(self):
if not self.data:
ret = None
else:
ret = self.data
self.data = []
return ret
def send(self, data):
self.data.append(data)