-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1116 lines (988 loc) · 39.4 KB
/
main.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
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 9 12:54:08 2020
@author: zefyr
"""
# Should have better way to set these values than hard coding
import logging
import datetime
import os
from pathlib import Path
if not os.path.exists("logs"): os.makedirs("logs")
p = Path("logs")
file = datetime.datetime.now().strftime("%H%M%S.txt")
logFormat = "%(asctime)s::%(levelname)s::%(name)s::"\
"%(filename)s::%(lineno)d::%(message)s"
logging.basicConfig(level='DEBUG', filename=p/file, format=logFormat)
import settings
import gamePlay as g
import playerPi
import playerPC
import comms
from threading import Thread
import multiprocessing
import random
import time
import traceback
import numpy as np
import platform
if 'arm' not in platform.machine().lower():
import pygame
import cv2
MOTION_DELAY = 500
testWithoutPi = False
def piProcess():
'''
Processes run on the pi. This detects a rotation on the pi, sends it,
and then waits for permission to detect a new rotation.
'''
log = ("Starting pi processes")
logging.info(log)
if settings.verbose: print(log, flush=True)
clientId = f'{datetime.datetime.now().strftime("%H%M%S")}{random.randint(0, 1000)}'
abort = False
try:
pi = playerPi.PlayerPi(clientId)
except:
log = "An error occurred initializing PlayerPi"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
abort = True
if not abort:
try:
receiver = comms.Receiver((comms.initial,
comms.assign,
comms.coolDown,
comms.axes,
comms.start,
comms.stop),
clientId)
except:
log = "An error occurred initializing pi process receiver"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
abort = True
receiver = 0
if not abort:
try:
transmitter = comms.Transmitter()
except:
log = "An error occurred initializing pi process transmitter"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
abort = True
if not abort:
try:
receiver.start()
except:
log = "An error occurred starting pi process receiver"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
abort = True
if not abort:
#First, get initial load with full playspace info
while not pi.initialReceived:
# Keep checking for an initial load
if len(receiver.packages):
try:
# Sets initialReceived to true if initial load
pi.unpack(receiver.packages.pop(0))
except:
log = f"An error occurred unpacking a message on the pi queue. Current queue: {receiver.packages}"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
# Send handshake to confirm receipt of first load
try:
package = pi.pack(pi.clientId)
except:
log = "An error occurred packing the clientId"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
abort = True
if not abort:
try:
transmitter.transmit(comms.piConfirmation, package)
except:
log = "An error occurred transmitting the clientId"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
abort = True
if not abort:
# Receive playerId. May not correspond to playerId for the same player's PC
# but that doesn't matter, this is only for ease of reading logs
while not pi.playerId:
# Keep checking for a message assigning the player number
if len(receiver.packages):
try:
# Gets true if initial load received, false and deletes message
# from queue otherwise
pi.unpack(receiver.packages.pop(0))
except:
log = f"An error occurred unpacking a message on the pi queue. Current queue: `{receiver.packages}`"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
try:
# Send handshake to confirm receipt of playerId
package = pi.pack(pi.playerId)
except:
log = "An error occurred packing the playerId"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
abort = True
if not abort:
try:
transmitter.transmit(comms.ready, package)
except:
log = "An error occurred transmitting the playerId"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
abort = True
stop = [abort]
# Send transmitter to separate thread to handle getting player input and
# sending to central, while current process gets display updates
if not abort:
transmit = Thread(target=piTransmit, args = (transmitter, pi, stop,))
transmit.daemon = True
try:
transmit.start()
except:
log = "An error occurred starting the piTransmit thread"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
abort = True
# Gameplay receiver loop checks for new packages in the queue. Packages
# set the rotation cooldown or end the game.
#while not pi.gameOver:
if not abort:
while not pi.gameOver:
if len(receiver.packages):
try:
pi.unpack(receiver.packages.pop(0))
except:
log = f"An error occurred unpacking a message on the pi queue. Current queue: `{receiver.packages}`"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
if abort:
log = "pi processes aborted due to unresolvable errors"
else:
log = "pi game over"
logging.info(log)
if settings.verbose: print(log, flush=True)
stop[0] = True
try:
transmit.join()
except:
log = "Unable to join transmit thread. Possible it was not instantiated, if game aborted early."
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
if receiver:
receiver.stop()
def piTransmit(transmitter, pi, stop):
'''
Separate thread for receiving player input on Pi and transmitting it to
central.
'''
# Hold until receive start message
while not pi.start and not pi.gameOver:
pass
delay = datetime.datetime.now()
# Get rotation information and transmit it
while not pi.gameOver:
if datetime.datetime.now()>delay:
try:
rotation = pi.getRotation(stop)
except:
log = "An error occurred getting a rotation"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
rotation = 0
if rotation:
try:
package = pi.pack(rotation)
except:
log = "An error occurred packing a rotation"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
package = 0
if package:
try:
transmitter.transmit(comms.rotation, package)
delay = datetime.datetime.now() + datetime.timedelta(milliseconds = MOTION_DELAY)
except:
log = "An error occurred transmitting a rotation"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
def pcProcess():
'''
Processes run on the pc. This detects a direction with the camera, sends it,
and then waits for permission to detect a new direction. It also runs a
display update on a separate thread which can access the local pc class, so
that the display just updates when display information is updated from a
received message.
'''
log = ("Starting PC processes")
logging.info(log)
if settings.verbose: print(log, flush=True)
breakEarly = False
abort = False
abortPygame = False
try:
# Initialize the PyGame
pygame.init()
except:
log = "An error occurred initializing Pygame"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abortPygame = True
if not abortPygame:
try:
pygame.mixer.init()
except:
log = "An error occurred initializing Pygame mixer"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abortPygame = True
if not abortPygame:
try:
# Start settings soundtrack
pygame.mixer.music.load('SoundEffects/ready_two_run.wav')
pygame.mixer.music.set_volume(0.1)
except:
log = "An error occurred loading settings music"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abortPygame = True
if not abortPygame:
try:
pygame.mixer.music.play(-1)
except:
log = "An error occurred starting settings music"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abortPygame = True
clientId = f'{datetime.datetime.now().strftime("%H%M%S")}{random.randint(0, 1000)}'
try:
pc = playerPC.PlayerPC(clientId)
except:
log = "An error has occurred initializing PlayerPC"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
stop = [0]
if not abort:
try:
receiver = comms.Receiver((comms.initial,
comms.assign,
comms.move,
comms.tag,
comms.launch,
comms.start,
comms.stop,
comms.axes,
comms.coolDown,
comms.pickup,
comms.activePower,
comms.timerOver,
comms.dropped),
clientId)
except:
log = "An error occurred initializing PC process reciever"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
receiver = 0
if not abort:
try:
transmitter = comms.Transmitter()
except:
log = "An error occurred initializing PC process transmitter"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort:
try:
receiver.start()
except:
log = "An error occurred starting the PC process receiver"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
try:
# Send receiver to separate thread
packageReceipt = Thread(target=pcPackageReceipt, args = (receiver, pc, stop,))
packageReceipt.daemon = True
except:
log = "An error occurred sending receiver to separate thread"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
try:
packageReceipt.start()
except:
log = "An error occurred starting the package receipt"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
try:
# Get settings. If not isPrimary, other returned variables are all 0. If
# primary, spawn primary player stuff
isPrimary, playMode, numPlayers, edgeLength, numObstacles, numPowerups = pc.settings()
except:
log = "An error occurred getting settings"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and isPrimary and not pc.gameOver:
try:
stopCentral = multiprocessing.Value('i', False)
except:
log = "An error occurred creating stop central flag"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
try:
central = multiprocessing.Process(target=centralNodeProcess, args = (stopCentral, playMode, numPlayers, edgeLength, numObstacles, numPowerups, ))
central.daemon = True
except:
log = "An error occurred creating central multiprocess"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
try:
central.start()
except:
log = "An error occurred starting central multiprocess"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
try:
pc.loading("Waiting for initial game state...")
except:
log = "An error occurred generating loading screen"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
#First, get initial load with full playspace info
while not pc.initialReceived and not pc.gameOver:
try:
if cv2.waitKey(1) & 0xFF == ord('q'):
abort = True
break
except:
log = "An error occurred evaluating display close out"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
if not abort and not pc.gameOver:
try:
pc.loading("Initial game state received. Waiting for player ID assignment...")
except:
log = "An error occurred updating loading screen"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
try:
# Send handshake to confirm receipt of first load
package = pc.pack(pc.clientId)
except:
log = "An error occurred packaging clientID"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
try:
transmitter.transmit(comms.pcConfirmation, package)
except:
log = "An error occurred transmitting clientID"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
# Check for assignment of a player ID
while not pc.playerId and not pc.gameOver:
try:
if cv2.waitKey(1) & 0xFF == ord('q'):
abort = True
break
except:
log = "An error occurred evaluating display close out"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
if not abort and not pc.gameOver:
try:
pc.loading(f"You are player {pc.playerId}. Say ""ready"" when you're ready to join...")
except:
log = "An error occurred displaying ready instructions"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
try:
# Send command thread to separate loop
command = Thread(target=pcCommand, args = (transmitter, pc, stop,))
command.daemon = True
except:
log = "An error occurred creating command thread"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
try:
command.start()
except:
log = "An error occurred "
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
readySent = False
while not abort and not pc.launch and not pc.gameOver:
if not readySent and pc.ready:
try:
pc.loading("You are ready! Waiting for other players to be ready...")
readySent = True
except:
log = "An error occurred displaying ready instructions"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort:
try:
if cv2.waitKey(1) & 0xFF == ord('q'):
abort = True
break
except:
log = "An error occurred evaluating display close out"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
try:
pygame.mixer.music.stop()
except:
log = "An error occurred stopping settings music"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abortPygame = True
try:
cv2.destroyAllWindows()
cv2.waitKey(1)
except:
log = "An error occurred closing settings display"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
if not abort and not pc.gameOver:
try:
frameCapture = cv2.VideoCapture(settings.camera)
frameCapture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
frameCapture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
except:
log = "An error occurred creating video capture window"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abort = True
# Start game soundtrack
if not abortPygame and not abort and not pc.gameOver:
try:
pygame.mixer.music.load('SoundEffects/Run.wav')
pygame.mixer.music.set_volume(0.1)
except:
log = "An error occurred loading gameplay music"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abortPygame = True
if not abortPygame and not abort and not pc.gameOver:
try:
pygame.mixer.music.play(-1)
except:
log = "An error occurred starting gameplay music"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abortPygame = True
if not abort and not pc.gameOver:
try:
blink = Thread(target=pcBlink, args = (pc, stop,))
blink.daemon = True
except:
log = "An error occurred creating blink thread"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
# If blink thread doesn't work for some reason but display stuff
# has worked so far, no need to abort -- this should just mean the
# player won't blink at start of game
if not abort and not pc.gameOver:
try:
blink.start()
except:
log = "An error occurred starting blink thread"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
# launch display and show feed while blink thread blinks players before
# letting people start
while not pc.start and not abort and not pc.gameOver:
try:
direction = pc.getDirection(frameCapture)
except:
log = "An error occurred getting camera feed"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
try:
pc.updateDisplay()
except:
log = "An error occurred updating display"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
try:
if cv2.waitKey(1) & 0xFF == ord('q'):
abort = True
break
except:
log = "An error occurred evaluating display close out"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
try:
blink.join()
except:
log = "An error occurred joining blink thread"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
delay = datetime.datetime.now()
#cv2.startWindowThread()
if abort: stop[0] = True
while not pc.gameOver and not stop[0]:
try:
direction = pc.getDirection(frameCapture)
except:
log = "An error occurred getting camera feed"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
try:
pc.updateDisplay()
except:
log = "An error occurred updating display"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
if direction and datetime.datetime.now()>delay:
try:
package = pc.pack(direction)
except:
log = "An error occurred packaging the direction"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
package = 0
if package:
try:
transmitter.transmit(comms.direction, package)
delay = datetime.datetime.now() + datetime.timedelta(milliseconds = MOTION_DELAY)
except:
log = "An error occurred transmitting the direction"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
try:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except:
log = "An error occurred evaluating display close out"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
try:
pygame.mixer.music.stop()
except:
log = "An error occurred ending gameplay music"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
abortPygame = True
try:
frameCapture.release()
except:
log = "An error occurred releasing the camera feed"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
try:
cv2.destroyAllWindows()
except:
log = "An error occurred closing the display"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
stop[0] = True
try:
command.join()
except:
log = "An error occurred joining the command thread"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
if isPrimary:
stopCentral.value = True
try:
central.join()
except:
log = "An error occurred joining the central multiprocess"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
try:
packageReceipt.join()
except:
log = "An error occurred joining the package receipt thread"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
try:
receiver.stop()
except:
log = "An error occurred stopping the receiver"
logging.error(log, exc_info = True)
if settings.verbose:
print(log, flush=True)
traceback.print_exc()
def pcBlink(pc, stop):
'''
Blinks player on game startup
'''
on = True
while not pc.start and not stop[0]:
pc.blinkPlayer(on)
on = not on
time.sleep(0.3)
def pcPackageReceipt(receiver, pc, stop):
'''
Gets packages from central and updates the display information with the new
event. Does not update the display on screen, which must be handled in the
main thread for Mac compatibility.
'''
while not pc.gameOver and not stop[0]:
if len(receiver.packages):
pc.unpack(receiver.packages.pop(0))
#pc.updateDisplay()
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
#cv2.destroyAllWindows()
def pcCommand(transmitter, pc, stop):
'''
Separate thread for receiving player input on PC and transmitting it to
central.
'''
while not pc.gameOver and not stop[0]:
# Returned command is a topic. Package is sent to provide player ID.
command = pc.getCommand(stop)
if command:
package = pc.pack(command)
transmitter.transmit(command, package)
def centralNodeProcess(stop, playMode, numPlayers, edgeLength, numObstacles, numPowerups):
'''
Processes run on the central node only, which will run on a separate thread
from that particular player's personal processes (pcProcess above). This
waits for messages from player PCs and Pi's about direction and rotation.
When a message is received, the PlaySpace and game state are updated, and
a message is sent to player PCs and Pi's indicating the update.
'''
if settings.verbose: print("Starting central process", flush=True)
clientId = f'{datetime.datetime.now().strftime("%H%M%S")}{random.randint(0, 1000)}'
receiver = comms.Receiver((comms.piConfirmation,
comms.pcConfirmation,
comms.direction,
comms.command,
comms.ready,
comms.powerUp,
comms.rotation,
comms.drop,
comms.pickup),
clientId)
transmitter = comms.Transmitter()
receiver.start()
game = g.GamePlay(playMode, numPlayers, edgeLength, numObstacles, numPowerups)
initialPackage = game.pack()
# Send initial message until all devices confirm receipt
devicesPending = True
pcs = [i for i in range(1, game.numPlayers+1)]
readiesPC = [i for i in range(1, game.numPlayers+1)]
pcsReceived = []
if testWithoutPi:
pis = []
readiesPi = []
else:
pis = [i for i in range(game.numPlayers+1, 2*game.numPlayers+1)]
readiesPi = [i for i in range(game.numPlayers+1, 2*game.numPlayers+1)]
pisReceived = []
readies = [i for i in range(1, game.numPlayers+1)]
while devicesPending and not stop.value:
# Transmit the initial playspace info
transmitter.transmit(comms.initial, initialPackage)
# Check if any packages in the queue
if len(receiver.packages):
if settings.verbose: print("Central first loop found", receiver.packages, flush=True)
# If yes, unpack the first one and use to identify which device is
# now connected. Confirmation topics are for the first step in the
# handshake, providing central with a client ID for the PC or Pi.
# Central then associates a player ID with that device and sends it
# out. When the device has received its number successfully, it
# sends a Ready, completing device registration.
client, player, pi, pc, ready = game.unpack(receiver.packages.pop(0))
if pi and client not in pisReceived:
pisReceived.append(client)
package = game.pack(clientId = client, playerId = pis.pop(0))
transmitter.transmit(comms.assign, package)
elif pc and client not in pcsReceived:
pcsReceived.append(client)
package = game.pack(clientId = client, playerId = pcs.pop(0))
transmitter.transmit(comms.assign, package)
elif ready:
if player in readiesPC:
readiesPC.remove(player)
elif player in readiesPi:
readiesPi.remove(player)
# Repeat until no devices left to join
devicesPending = len(pcs)+len(pis)+len(readiesPC)+len(readiesPi)
if settings.verbose:
print("Pending pis:", pis, flush=True)
print("Pending pcs:", pcs, flush=True)
print("Pending ready pis:", readiesPi, flush=True)
print("Pending ready pcs:", readiesPC, flush=True)
time.sleep(1)
if not stop.value:
game.start = True
if settings.verbose: print("All player devices connected", flush=True)
package = game.pack(game.start)
transmitter.transmit(comms.launch, package)
# Let players blink on screen a moment before playing
time.sleep(5)
transmitter.transmit(comms.start, package)
# Then start the game
while not game.isGameOver() and not stop.value:
# Poll for messages in queue
if len(receiver.packages):
# On receipt, get the first message and do stuff relevant to the
# message topic
try:
topic, message = game.unpack(receiver.packages.pop(0))
except:
log = f"An error occurred unpacking a message on the central queue. Current queue: `{receiver.packages}`"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
# Generally this should result in some outbound message
if message:
try:
transmitter.transmit(topic, message)
except:
log = f"Unable to transmit message: {message}"
logging.error(log)
if settings.verbose: print(log, flush=True)
traceback.print_exc()
else:
if settings.verbose:
print("No outbound message to send", flush=True)
# Check if a rotation cooldown is in place
if game.playSpace.rotationCoolDownTime:
# If yes, check if it's now ended, in which case a message should
# be sent.