-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.py
1121 lines (858 loc) · 37.8 KB
/
server.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
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
# ----------------------- Imports -----------------------
from socket import *
from random import randint
import select
from threading import *
import time
import traceback
from datetime import datetime
from player import Player
from wall import Wall
from light import Light
from inlight import *
from common import *
# ----------------------- IP -----------------------
def extractingIP():
"""The host IP"""
s = socket(AF_INET, SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return(ip)
# ----------------------- Constants and Global Variables -----------------------
#logs and debugs
DEBUG_M_IN=False #debug prints on received msgs
DEBUG_M_OUT=False #debug prints on sent msgs
DEBUG_S_IN=False #debug prints on receiving socket
DEBUG_S_OUT=False #debug prints on sending sockets
DEBUG_CO=False #debug prints for problems during connection attempts
DATE=datetime.now()
LOG=None
# Game map
SIZE_X = int(1920 * .9)
SIZE_Y = int(1080 * .9)
SIZE = (SIZE_X,SIZE_Y)
# Movements speeds differ depending on the player's team
STEP_X = [10, 4, 3]
STEP_Y = [10, 4, 3]
STEP_PRECISION = 1
# Server
IP = extractingIP()
# Player
SIZE_MAX_PSEUDO = 10
PLAYER_SIZE = Size(20, 20)
# Maybe not mandatory
WAITING_TIME = 0.005 # in seconds - period of connection requests when trying to connect to the host - must be < TIMEOUT
HOST = str(IP)
PORT = 9998
# Sockets main variables
MAINSOCKET = None
LOCK = None
BACKLOG = 1
MAX_NUMBER_OF_PLAYERS = 10
PLAYERS_BEGIN_PORT = 9000
MESSAGES_LENGTH = 1024 * 3
TIMEOUT = 0.050 # socket set to non-blocking mode - must be > waiting time
# Server managing variables
LISTENING = True
MANAGING = True
STOP = False
### Game
TIME_TO_SWITCH = 5 # Time before switching from lobby to the game when everyone is ready, and from game to lobby when the game is finished.
# Lobby
LOBBY = True
TEAMSID = {"Not assigned" : 0, "Seekers" : 1, "Hidders" : 2}
READY = {}
# In-game
FINISHED = False
DEAD = {}
SEEKING_TIME = 200 # Time to seek for the hidders - in seconds
CURRENT_INGAME_TIME = None # Current in-game time left - in seconds
game_start_time = None
TRANSITION_TIME = 5 # Time to wait for transitions from LOBBY to GAME and vice-versa - in seconds
CURRENT_TRANSITION_TIME = None # Current transition time left - in seconds
transition_start_time = None
# ----------------------- Variables -----------------------
dicoJoueur = {} # Store players' Player structure
dicoSocket = {} # Store clients' (sock, addr) structures where sock is the socket used for communicating, and addr = (ip, port)
waitingDisconnectionList = []
availablePorts = [] # Store available ports for new players
dicoMur = {}
WALLS = [] # List of walls
LIGHTS = []
STATIC_SHADOW = None
LIST_STATIC_SHADOW = []
# -------------------- Processing a Request -----------------------
def processRequest(addr:int, s:str):
"""Calls the right function according to process a request
Args:
addr : player address
s (str): the request to process
Returns:
A string representing the connection of the player and/or the state of the server or why the request was invalid
"""
type = typeOfRequest(s)
if type == "CONNECT":
return(processConnect(addr, s))
elif type == "INPUT":
return(processInput(addr, s))
elif type == "DISCONNECTION":
return(processDisconnection(addr, s))
elif type == "PING":
return(processPing(s))
else :
return("Invalid Request")
def processConnect(addr:tuple, s:str):
"""Process a connection request
Args:
s (str): the connection request ("CONNECT <username> END")
Returns:
A string representing the connection of the player and the state of the server or why the connection request was invalid
"""
if len(dicoSocket) >= MAX_NUMBER_OF_PLAYERS:
return("The game is already full")
elif not LOBBY:
return("The game has already started")
pseudo = extractPseudo(s)
if doPseudoExist(pseudo):
# # same ip, socket may have been lost so send connection message back
# if pseudo in dicoSocket:
# addr = dicoSocket[pseudo][1]
# if addr[0] == ip:
# return firstConnection(pseudo)
# else:
# # error somewhere
# return("This pseudo already exists.")
# else:
# return("This pseudo already exists.")
# bad idea because the socket will be created several times
return("This pseudo already exists.")
elif len(pseudo)>SIZE_MAX_PSEUDO:
return("Your pseudo is too big !")
elif [c for c in pseudo if c in [" ", ",", "(", ")"]] != []:
return("Don't use ' ' or ',' or '(' or ')' in your pseudo !")
else :
initNewPlayer(pseudo)
DATE=datetime.now()
LOG.write(DATE.strftime("%H:%M - ")+"Connected: "+addr[0]+" - "+pseudo+"\n")
return(firstConnection(pseudo))
def processInput(addr:int, s:str):
"""Process an 'input' request
Args:
addr : player address
s (str): the input request ("INPUT <username> <input> END")
Returns:
A string representing the state of the server or why the input request was invalid
"""
pseudo = extractPseudo(s)
if not(doPseudoExist(pseudo)):
return("No player of that name")
if not(validAddress(addr, pseudo)):
return("You are impersonating someone else !")
inputWord = extractWord(s)
rules(inputWord,pseudo)
return(states(pseudo))
def processDisconnection(addr:tuple, s:str):
"""Process a disconnection request
Args:
s (str): the disconnection request ("DISCONNECT <username> END")
Returns:
"DISCONNECTED <username> END" or why the disconnection request was invalid
"""
pseudo = extractPseudo(s)
if not(validAddress(addr, pseudo)):
return("You are impersonating someone else !")
DATE=datetime.now()
LOG.write(DATE.strftime("%H:%M - ")+"Disconnected: "+addr[0]+" - "+pseudo+"\n")
return("DISCONNECTED " + pseudo + " END")
def processPing(s:str):
"""Process a ping request
Args:
s (str): the time ("PING <clock time> END")
Returns:
"PING <clock time> END"
"""
Clock = extractClock(s)
return("PING " + Clock + " END")
def typeOfRequest(s:str):
"""The type of a request (CONNECT,INPUT,DISCONNECT)"""
type = s.split(" ")[0]
return(type)
def extractPseudo(s:str):
"""The pseudo of a player from a connection request"""
pseudo = ""
parts = s.split(" ")
if parts[0] == "CONNECT":
i = 1
while parts[i] != "END" and i < len(parts) - 1:
pseudo += parts[i] + " "
i+=1
pseudo = pseudo[:-1]
else:
pseudo = parts[1]
return(pseudo)
def extractWord(s):
"""The input word from the 's' input request string"""
parts = s.split(" ")
return(parts[2])
def extractClock(s):
"""The clock time from the 's' ping request string"""
parts = s.split(" ")
return(parts[1])
def states(pseudo:str):
"""The state of the server modulo what the player can see
Args:
pseudo (str): player pseudo
Returns:
A string representing the state of the server
"""
player = 0 # the player
liste = [] # list of player strings
listOfPlayers = [] # list of all players
listOfAlivePlayers = [] # list of players that have not been caught yet
out="" # string to send back
# gets all player
for key in dicoJoueur:
p = dicoJoueur[key]
if key == pseudo:
player = p
listOfPlayers.append(p)
if not DEAD[key]:
listOfAlivePlayers.append(p)
# In-game messages
if not LOBBY:
# In a transition state from Game to Lobby
if not None in [TRANSITION_TIME, transition_start_time]:
out += "TRANSITION_GAME_LOBBY " + checkForWin().replace(" ", "_") + "_Going_back_to_lobby_in_{time:.1f}s ".format(time=CURRENT_TRANSITION_TIME)
else:
out += "GAME " + "{time:.1f} ".format(time=CURRENT_INGAME_TIME)
if not DEAD[pseudo]:
#TEMPORAIRE
t = time.time()
shadows = Visible(player, LIGHTS, listOfAlivePlayers, SIZE_X, SIZE_Y, STATIC_SHADOW, WALLS, LIST_STATIC_SHADOW)
visiblePlayer = allVisiblePlayer(shadows,listOfAlivePlayers)
formatShadows = sendingFormat(shadows)
print("Shadows calculation time : " + str(1000 * (time.time() - t)))
# gets visible player strings
liste.append(str(player))
for key in visiblePlayer:
p = dicoJoueur[key]
if key != pseudo:
liste.append(str(p))
out += "STATE "+(str(liste)).replace(" ","")+" SHADES "+formatShadows+" END"
else:
for p in listOfAlivePlayers:
liste.append(str(p))
out += "STATE "+(str(liste)).replace(" ","")+" SHADES [] END"
return out
# Lobby messages
else:
# In a transition state from Lobby to Game
if not None in [TRANSITION_TIME, transition_start_time]:
out += "TRANSITION_LOBBY_GAME Entering_game_in_{time:.1f}s ".format(time=CURRENT_TRANSITION_TIME)
else:
rlist = []
for key in READY:
if READY[key]:
rlist.append(key) # List of ready players' username
n = len(rlist)
strList = "["
for i in range(n):
if i != n - 1:
strList += rlist[i] + ","
else:
strList += rlist[i]
strList += "]"
out += "LOBBY " + strList + " "
for p in listOfPlayers:
liste.append(str(p))
out += "STATE "+(str(liste)).replace(" ","")+" END"
return out
def walls():
"""Formated wall string "WALLS <wallstring> END" """
liste = []
for key in dicoMur:
liste.append(str(dicoMur[key]))
out = "WALLS " + (str(liste)).replace(" ","") + " END"
return(out)
def firstConnection(pseudo:str):
"""Formated string for first connections:
"CONNECTED <username> <size> WALLS <wallstring> STATE <statestring> SHADES <shadestring> END" """
out = "CONNECTED " + pseudo + " " + (str(SIZE)).replace(" ","") + " " + walls().replace("END","") + states(pseudo)
return(out)
def doPseudoExist(pseudo:str):
"""If the pseudo exists"""
return(pseudo in dicoJoueur.keys())
def validAddress(addr, pseudo:str):
"""If the pseudo and a socket with the address exist and they are associated"""
return (pseudo in dicoJoueur.keys() and addr in dicoSocket.keys() and dicoSocket[addr][1] == pseudo)
# ----------------------- Games Rules -----------------------
def rules(inputLetter:str,pseudo:str,factor=1.):
"""Process an input for a player
Args:
inputLetter (char): input letter
pseudo (str): player pseudo
factor (float): a factor applicated to steps. Less than one. Defaults to 1.
Returns:
"Invalid Input" if the input did not respect the rules, else None
"""
global READY
id, _, _, position1, size1 = dicoJoueur[pseudo].toList()
x,y=position1.x,position1.y
tempId = id
match inputLetter:
case ".":
pass
case "RIGHT":
x+=int(STEP_X[id]*factor)
case "LEFT":
x-=int(STEP_X[id]*factor)
case "UP":
y-=int(STEP_Y[id]*factor)
case "DOWN":
y+=int(STEP_Y[id]*factor)
case "RED":
if LOBBY and not READY[pseudo]:
tempId = TEAMSID["Seekers"]
case "BLUE":
if LOBBY and not READY[pseudo]:
tempId = TEAMSID["Hidders"]
case "NEUTRAL":
if LOBBY and not READY[pseudo]:
tempId = TEAMSID["Not assigned"]
case "READY":
if LOBBY and id != 0:
READY[pseudo] = not READY[pseudo]
case _ :
return("Invalid Input")
if tempId != id:
dicoJoueur[pseudo].update(teamId=tempId)
if correctPosition(pseudo, x,y,size1.w,size1.h):
dicoJoueur[pseudo].update(position=Position(x, y), size=Size(size1.w, size1.h))
elif abs(position1.x-x)>STEP_PRECISION or abs(position1.y-y)>STEP_PRECISION:
rules(inputLetter,pseudo,factor/2)
# rules can launch transition only from LOBBY to GAME
if LOBBY:
waitForTransition(cancel=(not (checkReady() and noEmptyTeams())))
return
def checkForWin():
"""Did a team win the game?"""
if LOBBY:
return ""
else:
if CURRENT_INGAME_TIME <= 0:
return "The hidders won the game!"
else:
every1dead = True # by default, but updated right afterwards
for pseudo in dicoJoueur:
if dicoJoueur[pseudo].teamId == TEAMSID["Hidders"]:
every1dead = every1dead and DEAD.get(pseudo,False)
if every1dead:
return "The seekers won the game!"
return "None of both teams have won the game yet."
def checkReady():
"""Are all players ready?"""
for pseudo in READY:
if not READY[pseudo]:
return False
return True
def noEmptyTeams():
"""Are both Seekers and Hidders teams not empty?"""
teamCounts = {TEAMSID[i] : 0 for i in TEAMSID}
n = len(teamCounts)
# problem with the server variables, TEAMSID should always have at least 3 different teams
if n <= 2:
return False
for pseudo in dicoJoueur:
teamId, _, _, _, _ = dicoJoueur[pseudo].toList()
if teamId in teamCounts:
teamCounts[teamId] += 1
return teamCounts[TEAMSID["Hidders"]] > 0 and teamCounts[TEAMSID["Seekers"]] > 0
def switchGameState(ready:bool=None):
"""Switch from lobby to game or vice-versa. If no parameters are used, it will switch to the other state automatically"""
global LOBBY
if ready == None:
ready = LOBBY
if LOBBY == ready:
LOBBY=not ready
# in game
if not LOBBY:
launchGame()
# in lobby
else:
resetGameState()
# stop transition state
waitForTransition(cancel=True)
def waitForTransition(cancel=False):
"""Start a transition timer before switching lobby <-> game (not done in the function itself) or cancel a current timer if cancel = True"""
global CURRENT_TRANSITION_TIME
global transition_start_time
if cancel:
CURRENT_TRANSITION_TIME = None
transition_start_time = None
elif not cancel and None in [CURRENT_TRANSITION_TIME, transition_start_time]:
CURRENT_TRANSITION_TIME = TRANSITION_TIME
transition_start_time = time.time()
def launchGame():
"""Set the basic state of the game when launching a new game"""
global CURRENT_INGAME_TIME
global game_start_time
global FINISHED
FINISHED = False
CURRENT_INGAME_TIME = SEEKING_TIME
for pseudo in dicoJoueur:
_, _, _, _, size = dicoJoueur[pseudo].toList()
dicoJoueur[pseudo].update(position=randomValidPosition(pseudo, size.w, size.h))
game_start_time = time.time()
DATE=datetime.now()
LOG.write(DATE.strftime("%H:%M - ")+"Game started")
def resetGameState():
"""Reset the current state of the game to get ready for a new game"""
global CURRENT_INGAME_TIME
global game_start_time
global READY
global DEAD
CURRENT_INGAME_TIME = None
game_start_time = None
for pseudo in dicoJoueur:
_, _, _, _, size = dicoJoueur[pseudo].toList()
READY[pseudo] = False
DEAD[pseudo] = False
dicoJoueur[pseudo].update(position=randomValidPosition(pseudo, size.w, size.h))
def correctPosition(pseudo:str, x:int,y:int,dx:int,dy:int):
"""If a position is inside the level boundaries and does not overlap walls or other players
Args:
pseudo (str): player pseudo
x (int): player x position
y (int): player y position
dx (int): player width
dy (int): player height
Returns:
bool: is the position valid for player 'pseudo'?
"""
# The player is dead and can not move
if DEAD.get(pseudo,False):
return False
correctX = (x>=0) and (x+dx <= SIZE_X)
correctY = (y>=0) and (y+dy <= SIZE_Y)
return correctX and correctY and not collision(pseudo, x, y, dx, dy)
def collision(pseudo:str, x:int, y:int, dx:int, dy:int):
"""If a position does not overlap walls or other players
Args:
pseudo (str): player pseudo
x (int): player x position
y (int): player y position
dx (int): player width
dy (int): player height
Returns:
bool: is the position not making player 'pseudo' overlap walls or other?
"""
global DEAD
id = 0
if pseudo in dicoJoueur:
id, _, _, _, _ = dicoJoueur[pseudo].toList()
c = (x + dx/2, y + dy/2)
for key in dicoMur.keys():
_, _, position, size = dicoMur[key].toList()
if abs(c[0] - position.x - size.w/2) < (dx + size.w)/2 and abs(c[1] - position.y - size.h/2) < (dy + size.h)/2:
return True
for key in dicoJoueur.keys():
if key != pseudo and not DEAD.get(key, False):
pid, username, _, position, size = dicoJoueur[key].toList()
if abs(c[0] - position.x - size.w/2) < (dx + size.w)/2 and abs(c[1] - position.y - size.h/2) < (dy + size.h)/2:
# players should be able to catch others only if the game started (LOBBY = False)
if (not LOBBY and not FINISHED and id != pid):
if id == TEAMSID["Seekers"] and pid == TEAMSID["Hidders"]:
DEAD[username] = True
return False # The player caught a hidder and can thus move on its previous position
elif pid == TEAMSID["Hidders"] and id == TEAMSID["Seekers"]:
DEAD[pseudo] = True
return True # The player got caught and can no longer move
return True
return False
# ----------------------- Init of a new Player -----------------------
def initNewPlayer(pseudo:str):
"""Creates a new player 'pseudo'
Args:
pseudo (str): the player pseudo
"""
size = sizeNewPlayer()
dx,dy=size.w,size.h
pos = positionNewPlayer(pseudo, dx, dy)
color = colorNewPlayer()
dicoJoueur[pseudo] = Player(0, pseudo, color, pos, size)
READY[pseudo] = False
DEAD[pseudo] = False
def sizeNewPlayer():
"""A size for a new player (fixed)"""
return PLAYER_SIZE
def positionNewPlayer(pseudo, dx, dy):
"""A position for a new player (random)"""
return randomValidPosition(pseudo, dx, dy)
def colorNewPlayer():
"""A color for a new player (random)"""
return Color(randint(1,255),randint(1,255),randint(1,255))
def randomValidPosition(pseudo, dx, dy):
"""Generate a random valid position"""
pos = Position(randint(0, int(SIZE_X - dx)), randint(0, int(SIZE_Y - dy)))
x,y=pos.x,pos.y
while not correctPosition(pseudo, x, y, dx, dy):
pos = Position(randint(0, int(SIZE_X - dx)), randint(0, int(SIZE_Y - dy)))
x,y=pos.x,pos.y
return pos
# ----------------------- Threads -----------------------
def manage_server():
"""Manage console inputs"""
global STOP
global LISTENING
global MANAGING
global DEBUG_M_IN
global DEBUG_M_OUT
global DEBUG_S_IN
global DEBUG_S_OUT
global DEBUG_CO
global MAINSOCKET
while not STOP:
command = input()
DATE=datetime.now()
LOG.write(DATE.strftime("%H:%M - ")+"Command: "+command+'\n\t')
match command:
case "stop":
STOP = True
print("STOP = ", STOP)
MAINSOCKET.close()
print("Socket server closed !")
for username, (sock,addr) in dicoSocket.items():
sock.close()
print("Client sockets closed !")
print("Every sockets have been successfully closed!")
case "deaf":
LISTENING = False
print("LISTENING = ", LISTENING)
case "listen":
LISTENING = True
print("LISTENING = ", LISTENING)
case "ignore":
MANAGING = False
print("MANAGING = ", MANAGING)
case "manage":
MANAGING = True
print("MANAGING = ", MANAGING)
case "debug":
DEBUG_M_IN=True
DEBUG_M_OUT=True
DEBUG_S_IN=True
DEBUG_S_OUT=True
DEBUG_CO=True
print("All debugging parameters have been set to True")
LOG.write("All debugging parameters have been set to True\n\t")
print("To avoid too much debug printing use : debug_msg, debug_socket, debug_in, debug_out or debug_connect")
print("To stop use no_debug")
case "debug_all":
DEBUG_M_IN=True
DEBUG_M_OUT=True
DEBUG_S_IN=True
DEBUG_S_OUT=True
DEBUG_CO=True
print("All debugging parameters have been set to True")
LOG.write("All debugging parameters have been set to True\n\t")
print("To stop use no_debug")
case "debug_msg":
DEBUG_M_IN=True
DEBUG_M_OUT=True
print("DEBUG_M_IN=", DEBUG_M_IN)
print("DEBUG_M_OUT=", DEBUG_M_OUT)
LOG.write("DEBUG_M_IN="+DEBUG_M_IN+"\n\tDEBUG_M_OUT="+DEBUG_M_OUT+"\n\t")
print("To stop use no_debug_msg")
print("You may use : debug_all, debug_socket, debug_in, debug_out or debug_connect")
case "debug_socket":
DEBUG_S_IN=True
DEBUG_S_OUT=True
print("DEBUG_S_IN=", DEBUG_S_IN)
print("DEBUG_S_OUT=", DEBUG_S_OUT)
LOG.write("DEBUG_S_IN="+DEBUG_S_IN+"\n\tDEBUG_S_OUT="+DEBUG_S_OUT+"\n\t")
print("To stop use no_debug_socket")
print("You may use : debug_all, debug_msg, debug_in, debug_out or debug_connect")
case "debug_in":
DEBUG_M_IN=True
DEBUG_S_IN=True
print("DEBUG_M_IN=", DEBUG_M_IN)
print("DEBUG_S_IN=", DEBUG_S_IN)
LOG.write("DEBUG_M_IN="+DEBUG_M_IN+"\n\tDEBUG_S_IN="+DEBUG_S_IN+"\n\t")
print("To stop use no_debug_in")
print("You may use : debug_all, debug_msg, debug_socket, debug_out or debug_connect")
case "debug_out":
DEBUG_M_OUT=True
DEBUG_S_OUT=True
print("DEBUG_M_OUT=", DEBUG_M_OUT)
print("DEBUG_S_OUT=", DEBUG_S_OUT)
LOG.write("DEBUG_M_OUT="+DEBUG_M_OUT+"\n\tDEBUG_S_OUT="+DEBUG_S_OUT+"\n\t")
print("To stop use no_debug_out")
print("You may use : debug_all, debug_msg, debug_in, debug_socket or debug_connect")
case "debug_connect":
DEBUG_CO=True
print("DEBUG_CO=", DEBUG_CO)
LOG.write("DEBUG_CO="+DEBUG_CO+"\n\t")
print("To stop use no_debug_connect")
print("You may use : debug_all, debug_msg, debug_in, debug_socket or debug_out")
case "no_debug":
DEBUG_M_IN=False
DEBUG_M_OUT=False
DEBUG_S_IN=False
DEBUG_S_OUT=False
DEBUG_CO=False
print("All debugging parameters have been set to False")
case "no_debug_msg":
DEBUG_M_IN=False
DEBUG_M_OUT=False
print("DEBUG_M_IN=", DEBUG_M_IN)
print("DEBUG_M_OUT=", DEBUG_M_OUT)
case "no_debug_socket":
DEBUG_S_IN=False
DEBUG_S_OUT=False
print("DEBUG_S_IN=", DEBUG_S_IN)
print("DEBUG_S_OUT=", DEBUG_S_OUT)
case "no_debug_in":
DEBUG_M_IN=False
DEBUG_S_IN=False
print("DEBUG_M_IN=", DEBUG_M_IN)
print("DEBUG_S_IN=", DEBUG_S_IN)
case "no_debug_out":
DEBUG_M_OUT=False
DEBUG_S_OUT=False
print("DEBUG_M_OUT=", DEBUG_M_OUT)
print("DEBUG_S_OUT=", DEBUG_S_OUT)
case "no_debug_connect":
DEBUG_CO=False
print("DEBUG_CO=", DEBUG_CO)
case _:
print("Wrong command : use either stop, deaf, listen, ignore, manage or debug commands")
print("STOP = ", STOP)
print("LISTENING = ", LISTENING)
print("MANAGING = ", MANAGING)
print("LOBBY = ", LOBBY)
LOG.write("STOP = "+ str(STOP)+'\n\t')
LOG.write("LISTENING = "+ str(LISTENING)+'\n\t')
LOG.write("MANAGING = "+ str(MANAGING)+'\n\t')
LOG.write("LOBBY = "+ str(LOBBY)+'\n')
return
def manage_game_state():
"""Thread to manage the current state of the game and communication with clients."""
global waitingDisconnectionList
global CURRENT_INGAME_TIME
global CURRENT_TRANSITION_TIME
global FINISHED
while not STOP:
# Listening for clients and answering
if LISTENING or MANAGING:
sockets = [MAINSOCKET] + [dicoSocket[addr][0] for addr in dicoSocket]
if sockets != []:
inSockets, _, _ = select.select(sockets, [], [], TIMEOUT)
for sock in inSockets:
# New connections
if sock == MAINSOCKET:
if LISTENING:
try:
data, addr = MAINSOCKET.recvfrom(MESSAGES_LENGTH)
in_data = str(data.strip(), "utf-8")
in_ip = addr[0]
if DEBUG_M_IN:
print("{} wrote to MAINSOCKET:".format(addr))
print(in_data)
out = processRequest(addr, in_data)
message = out.split(" ")
username = message[1]
if message[0]=="CONNECTED":
if DEBUG_CO:
print("Connection attempt from ",addr," with username ",username)
sock = socket(AF_INET, SOCK_DGRAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.settimeout(TIMEOUT)
# port attribution
if DEBUG_CO:
print("available ports = ", availablePorts)
port = availablePorts[0]
out = message[0] + " " + str(port)
for s in message[1:]:
out += (" " + s)
# out = CONNECTED <port> <username> <size> WALLS <wallstring> STATE <statestring> SHADES <shadestring> END
sock.bind((HOST, port))
availablePorts.remove(port)
username = message[1]
dicoSocket[addr] = (sock, username)
if DEBUG_M_OUT:
print("sending to: ", addr)
print(">>> ",out)
try:
MAINSOCKET.sendto(bytes(out,'utf-8'), addr)
if DEBUG_S_OUT:
print("answer sent!\n")
except (OSError):
if DEBUG_S_OUT:
traceback.print_exc()
DATE=datetime.now()
LOG.write(DATE.strftime("%H:%M - ")+"New connection from " + str(in_ip) + " failed!\n")
print("New connection from " + str(in_ip) + " failed!")
waitingDisconnectionList.append((addr, sock, username))
except (BlockingIOError, TimeoutError):
pass
except (OSError):
if DEBUG_S_IN:
traceback.print_exc()
print("The main socket was closed. LISTENING = " + str(LISTENING) + " and STOP = " + str(STOP))
else:
print("Connection attempt from " + str(in_ip) + " | Refused : LISTENING = " + str(LISTENING))
# Already connected clients
else:
host, port = sock.getsockname()
try:
data, addr = sock.recvfrom(MESSAGES_LENGTH)
in_data = str(data.strip(), "utf-8")
in_ip = addr[0]
if DEBUG_M_IN:
print("{} wrote to sock with port {}:".format(addr, port))
print(in_data)
out = processRequest(addr, in_data)
message = out.split(" ")
if addr in dicoSocket and dicoSocket[addr][0] == sock:
username = dicoSocket[addr][1]
if message[0]=="DISCONNECTED":
username = message[1]
waitingDisconnectionList.append((addr, sock, username))
if DEBUG_M_OUT:
print("sock with port {} for player {} wrote back to {} :".format(port, username, addr))
print(">>> ",out,"\n")
try:
sock.sendto(bytes(out,'utf-8'), addr)
except (OSError):
if DEBUG_S_OUT:
traceback.print_exc()
DATE=datetime.now()
LOG.write(DATE.strftime("%H:%M - ")+"Loss connection while sending data with player " + username + " (ip = " + str(addr[0]) + ")\n")
print("Loss connection while sending data with player " + username + " (ip = " + str(addr[0]) + ")")
waitingDisconnectionList.append((addr, sock, username))
except (BlockingIOError, TimeoutError):
pass
except (OSError):
if DEBUG_S_IN:
traceback.print_exc()
print("The main socket was closed. LISTENING = " + str(LISTENING) + " and STOP = " + str(STOP))
# process disconnections
for elt in waitingDisconnectionList:
addr, sock, username = elt[0], elt[1], elt[2]
if addr in dicoSocket and dicoSocket[addr] == (sock, username):
host, port = sock.getsockname()
availablePorts.append(port)
sock.close()
dicoSocket.pop(addr)
dicoJoueur.pop(username)
READY.pop(username)
DEAD.pop(username)
waitingDisconnectionList = []
# Not in a transition state
if None in [CURRENT_TRANSITION_TIME, transition_start_time]:
# In game
if not (None in [CURRENT_INGAME_TIME, game_start_time]):
CURRENT_INGAME_TIME = SEEKING_TIME - (time.time() - game_start_time)
if CURRENT_INGAME_TIME < 0:
CURRENT_INGAME_TIME = 0
# game finished
if not LOBBY and (len(dicoSocket.keys())==0 or not "None" in checkForWin()):
FINISHED = True
DATE=datetime.now()
LOG.write(DATE.strftime("%H:%M - ")+"Game ended")
waitForTransition()
# In a transition state
else:
CURRENT_TRANSITION_TIME = TRANSITION_TIME - (time.time() - transition_start_time)
if CURRENT_TRANSITION_TIME <= 0:
switchGameState()
time.sleep(WAITING_TIME)