-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcode.py
More file actions
2204 lines (2003 loc) · 90.6 KB
/
code.py
File metadata and controls
2204 lines (2003 loc) · 90.6 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
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
"""
Moon Miner Game
WIP by Dan Cogliano
"""
VERSION = "1.0.4"
JSON_VERSION = 1
import board
import picodvi
import framebufferio
import sys
import os
import gc
import time
import math
import json
import struct
import random
import displayio
import array
import usb
import usb.core
import adafruit_usb_host_descriptors
import adafruit_imageload
import audiocore
import audiomixer
from adafruit_fruitjam.peripherals import Peripherals
#fruit_jam = Peripherals(audio_output="speaker")
fruit_jam = Peripherals(audio_output="headphone")
# use headphones
#fruit_jam.dac.headphone_output = True
#fruit_jam.dac.dac_volume = -10 # dB
# or use speaker
#fruit_jam.dac.speaker_output = True
#fruit_jam.dac.speaker_volume = -20 # dB
# set sample rate & bit depth, use bclk
#fruit_jam.dac.configure_clocks(sample_rate=44100, bit_depth=16)
from adafruit_bitmap_font import bitmap_font
import bitmaptools
from adafruit_display_text.bitmap_label import Label
from adafruit_display_shapes.rect import Rect
from adafruit_display_shapes.triangle import Triangle
from adafruit_display_shapes.filled_polygon import FilledPolygon
from adafruit_display_text import wrap_text_to_lines
import supervisor
import storage
# terminalio
from adafruit_fruitjam import peripherals
from displayio import Group
from terminalio import FONT
import gc
DISPLAY_WIDTH = 640 # Take advantage of higher resolution
DISPLAY_HEIGHT = 480
COLOR_DEPTH = 8 # 8-bit color for better memory usage
LANDER_WIDTH = 32
LANDER_HEIGHT = 32
TREZ = 10 # terrain resolution in pixels
LAVA_COUNT = 16 # should be divisible into 480
FRAME_RATE = .05
BTN_DPAD_UPDOWN_INDEX = 1
BTN_DPAD_RIGHTLEFT_INDEX = 0
BTN_ABXY_INDEX = 5
BTN_OTHER_INDEX = 6
timesfile = "/saves/moonminer.json"
class Game:
def __init__(self):
#initial settings go here
self.xvelocity = 0 # initial velocity
self.yvelocity = 10 # initial velocity
#self.scale = .8 # pixels to meter
self.scale = 2.4 # pixels to meter (24 pixels / 10 meters high)
self.xdistance = (DISPLAY_WIDTH//2 - LANDER_WIDTH//2)//self.scale
self.ydistance = 0
self.ydistance = -LANDER_HEIGHT
self.gravity = 1.62 # m/s/s
self.rotate = 18
self.frotate = 270.0
self.timer = 0
self.gtimer = 0
self.fcount = 0
self.thruster = False # self.thruster initially turned off
self.thrust = 1.5 # self.thrust strength
self.fuel = 10000 # fuel capacity
self.fuelleak = 0
#interface index, and endpoint addresses for USB Device instance
self.kbd_interface_index = None
self.kbd_endpoint_address = None
self.keyboard = None
self.controller = None
self.tpage = 0 # terrian display page
self.onground = False
self.crashed = False
self.game_over = False
self.message_label = []
self.display_terrain = []
self.gem_group = []
self.volcano_group = []
self.lander_group = []
self.sprite1 = []
self.sprite2 = []
self.missions = []
self.mines = []
self.volcanos = []
self.times = []
self.id = None
self.last_input = "" # c for controller, k for keyboard
def init_soundfx(self):
# voices:
# 0: rocket thrust
# 1: warning beep (low fuel)
# 2: non-looping sounds
self.mixer = audiomixer.Mixer(voice_count=3, sample_rate=22050, channel_count=1,
bits_per_sample=16, samples_signed=True)
fruit_jam.audio.play(self.mixer)
wav_file = open("assets/thrust.wav", "rb")
self.thrust_wave = audiocore.WaveFile(wav_file)
wav_file = open("assets/explode.wav","rb")
self.explosion_wave = audiocore.WaveFile(wav_file)
wav_file = open("assets/reward.wav", "rb")
self.reward_wave = audiocore.WaveFile(wav_file)
wav_file = open("assets/beep.wav", "rb")
self.beep_wave = audiocore.WaveFile(wav_file)
self.mixer.voice[0].level = 1.0
self.mixer.voice[1].level = 1.0
self.mixer.voice[2].level = 1.0
# test mixer here
#print("testing mixer")
#self.mixer.voice[0].level = 1.0
#self.mixer.voice[0].play(self.reward_wave,loop=True)
#time.sleep(1)
#print("testing mixer done")
#self.mixer.voice[0].stop()
def init_display(self):
"""Initialize DVI display on Fruit Jam"""
try:
displayio.release_displays()
# Fruit Jam has built-in DVI - no HSTX adapter needed
# Use board-specific pin definitions
fb = picodvi.Framebuffer(
DISPLAY_WIDTH, DISPLAY_HEIGHT,
clk_dp=board.CKP, clk_dn=board.CKN,
red_dp=board.D0P, red_dn=board.D0N,
green_dp=board.D1P, green_dn=board.D1N,
blue_dp=board.D2P, blue_dn=board.D2N,
color_depth=COLOR_DEPTH
)
self.display = framebufferio.FramebufferDisplay(fb)
# Create display groups
self.title_group = displayio.Group(scale=2)
self.help_group = displayio.Group()
self.lander_group = displayio.Group()
self.main_group = displayio.Group()
# Load title screeen
title_bit, title_pal = adafruit_imageload.load(
"assets/title_screen.bmp",
bitmap=displayio.Bitmap,
palette=displayio.Palette
)
self.display_title = displayio.TileGrid(title_bit, x=0, y=0,pixel_shader=title_pal)
self.title_group.append(self.display_title)
font = bitmap_font.load_font("fonts/ter16b.pcf")
self.bb = font.get_bounding_box()
version_label = Label(
font,
color=0x000000,
text= f"version:{VERSION}",
x = self.bb[0], y= DISPLAY_HEIGHT//2 - self.bb[1]
)
self.title_group.append(version_label)
loading_label = Label(
font,
color=0x000000,
text="loading...",
x = DISPLAY_WIDTH//2 - self.bb[0]*11, y = DISPLAY_HEIGHT//2 - self.bb[1]
)
self.title_group.append(loading_label)
self.display.root_group = self.title_group
# Load help screen
help_bit, help_pal = adafruit_imageload.load(
"assets/help_screen.bmp",
bitmap=displayio.Bitmap,
palette=displayio.Palette
)
self.display_help = displayio.TileGrid(help_bit, x=0, y=0,pixel_shader=help_pal)
self.help_group.append(self.display_help)
# gemstone sheet
self.gems_bit, self.gems_pal = adafruit_imageload.load("assets/gemsheet.bmp",
bitmap=displayio.Bitmap,
palette=displayio.Palette)
self.gems_pal.make_transparent(self.gems_bit[0])
# rocket lander setup
self.main_group.append(self.lander_group)
rocket_bit, rocket_pal = adafruit_imageload.load("assets/rocketsheet.bmp",
bitmap=displayio.Bitmap,
palette=displayio.Palette)
rocket_pal.make_transparent(rocket_bit[0])
self.display_lander = displayio.TileGrid(rocket_bit, pixel_shader=rocket_pal,
width=1, height=1,
tile_height=LANDER_HEIGHT, tile_width=LANDER_WIDTH,
default_tile=0,
x=DISPLAY_WIDTH//2 - LANDER_WIDTH//2, y=-LANDER_HEIGHT)
self.lander_group.append(self.display_lander)
# explosion animation
explosion_bit, explosion_pal = adafruit_imageload.load("assets/explosionsheet.bmp",
bitmap=displayio.Bitmap,
palette=displayio.Palette)
explosion_pal.make_transparent(explosion_bit[0])
self.display_explosion = displayio.TileGrid(explosion_bit,
pixel_shader=explosion_pal,
width=1, height=1,
tile_height=48, tile_width=48,
default_tile=0,
x=DISPLAY_WIDTH//2 , y=DISPLAY_HEIGHT//2)
self.lander_group.append(self.display_explosion)
self.display_explosion.hidden = True
# self.display_thrust1 animation
self.display_thrust1_bit, self.display_thrust1_pal = adafruit_imageload.load("assets/thrust1sheet.bmp",
bitmap=displayio.Bitmap,
palette=displayio.Palette)
self.display_thrust1_pal.make_transparent(self.display_thrust1_bit[0])
self.display_thrust1 = displayio.TileGrid(self.display_thrust1_bit,
pixel_shader=self.display_thrust1_pal,
width=1, height=1,
tile_height=32, tile_width=32,
default_tile=0,
x=DISPLAY_WIDTH//2 - LANDER_WIDTH//2, y=-LANDER_HEIGHT)
self.lander_group.append(self.display_thrust1)
self.display_thrust1.hidden = True
self.display_thrust2_bit, self.display_thrust2_pal = adafruit_imageload.load("assets/thrust2sheet.bmp",
bitmap=displayio.Bitmap,
palette=displayio.Palette)
self.display_thrust2_pal.make_transparent(self.display_thrust2_bit[0])
self.display_thrust2 = displayio.TileGrid(self.display_thrust2_bit,
pixel_shader=self.display_thrust2_pal,
width=1, height=1,
tile_height=48, tile_width=48,
default_tile=0,
x=DISPLAY_WIDTH//2 - LANDER_WIDTH//2, y=-LANDER_HEIGHT)
self.lander_group.append(self.display_thrust2)
self.display_thrust2.hidden = True
self.display_thrust3_bit, self.display_thrust3_pal = adafruit_imageload.load("assets/thrust3sheet.bmp",
bitmap=displayio.Bitmap,
palette=displayio.Palette)
self.display_thrust3_pal.make_transparent(self.display_thrust3_bit[0])
self.display_thrust3 = displayio.TileGrid(self.display_thrust3_bit,
pixel_shader=self.display_thrust3_pal,
width=1, height=1,
tile_height=48, tile_width=48,
default_tile=0,
x=DISPLAY_WIDTH//2 - LANDER_WIDTH//2, y=-LANDER_HEIGHT)
self.lander_group.append(self.display_thrust3)
self.display_thrust3.hidden = True
self.display_thruster = False
# panel labels
self.panel_group = displayio.Group()
self.main_group.append(self.panel_group)
#print("bb:",self.bb)
self.score_label = Label(
font,
color=0x00ff00,
text= "SCORE",
x = self.bb[0], y= self.bb[1]
)
self.panel_group.append(self.score_label)
self.score_text = Label(
font,
color=0x00ff00,
x=self.bb[0]*9, y= self.bb[1]
)
self.panel_group.append(self.score_text)
self.score_text.text = ""
self.time_label = Label(
font,
color=0x00ff00,
text= "TIME",
x = self.bb[0], y= self.bb[1]*3
)
self.panel_group.append(self.time_label)
self.time_text = Label(
font,
color=0x00ff00,
x=self.bb[0]*9, y= self.bb[1]*3
)
self.panel_group.append(self.time_text)
self.time_text.text = "00:00"
self.time_to_beat_label = Label(
font,
color=0x00ff00,
text= "BEST",
x = self.bb[0], y= self.bb[1]*4
)
self.panel_group.append(self.time_to_beat_label)
self.time_to_beat_label.hidden = True
self.time_to_beat_text = Label(
font,
color=0x00ff00,
x=self.bb[0]*9, y= self.bb[1]*4
)
self.time_to_beat_text.hidden = True
self.panel_group.append(self.time_to_beat_text)
self.fuel_label = Label(
font,
color=0x00ff00,
text= "FUEL",
x = self.bb[0], y= self.bb[1]*2
)
self.panel_group.append(self.fuel_label)
self.fuel_text = Label(
font,
color=0x00ff00,
x=self.bb[0]*8, y= self.bb[1]*2
)
self.panel_group.append(self.fuel_text)
self.fuel_text.text = "000000"
self.velocityx_label = Label(
font,
color=0x00ff00,
text= "HORIZONTAL SPEED",
x = DISPLAY_WIDTH - self.bb[0]*24, y= self.bb[1]
)
self.panel_group.append(self.velocityx_label)
self.velocityx_text = Label(
font,
color=0x00ff00,
x=DISPLAY_WIDTH - self.bb[0]*6, y= self.bb[1]
)
self.panel_group.append(self.velocityx_text)
self.velocityx_text.text = "000.0"
self.velocityy_label = Label(
font,
color=0x00ff00,
text= "VERTICAL SPEED",
x = DISPLAY_WIDTH - self.bb[0]*24, y= self.bb[1]*2
)
self.panel_group.append(self.velocityy_label)
self.velocityy_text = Label(
font,
color=0x00ff00,
x=DISPLAY_WIDTH - self.bb[0]*6, y= self.bb[1]*2
)
self.panel_group.append(self.velocityy_text)
self.velocityy_text.text = "000.0"
self.rotation_label = Label(
font,
color=0x00ff00,
text= "ROTATION",
x = DISPLAY_WIDTH - self.bb[0]*24, y= self.bb[1]*3
)
self.panel_group.append(self.rotation_label)
self.rotation_text = Label(
font,
color=0x00ff00,
x=DISPLAY_WIDTH - self.bb[0]*6, y= self.bb[1]*3
)
self.panel_group.append(self.rotation_text)
self.rotation_text.text = "000.0"
self.altitude_label = Label(
font,
color=0x00ff00,
text= "ALTITUDE",
x = DISPLAY_WIDTH - self.bb[0]*24, y= self.bb[1]*4
)
self.panel_group.append(self.altitude_label)
self.altitude_text = Label(
font,
color=0x00ff00,
x=DISPLAY_WIDTH - self.bb[0]*6, y= self.bb[1]*4
)
self.panel_group.append(self.altitude_text)
self.altitude_text.text = "000.0"
# arrows
arrows_bit, arrows_pal = adafruit_imageload.load("assets/arrows.bmp",
bitmap=displayio.Bitmap,
palette=displayio.Palette)
arrows_pal.make_transparent(arrows_bit[0])
self.arrowh = displayio.TileGrid(arrows_bit, pixel_shader=arrows_pal,
width=1, height=1,
tile_height=12, tile_width=8,
default_tile=0,
x=DISPLAY_WIDTH - self.bb[0]*7, y= self.bb[1]-4)
self.panel_group.append(self.arrowh)
self.arrowv = displayio.TileGrid(arrows_bit, pixel_shader=arrows_pal,
width=1, height=1,
tile_height=12, tile_width=8,
default_tile=0,
x=DISPLAY_WIDTH - self.bb[0]*7, y= self.bb[1]*2-4)
self.panel_group.append(self.arrowv)
self.arrowr = displayio.TileGrid(arrows_bit, pixel_shader=arrows_pal,
width=1, height=1,
tile_height=12, tile_width=8,
default_tile=0,
x=DISPLAY_WIDTH - self.bb[0]*7, y= self.bb[1]*3-4)
self.panel_group.append(self.arrowr)
self.pause_label = Label(
font,
scale=4,
color=0x00ff00,
outline_color = 0x004400,
text= "PAUSED",
x = DISPLAY_WIDTH//2 - len("PAUSED")*self.bb[0]*2,
y= DISPLAY_HEIGHT // 2 # - self.bb[1]*4
)
self.pause_label.hidden = True
self.panel_group.append(self.pause_label)
key_label = "PRESS THRUST TO CONTINUE"
self.wait_label = Label(
font,
scale=2,
color=0x00ff00,
outline_color = 0x004400,
text= key_label,
x = DISPLAY_WIDTH//2 - len(key_label)*self.bb[0],
y = DISPLAY_HEIGHT - self.bb[1]*2
)
self.wait_label.hidden = True
self.panel_group.append(self.wait_label)
# message text labels
self.message_group = displayio.Group()
self.message_group.hidden = True
font = bitmap_font.load_font("fonts/ter16b.pcf")
bb = font.get_bounding_box()
for i in range(6):
self.message_label.append(Label(
#self.message_label.append(Label(
font,
scale=2,
color=0x00ff00,
outline_color = 0x004400,
text= "",
x = DISPLAY_WIDTH//2 - self.bb[0]*38,
y= DISPLAY_HEIGHT // 2 - self.bb[1]*(2-i)*2
))
self.message_label[i].hidden = False
self.message_group.append(self.message_label[i])
self.getready_group = displayio.Group(scale=2)
getready_bitmap = displayio.Bitmap(320, 240, 1)
getready_palette = displayio.Palette(4)
getready_palette[0] = 0x000000
getready_palette[1] = 0x00FF00
getready_palette[2] = 0x555555
getready_palette[3] = 0xAAAAAA
display_getready = displayio.TileGrid(getready_bitmap, x=0, y=0,pixel_shader=getready_palette)
self.getready_group.append(display_getready)
tmessage = Label(
font,
scale=1,
color=0x00ff00,
outline_color = 0x004400,
text= "Preparing mission...".upper(),
x = self.bb[0],
y= (240 - self.bb[1])//2
)
self.getready_group.append(tmessage)
self.mission_group = displayio.Group(scale=2)
self.load_mission_list()
mission_bitmap = displayio.Bitmap(320, 240, 1)
mission_palette = displayio.Palette(4)
mission_palette[0] = 0x000000
mission_palette[1] = 0x00FF00
mission_palette[2] = 0x555555
mission_palette[3] = 0xAAAAAA
mission_label = []
mission_label_time = []
display_title = displayio.TileGrid(mission_bitmap, x=0, y=0,pixel_shader=mission_palette)
self.mission_group.append(display_title)
bb = font.get_bounding_box()
mission_label.append(Label(
font,
scale=1,
color=0x00ff00,
outline_color = 0x004400,
text= "CHOOSE YOUR MISSION:".upper(),
x = self.bb[0],
y= self.bb[1]
))
mission_label[0].hidden = False
self.mission_group.append(mission_label[0])
mission_label_time.append(Label(
font,
scale=1,
color=0x00ff00,
outline_color = 0x004400,
text= "Best Time".upper(),
x = self.bb[0] + self.bb[0]*28,
y= self.bb[1]*2
))
mission_label_time[0].hidden = False
self.mission_group.append(mission_label_time[0])
self.load_time_list()
i = 1
for m in self.missions:
print("mission:",m["mission"])
time = "--:--"
for t in self.times:
if t["id"] == m["id"]:
time = f"{int(t["time"])//60:02d}:{int(t["time"])%60:02d}"
mission_label.append(Label(
font,
scale=1,
color=0x00ff00,
outline_color = 0x004400,
text= f"{m["mission"].upper():<30} " + time,
x = self.bb[0]*2,
y= self.bb[1]*i+self.bb[1]*2
))
mission_label[i].hidden = False
self.mission_group.append(mission_label[i])
i += 1
print("Fruit Jam DVI display initialized successfully")
return True
except Exception as e:
print(f"Failed to initialize DVI display: {e}")
return False
def display_message(self,message):
print(f"display_message")
self.fuel_text.hidden = False
self.clear_message() # clear previous message, if any
lines = []
tlines = message.split("\n")
for t in tlines:
t2 = wrap_text_to_lines(t, 38)
for t3 in t2:
print(t3)
lines.append(t3)
#lines = wrap_text_to_lines(message, 30)
print(lines)
for i in range(6):
#self.message_label[i].hidden = False
if len(lines) > i:
#self.message_label[i].x = DISPLAY_WIDTH//2 - len(lines[i])*self.bb[0]
self.message_label[i].text = lines[i]
self.message_group.hidden = False
def clear_message(self):
self.message_group.hidden = True
for i in range(6):
#self.message_label[i].hidden = True
self.message_label[i].text = ""
def wait_for_key(self):
self.wait_label.hidden = False
gc.enable()
while True:
buff = self.get_button()
if buff != None:
if buff[BTN_ABXY_INDEX] == 0x2F: # A button pressed
break
buff = self.get_key()
#buff = None
if buff != None:
if 22 in buff: # "s" thrust
break
time.sleep(.001)
self.wait_label.hidden = True
gc.disable()
def update_score(self):
minetotal = 0
minecount = 0
for p in range(len(self.pages)):
for m in self.mines[p]:
#print(f"{self.mines[p]}")
if m["type"] == "m":
minetotal += 1
if m["count"] == 0:
minecount += 1
#minetotal += len(self.mines[p])
#print(f"minetotal: {minetotal}")
self.score_text.text = f"{minecount:02d}/{minetotal:02d}"
def reports_equal(self, report_a, report_b, check_length=None):
"""
Test if two reports are equal. If check_length is provided then
check for equality in only the first check_length number of bytes.
:param report_a: First report data
:param report_b: Second report data
:param check_length: How many bytes to check
:return: True if the reports are equal, otherwise False.
"""
if (
report_a is None
and report_b is not None
or report_b is None
and report_a is not None
):
return False
length = len(report_a) if check_length is None else check_length
for _ in range(length):
if report_a[_] != report_b[_]:
return False
return True
def init_controller(self):
# find controller device
device = None
for d in usb.core.find(find_all=True):
#print(
# f"found device {d.manufacturer}, {d.product}, {d.serial_number}"
#)
if d.product[:11] == "USB gamepad":
device = d
print("found gamepad")
break
if device is None:
print("no gamepad found")
return False # controller not found
# set configuration so we can read data from it
self.controller = device
self.controller.set_configuration()
# Test to see if the kernel is using the device and detach it.
if self.controller.is_kernel_driver_active(0):
self.controller.detach_kernel_driver(0)
self.idle_state = None
self.prev_state = None
return True
def init_keyboard(self):
# scan for connected USB devices
for device in usb.core.find(find_all=True):
if device.product[:12] == "USB Keyboard":
# check for boot keyboard endpoints on this device
self.kbd_interface_index, self.kbd_endpoint_address = (
adafruit_usb_host_descriptors.find_boot_keyboard_endpoint(device)
)
# if a boot keyboard interface index and endpoint address were found
if self.kbd_interface_index is not None and self.kbd_interface_index is not None:
self.keyboard = device
# detach device from kernel if needed
if self.keyboard.is_kernel_driver_active(0):
self.keyboard.detach_kernel_driver(0)
# set the configuration so it can be used
self.keyboard.set_configuration()
if self.keyboard is None:
return False
return True
def print_keyboard_report(self,report_data):
# Dictionary for modifier keys (first byte)
modifier_dict = {
0x01: "LEFT_CTRL",
0x02: "LEFT_SHIFT",
0x04: "LEFT_ALT",
0x08: "LEFT_GUI",
0x10: "RIGHT_CTRL",
0x20: "RIGHT_SHIFT",
0x40: "RIGHT_ALT",
0x80: "RIGHT_GUI",
}
# Dictionary for key codes (main keys)
key_dict = {
0x04: "A",
0x05: "B",
0x06: "C",
0x07: "D",
0x08: "E",
0x09: "F",
0x0A: "G",
0x0B: "H",
0x0C: "I",
0x0D: "J",
0x0E: "K",
0x0F: "L",
0x10: "M",
0x11: "N",
0x12: "O",
0x13: "P",
0x14: "Q",
0x15: "R",
0x16: "S",
0x17: "T",
0x18: "U",
0x19: "V",
0x1A: "W",
0x1B: "X",
0x1C: "Y",
0x1D: "Z",
0x1E: "1",
0x1F: "2",
0x20: "3",
0x21: "4",
0x22: "5",
0x23: "6",
0x24: "7",
0x25: "8",
0x26: "9",
0x27: "0",
0x28: "ENTER",
0x29: "ESC",
0x2A: "BACKSPACE",
0x2B: "TAB",
0x2C: "SPACE",
0x2D: "MINUS",
0x2E: "EQUAL",
0x2F: "LBRACKET",
0x30: "RBRACKET",
0x31: "BACKSLASH",
0x33: "SEMICOLON",
0x34: "QUOTE",
0x35: "GRAVE",
0x36: "COMMA",
0x37: "PERIOD",
0x38: "SLASH",
0x39: "CAPS_LOCK",
0x4F: "RIGHT_ARROW",
0x50: "LEFT_ARROW",
0x51: "DOWN_ARROW",
0x52: "UP_ARROW",
}
# Add F1-F12 keys to the dictionary
for i in range(12):
key_dict[0x3A + i] = f"F{i + 1}"
# First byte contains modifier keys
modifiers = report_data[0]
# Print modifier keys if pressed
if modifiers > 0:
print("Modifiers:", end=" ")
# Check each bit for modifiers and print if pressed
for bit, name in modifier_dict.items():
if modifiers & bit:
print(name, end=" ")
print()
# Bytes 2-7 contain up to 6 key codes (byte 1 is reserved)
keys_pressed = False
for i in range(2, 8):
key = report_data[i]
# Skip if no key or error rollover
if key in {0, 1}:
continue
if not keys_pressed:
print("Keys:", end=" ")
keys_pressed = True
# Print key name based on dictionary lookup
if key in key_dict:
print(key_dict[key], end=" ")
else:
# For keys not in the dictionary, print the HID code
print(f"0x{key:02X}", end=" ")
if keys_pressed:
print()
elif modifiers == 0:
print("No keys pressed")
def get_button(self):
press = False
#self.controller = None # disable for now, need to fix frame rate issue
if self.controller is not None:
# buffer to hold 64 bytes
buf = array.array("B", [0] * 64)
try:
timer1 = time.monotonic()
count = self.controller.read(0x81, buf)
timer2 = time.monotonic()
#if self.fcount%20 == 0:
# print(f"controller read time: {timer2 - timer1}")
#print(f"read: {count} {buf}")
except usb.core.USBTimeoutError:
return None
if self.idle_state is None:
self.idle_state = buf[:]
if not self.reports_equal(buf, self.prev_state, 8) and not self.reports_equal(buf, self.idle_state, 8):
press = False
if buf[BTN_DPAD_UPDOWN_INDEX] == 0x0:
print("D-Pad UP pressed")
press = True
elif buf[BTN_DPAD_UPDOWN_INDEX] == 0xFF:
print("D-Pad DOWN pressed")
press = True
if buf[BTN_DPAD_RIGHTLEFT_INDEX] == 0:
print("D-Pad LEFT pressed")
press = True
elif buf[BTN_DPAD_RIGHTLEFT_INDEX] == 0xFF:
print("D-Pad RIGHT pressed")
press = True
if buf[BTN_ABXY_INDEX] == 0x2F:
print("A pressed")
press = True
elif buf[BTN_ABXY_INDEX] == 0x4F:
print("B pressed")
press = True
elif buf[BTN_ABXY_INDEX] == 0x1F:
print("X pressed")
press = True
elif buf[BTN_ABXY_INDEX] == 0x8F:
print("Y pressed")
press = True
if buf[BTN_OTHER_INDEX] == 0x01:
print("L shoulder pressed")
press = True
elif buf[BTN_OTHER_INDEX] == 0x02:
print("R shoulder pressed")
press = True
elif buf[BTN_OTHER_INDEX] == 0x10:
print("SELECT pressed")
press = True
elif buf[BTN_OTHER_INDEX] == 0x20:
print("START pressed")
press = True
self.prev_state = buf[:]
else:
self.idle_state = buf[:]
#press = True
if press:
self.last_input = "c"
return buf
else:
return None
def get_key(self):
# try to read data from the keyboard
if self.keyboard is not None:
buff = array.array("b", [0] * 8)
try:
count = self.keyboard.read(self.kbd_endpoint_address, buff, timeout=10)
# if there is no data it will raise USBTimeoutError
except usb.core.USBTimeoutError:
# Nothing to do if there is no data for this keyboard
return None
except usb.core.USBError as e:
print(f"usb.core.USBError error: {e}")
# reset keyboard if we get this error
if not self.init_keyboard():
print("Failed to initialize keyboard or no keyboard attached")
#sys.exit()
# unknown error, ignore
return None
self.print_keyboard_report(buff)
# convert from byte to int array so "in" operator will work
format_string = 'b' * len(buff)
signed_int_tuple = struct.unpack(format_string, buff)
newbuff = list(signed_int_tuple)
self.last_input = "k"
if newbuff[2] == 0x6 and newbuff[0] & 0x11 != 0:
print("Ctrl-C detected, aborting game")
sys.exit()
return newbuff
def crash_animation(self):
self.engine_shutoff()
#fruit_jam.audio.play(self.explosion_wave, loop=False)
self.mixer.voice[2].play(self.explosion_wave,loop=False)
self.mixer.voice[0].stop()
self.mixer.voice[1].stop()
#animation here
self.lockout = True
self.display_explosion.hidden = False
self.display_thrust1.hidden = True
self.display_thrust2.hidden = True
self.display_thrust3.hidden = True
for i in range(4,24):
t = time.monotonic()
self.display_explosion[0] = i
self.tick()
if i == 12:
self.display_lander.hidden = True
#while time.monotonic() - t < FRAME_RATE:
# time.sleep(0.001)
time.sleep(FRAME_RATE)
self.display_explosion.hidden = True
#animate for an additional 2 seconds
for i in range(20):
t=time.monotonic()
self.tick()
time.sleep(FRAME_RATE)
#while time.monotonic() - t < .1: #tweak for frame rate slower than expected
# time.sleep(0.001)
def collision_detected(self):
# check for crash other than ground (lava for now)
#if len(self.volcanos) > 0 and len(self.volcanos[self.tpage]) > 0:
if len(self.volcanos) > self.tpage:
p1 = (self.display_lander.x+4) // TREZ
p2 = (self.display_lander.x+LANDER_WIDTH -4)//TREZ
p = []
for i in range(p1,p2+1):
p.append(i)
c = 0
for v in self.volcanos[self.tpage]:
#print("volcanos:",v, p)
if v["pos"] in p:
#print("debug: near volcano",v,c,p)
for i in range(LAVA_COUNT):
if self.display_lava[self.tpage][c][i].hidden == False:
if (
self.display_lander.y <= self.display_lava[self.tpage][c][i].y and
self.display_lava[self.tpage][c][i].y + self.display_lava[self.tpage][c][i].tile_height
<= self.display_lander.y) or (
self.display_lava[self.tpage][c][i].y <= self.display_lander.y and
self.display_lava[self.tpage][c][i].y + self.display_lava[self.tpage][c][i].tile_height
>= self.display_lander.y) or (
self.display_lava[self.tpage][c][i].y <= self.display_lander.y + LANDER_HEIGHT and
self.display_lava[self.tpage][c][i].y + self.display_lava[self.tpage][c][i].tile_height
>= self.display_lander.y + LANDER_HEIGHT):
self.crashed = True
self.game_over = True
print("crashed! (lava)")
reason = "You were hit by lava."
c += 1
if self.crashed:
self.game_over = True
self.display_thrust1.hidden = True
self.display_thrust2.hidden = True