forked from TheKitty/pac-fruitjam
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode.py
More file actions
2121 lines (1805 loc) · 70.2 KB
/
code.py
File metadata and controls
2121 lines (1805 loc) · 70.2 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
"""
Pac-Man Clone for Adafruit Fruit Jam
CircuitPython - 640x480 display, SNES USB controller, I2S audio
"""
import sys
import gc
import time
import random
import os
import board
import displayio
import audiobusio
import supervisor
import synthio
import json
import bitmaptools
from traceback import print_exception
from adafruit_fruitjam.peripherals import (
Peripherals,
request_display_config,
VALID_DISPLAY_SIZES,
)
import adafruit_imageload
import relic_usb_host_gamepad
# get Fruit Jam OS config if available
try:
import launcher_config
config = launcher_config.LauncherConfig()
except ImportError:
config = None
try:
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text import label
except ImportError:
bitmap_font = None
label = None
# =============================================================================
# CONSTANTS
# =============================================================================
# Tile dimensions
TILE_SIZE = 6
TILE_SIZE_X_2 = TILE_SIZE * 2
TILE_SIZE__2 = TILE_SIZE // 2
# Maze dimensions in tiles
MAZE_COLS = 28
MAZE_ROWS = 31
# Game area dimensions (from sprite sheet)
GAME_WIDTH = MAZE_COLS * TILE_SIZE
GAME_HEIGHT = MAZE_ROWS * TILE_SIZE
# Screen dimensions (Fruit Jam native)
if (SCREEN_WIDTH := os.getenv("CIRCUITPY_DISPLAY_WIDTH")) is not None:
SCREEN_HEIGHT = next((h for w, h in VALID_DISPLAY_SIZES if SCREEN_WIDTH == w))
else:
SCREEN_WIDTH = 320
SCREEN_HEIGHT = 240
# Scale factor for display (2x looks good on 640x480)
SCORE_SCALE = GAME_SCALE = round(SCREEN_WIDTH / 320)
# Force lower resolution for better performance
if SCORE_SCALE > 1:
SCREEN_WIDTH //= SCORE_SCALE
SCREEN_HEIGHT //= SCORE_SCALE
SCORE_SCALE = GAME_SCALE = 1
# SCORE_SCALE and GAME_SCALE will always be 1 in the current version
# but we'll leave the old code for future screen flexibility
# Display dimensions
DISPLAY_ROTATION = os.getenv("CIRCUITPY_DISPLAY_ROTATION", 0)
DISPLAY_VERTICAL = DISPLAY_ROTATION in (90, 270) # Tate mode / vertical orientation
DISPLAY_WIDTH = SCREEN_HEIGHT if DISPLAY_VERTICAL else SCREEN_WIDTH
DISPLAY_HEIGHT = SCREEN_WIDTH if DISPLAY_VERTICAL else SCREEN_HEIGHT
# Offset to position game on right side of screen
# Right side: 640 - (224*2) = 192 pixels from right edge
OFFSET_X = int((DISPLAY_WIDTH - GAME_WIDTH * GAME_SCALE) // 2)
OFFSET_Y = int((DISPLAY_HEIGHT - GAME_HEIGHT * GAME_SCALE) // 2) # Centered vertically
# Movement speeds (pixels per frame at game resolution)
PACMAN_SPEED = 1.3 * TILE_SIZE / 8 # was 1.3
GHOST_SPEED_LVL1 = 1.22 * TILE_SIZE / 8 # was 1.22
GHOST_SPEED = GHOST_SPEED_LVL1
GHOST_SPEED_INCFACT = 1.05
GHOST_SPEED_INCPOWER = [0,1,2,2,3,3,4,4,5,5,6,6,7]
FRAME_DELAY = 0.016 # ~60 FPS target was 0.016
# Directions
DIR_NONE = 0
DIR_UP = 1
DIR_DOWN = 2
DIR_LEFT = 3
DIR_RIGHT = 4
# Maze tile types
EMPTY = 0
WALL = 1
DOT = 2
POWER = 3
GATE = 4
# Ghost Modes
MODE_SCATTER = 0
MODE_CHASE = 1
MODE_FRIGHTENED = 2
MODE_EATEN = 3
# Game States
STATE_PLAY = 0
STATE_DYING = 1
STATE_EATING_GHOST = 2
STATE_GAME_OVER = 3
STATE_LEVEL_COMPLETE = 4
STATE_EATING_FRUIT = 5
STATE_READY = 6
MAX_LIVES = 3
# Fruit point values per level
FRUIT_POINTS = [100, 300, 500, 500, 700, 700, 1000, 1000, 2000, 2000, 3000, 3000, 5000]
# Mode Timings (seconds)
MODE_TIMES = [7, 20, 7, 20, 5, 20, 5, 999999]
# Frightened Mode Duration (Frames at 60fps)
FRIGHTENED_DURATION = 360
# High score file path
HIGH_SCORE_FILE = "/saves/highscores.txt"
SETTINGS_FILE = "/saves/pac-fruitjam.json"
# Sprite coordinates
# fmt: off
SPRITE_LIFE = (16 * TILE_SIZE, TILE_SIZE_X_2)
FRUIT_LEVELS = [
(4 * TILE_SIZE, 6 * TILE_SIZE), (6 * TILE_SIZE, 6 * TILE_SIZE),
(8 * TILE_SIZE, 6 * TILE_SIZE), (8 * TILE_SIZE, 6 * TILE_SIZE),
(10 * TILE_SIZE, 6 * TILE_SIZE), (10 * TILE_SIZE, 6 * TILE_SIZE),
(12 * TILE_SIZE, 6 * TILE_SIZE), (12 * TILE_SIZE, 6 * TILE_SIZE),
(14 * TILE_SIZE, 6 * TILE_SIZE), (14 * TILE_SIZE, 6 * TILE_SIZE),
(16 * TILE_SIZE, 6 * TILE_SIZE), (16 * TILE_SIZE, 6 * TILE_SIZE),
(18 * TILE_SIZE, 6 * TILE_SIZE)
]
FRUIT_POINTS_SPRITE = [
(0, 18 * TILE_SIZE), (TILE_SIZE_X_2, 18 * TILE_SIZE),
(4 * TILE_SIZE, 18 * TILE_SIZE), (4 * TILE_SIZE, 18 * TILE_SIZE),
(6 * TILE_SIZE, 18 * TILE_SIZE), (6 * TILE_SIZE, 18 * TILE_SIZE),
(8 * TILE_SIZE, 18 * TILE_SIZE), (8 * TILE_SIZE, 18 * TILE_SIZE),
(8 * TILE_SIZE, 20 * TILE_SIZE), (8 * TILE_SIZE, 20 * TILE_SIZE),
(8 * TILE_SIZE, 22 * TILE_SIZE), (8 * TILE_SIZE, 22 * TILE_SIZE),
(8 * TILE_SIZE, 24 * TILE_SIZE)
]
# =============================================================================
# MAZE DATA
# =============================================================================
MAZE_DATA = [
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1],
[1,0,1,0,0,1,0,1,0,0,0,1,0,1,1,0,1,0,0,0,1,0,1,0,0,1,0,1],
[1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,0,1],
[1,0,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,0,1],
[1,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1],
[1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1],
[0,0,0,0,0,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,0,0,0,0,0],
[0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0],
[0,0,0,0,0,1,0,1,1,0,1,1,1,0,0,1,1,1,0,1,1,0,1,0,0,0,0,0],
[1,1,1,1,1,1,0,1,1,0,1,1,1,0,0,1,1,1,0,1,1,0,1,1,1,1,1,1],
[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1],
[0,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,0,0,0,0,0],
[0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0],
[0,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,0,0,0,0,0],
[1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1],
[1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1],
[1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1],
[1,1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,1],
[1,1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,1],
[1,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1],
[1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1],
[1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
]
POWER_PELLETS = [(1, 3), (26, 3), (1, 23), (26, 23)]
# fmt: on
# =============================================================================
# SOUND ENGINE (I2S + Synthio)
# =============================================================================
class SoundEngine:
"""I2S audio output using TLV320DAC3100 DAC for Pac-Man sounds."""
def __init__(self):
self._enabled = True
self.synth = None
self.peripherals = None
self.audio = None
self.dac = None
self._setup_audio()
# Waka frequencies
self.waka_freq_1 = 261 # C4
self.waka_freq_2 = 392 # G4
self.waka_toggle = False
def _setup_audio(self):
"""Initialize TLV320DAC3100 I2S DAC on Fruit Jam."""
try:
# Fruit Jam TLV320DAC3100 I2S DAC pinout:
# I2S_DIN = GPIO24 (board.I2S_DIN)
# I2S_BCLK = GPIO26 (board.I2S_BCLK)
# I2S_WS = GPIO27 (board.I2S_WS)
# PERIPH_RESET = GPIO22 (board.PERIPH_RESET) - shared with ESP32-C6
self.peripherals = Peripherals(
audio_output=(config.audio_output if config else "speaker"),
safe_volume_limit=(
config.audio_volume_override_danger if config else 0.75
),
sample_rate=22050,
bit_depth=16,
)
self.peripherals.volume = config.audio_volume if config else 0.35
# Try to use adafruit_tlv320 library if available
if self.peripherals.dac is not None:
# Create I2S output
self.audio = self.peripherals.audio
print("TLV320DAC3100 audio initialized with library")
else:
# Fallback: try basic I2S without DAC library
print("TLV320 library not found, trying basic I2S")
self.audio = audiobusio.I2SOut(
board.I2S_BCLK, board.I2S_WS, board.I2S_DIN
)
print("Basic I2S audio initialized")
# Create synthio synthesizer
self.synth = synthio.Synthesizer(sample_rate=22050)
self.audio.play(self.synth)
except Exception as e:
print(f"Audio init error: {e}")
self._enabled = False
def play_tone(self, frequency):
"""Play a simple tone."""
if not self._enabled or not self.synth:
return
try:
self.stop()
self.synth.release_all_then_press(synthio.Note(frequency))
except Exception:
pass
def stop(self):
"""Stop current sound."""
if self.synth:
try:
self.synth.release_all()
except:
pass
def play_waka(self):
"""Play the alternating waka sound."""
freq = self.waka_freq_2 if self.waka_toggle else self.waka_freq_1
self.waka_toggle = not self.waka_toggle
self.play_tone(freq)
def play_death_note(self, frame_idx):
"""Play descending death sound."""
freq = max(500 - (frame_idx * 35), 100)
self.play_tone(freq)
def play_eat_ghost(self):
"""Play ghost eating sound - quick ascending."""
if not self._enabled or not self.synth:
return
for freq in range(200, 800, 150):
self.play_tone(freq)
time.sleep(0.02)
self.stop()
def play_startup(self):
"""Play startup jingle."""
if not self._enabled or not self.synth:
time.sleep(2)
return
T = 0.08
H = T * 2
# fmt: off
melody = [
(494, T), (988, T), (740, T), (622, T), (988, T), (740, T), (622, H),
(523, T), (1047, T), (784, T), (659, T), (1047, T), (784, T), (659, H),
(494, T), (988, T), (740, T), (622, T), (988, T), (740, T), (622, H),
(622, T), (659, T), (698, T), (698, T), (740, T), (784, T),
(784, T), (831, T), (880, T), (988, H)
]
# fmt: on
for freq, duration in melody:
self.play_tone(freq)
time.sleep(duration)
self.stop()
time.sleep(0.015)
self.stop()
@property
def enabled(self) -> bool:
return self._enabled
@enabled.setter
def enabled(self, value: bool) -> None:
if not value and self._enabled:
self.stop()
self._enabled = value
def toggle(self) -> bool:
"""Toggle sound on/off."""
self.enabled = not self.enabled
return self.enabled
def deinit(self):
self.stop()
if self.audio and (self.peripherals is None or self.peripherals.dac is None):
self.audio.stop()
if self.peripherals:
self.peripherals.deinit()
# =============================================================================
# HIGH SCORE MANAGER
# =============================================================================
class HighScoreManager:
"""Manages top 10 high scores saved to file."""
def __init__(self, filepath=HIGH_SCORE_FILE):
self.filepath = filepath
self.scores = []
self._ensure_directory()
self.load()
def _ensure_directory(self):
"""Ensure SAVES directory exists."""
try:
os.listdir("/saves")
except OSError:
try:
os.mkdir("/saves")
except OSError:
pass
def load(self):
"""Load scores from file."""
self.scores = []
try:
with open(self.filepath, "r") as f:
for line in f:
line = line.strip()
if line:
parts = line.split(",")
if len(parts) >= 2:
try:
name = parts[1][:3].upper()
self.scores.append((int(parts[0]), name))
except ValueError:
continue
self.scores.sort(key=lambda x: x[0], reverse=True)
self.scores = self.scores[:10]
except OSError:
self.scores = [(10000, "AAA")] # Default high score
def save(self):
"""Save scores to file."""
try:
with open(self.filepath, "w") as f:
for _score, name in self.scores[:10]:
f.write(f"{_score},{name}\n")
except OSError as e:
print(f"Error saving scores: {e}")
def add_score(self, _score, name="PAC"):
"""Add a new score if it qualifies."""
name = name[:3].upper()
self.scores.append((_score, name))
self.scores.sort(key=lambda x: x[0], reverse=True)
self.scores = self.scores[:10]
self.save()
def is_high_score(self, _score):
"""Check if score qualifies for top 10."""
if len(self.scores) < 10:
return True
return _score > self.scores[-1][0]
def get_high_score(self):
"""Get the highest score."""
return self.scores[0][0] if self.scores else 0
# =============================================================================
# SETTINGS MANAGER
# =============================================================================
class SettingsManager:
"""Manages game settings."""
def __init__(self, sound: SoundEngine, gamepad: relic_usb_host_gamepad.Gamepad, pacman: PacMan, path=SETTINGS_FILE):
self._sound = sound
self._gamepad = gamepad
self._pacman = pacman
self._path = path
# load saved configuration
self._data = {}
try:
with open(self._path, "r") as f:
try:
data = json.load(f)
except (ValueError, AttributeError):
pass
else:
if isinstance(data, dict):
self._data = data
except OSError:
pass
# apply saved configuration
self._sound.enabled = self.sound_enabled
self._gamepad.left_joystick_invert_y = self.left_joystick_invert_y
self._pacman.ms = self.ms_pacman
def save(self):
"""Save settings to file."""
try:
with open(self._path, "w") as f:
json.dump(self._data, f)
except OSError as e:
print(f"Error saving settings: {e}")
@property
def sound_enabled(self) -> bool:
return bool(self._data.get("sound_enabled", True))
@sound_enabled.setter
def sound_enabled(self, value: bool) -> None:
self._data["sound_enabled"] = value
self._sound.enabled = value
@property
def left_joystick_invert_y(self) -> bool:
return bool(self._data.get("left_joystick_invert_y", False))
@left_joystick_invert_y.setter
def left_joystick_invert_y(self, value: bool) -> None:
self._data["left_joystick_invert_y"] = value
self._gamepad.left_joystick_invert_y = value
@property
def ms_pacman(self) -> bool:
return bool(self._data.get("ms_pacman", False))
@ms_pacman.setter
def ms_pacman(self, value: bool) -> None:
self._data["ms_pacman"] = value
self._pacman.ms = value
# =============================================================================
# DISPLAY SETUP
# =============================================================================
# Get the display from board (Fruit Jam has built-in display support)
print("Initializing DVI display...")
try:
# Initialize Fruit Jam display (640x480 DVI)
request_display_config(SCREEN_WIDTH, SCREEN_HEIGHT)
display = supervisor.runtime.display
print(f"Display: {display.width}x{display.height}")
except Exception as e:
print(f"Display init error: {e}")
sys.exit()
finally:
display.rotation = DISPLAY_ROTATION
main_group = displayio.Group()
display.root_group = main_group
# Game group with 2x scaling positioned on right side
game_group = displayio.Group(scale=GAME_SCALE, x=OFFSET_X, y=OFFSET_Y)
# Background for left side (score panel)
score_group = displayio.Group(scale=SCORE_SCALE)
main_group.append(score_group)
if not DISPLAY_VERTICAL:
left_panel_bmp = displayio.Bitmap(
int(OFFSET_X // SCORE_SCALE), int(DISPLAY_HEIGHT // SCORE_SCALE), 1
)
left_panel_palette = displayio.Palette(1)
left_panel_palette[0] = 0x000000
left_panel_bg = displayio.TileGrid(
left_panel_bmp, pixel_shader=left_panel_palette, x=0, y=0
)
score_group.append(left_panel_bg)
# =============================================================================
# LOAD MAZE BACKGROUND
# =============================================================================
_maze_bmp, maze_palette = adafruit_imageload.load("images/maze_empty.bmp")
if TILE_SIZE != 6:
maze_bmp = displayio.Bitmap(GAME_WIDTH, GAME_HEIGHT, 2**_maze_bmp.bits_per_value)
bitmaptools.rotozoom(maze_bmp, _maze_bmp, scale=TILE_SIZE / 6)
else:
maze_bmp = _maze_bmp
maze_bg = displayio.TileGrid(maze_bmp, pixel_shader=maze_palette, x=0, y=0)
game_group.append(maze_bg)
# =============================================================================
# ITEMS GRID (DOTS & POWER PELLETS)
# =============================================================================
items_bitmap = displayio.Bitmap(TILE_SIZE, TILE_SIZE * 3, 3)
# Small Dot (Tile 1)
items_bitmap[TILE_SIZE__2 - 1, TILE_SIZE + TILE_SIZE__2 - 1] = 1
items_bitmap[TILE_SIZE__2, TILE_SIZE + TILE_SIZE__2 - 1] = 1
items_bitmap[TILE_SIZE__2 - 1, TILE_SIZE + TILE_SIZE__2] = 1
items_bitmap[TILE_SIZE__2, TILE_SIZE + TILE_SIZE__2] = 1
# Power Pellet (Tile 2)
for x in range(1, TILE_SIZE - 1):
for y in range(TILE_SIZE_X_2 + 1, TILE_SIZE * 3 - 1):
if x in (1, TILE_SIZE - 2) and y in (TILE_SIZE_X_2 + 1, TILE_SIZE * 3 - 2):
continue
items_bitmap[x, y] = 2
items_palette = displayio.Palette(3)
items_palette[0] = 0x000000
items_palette[1] = 0xFFB8AE
items_palette[2] = 0xFFB8AE
items_palette.make_transparent(0)
items_grid = displayio.TileGrid(
items_bitmap,
pixel_shader=items_palette,
width=MAZE_COLS,
height=MAZE_ROWS,
tile_width=TILE_SIZE,
tile_height=TILE_SIZE,
x=0,
y=0,
)
# Flood fill reachable tiles
reachable = set()
queue = [(14, 23)]
reachable.add((14, 23))
while queue:
cx, cy = queue.pop(0)
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nx, ny = cx + dx, cy + dy
if 0 <= nx < MAZE_COLS and 0 <= ny < MAZE_ROWS:
if MAZE_DATA[ny][nx] != WALL and (nx, ny) not in reachable:
reachable.add((nx, ny))
queue.append((nx, ny))
def reset_dots():
"""Reset all dots."""
global dots_eaten
dots_eaten = 0
for y in range(MAZE_ROWS):
for x in range(MAZE_COLS):
if MAZE_DATA[y][x] == 0 and (x, y) in reachable:
is_ghost_area = (7 <= x <= 20) and (9 <= y <= 19)
is_player_area = (y == 23) and (13 <= x <= 14)
is_tunnel = (y == 14) and (x < 6 or x > 21)
if (x, y) in POWER_PELLETS:
items_grid[x, y] = 2
elif not is_ghost_area and not is_player_area and not is_tunnel:
items_grid[x, y] = 1
else:
items_grid[x, y] = 0
else:
items_grid[x, y] = 0
reset_dots()
game_group.append(items_grid)
# Count total dots
TOTAL_DOTS = sum(
1 for y in range(MAZE_ROWS) for x in range(MAZE_COLS) if items_grid[x, y] in (1, 2)
)
print(f"Total dots: {TOTAL_DOTS}")
# Power pellet covers for blinking
cover_bmp = displayio.Bitmap(TILE_SIZE, TILE_SIZE, 1)
cover_palette = displayio.Palette(1)
cover_palette[0] = 0x000000
pellet_covers = []
for tx, ty in POWER_PELLETS:
tg = displayio.TileGrid(
cover_bmp, pixel_shader=cover_palette, x=tx * TILE_SIZE, y=ty * TILE_SIZE
)
tg.hidden = True
game_group.append(tg)
pellet_covers.append(tg)
# =============================================================================
# LOAD SPRITE SHEET
# =============================================================================
_sprite_sheet, sprite_palette = adafruit_imageload.load("images/sprites.bmp")
if TILE_SIZE != 6:
sprite_sheet = displayio.Bitmap(
_sprite_sheet.width * TILE_SIZE // 6,
_sprite_sheet.height * TILE_SIZE // 6,
2**_sprite_sheet.bits_per_value,
)
bitmaptools.rotozoom(sprite_sheet, _sprite_sheet, scale=TILE_SIZE / 6)
else:
sprite_sheet = _sprite_sheet
sprite_palette.make_transparent(0)
gc.collect()
# =============================================================================
# PAC-MAN CLASS
# =============================================================================
class PacMan:
"""Pac-Man player character."""
# TILE_SIZE = 6: 0, 6, 12, 18, 24, 30, 36, ... Faster than doing the math each time
_dir = [(i * TILE_SIZE) for i in range(27)]
FRAMES = {
DIR_RIGHT: [(0, 0), (_dir[2], 0), (_dir[4], 0)],
DIR_LEFT: [(0, _dir[2]), (_dir[2], _dir[2]), (_dir[4], 0)],
DIR_UP: [(0, _dir[4]), (_dir[2], _dir[4]), (_dir[4], 0)],
DIR_DOWN: [(0, _dir[6]), (_dir[2], _dir[6]), (_dir[4], 0)],
}
MS_FRAMES = {
DIR_RIGHT: [(0, _dir[26]), (_dir[2], _dir[26]), (_dir[4], _dir[26])],
DIR_LEFT: [(_dir[6], _dir[26]), (_dir[8], _dir[26]), (_dir[10], _dir[26])],
DIR_UP: [(_dir[12], _dir[26]), (_dir[14], _dir[26]), (_dir[16], _dir[26])],
DIR_DOWN: [(_dir[18], _dir[26]), (_dir[20], _dir[26]), (_dir[22], _dir[26])],
}
DEATH_FRAMES = [((TILE_SIZE * 6) + i * TILE_SIZE_X_2, 0) for i in range(11)]
SCORE_FRAMES = [
(0, _dir[16]),
(_dir[2], _dir[16]),
(_dir[4], _dir[16]),
(_dir[6], _dir[16]),
]
def __init__(self):
print("sprite height:", sprite_sheet.height)
self.sprite = displayio.TileGrid(
sprite_sheet,
pixel_shader=sprite_palette,
width=1,
height=1,
tile_width=TILE_SIZE_X_2,
tile_height=TILE_SIZE_X_2,
)
self._ms = False
self.reset()
def reset(self):
self.tile_x = 14
self.tile_y = 23
self.x = self.tile_x * TILE_SIZE - TILE_SIZE__2
self.y = self.tile_y * TILE_SIZE - TILE_SIZE__2
self.direction = DIR_NONE
self.next_direction = DIR_NONE
self.anim_frame = 0
self.anim_timer = 0
self.saved_x = 0
self.saved_y = 0
self.set_frame(DIR_RIGHT, 0)
self.update_sprite_pos()
@property
def ms(self) -> bool:
return self._ms
@ms.setter
def ms(self, value: bool) -> None:
self._ms = value
maze_palette[1] = 0xE01000 if value else 0x2121FF
maze_palette[3] = 0xFFB694 if value else 0x000000
def _set_tile(self, fx, fy):
self.sprite[0, 0] = int((fy // TILE_SIZE_X_2) * (
sprite_sheet.width // TILE_SIZE_X_2
) + (fx // TILE_SIZE_X_2))
def set_frame(self, direction, frame_idx):
if direction == DIR_NONE:
direction = DIR_RIGHT
if self._ms:
frames = self.MS_FRAMES.get(direction, self.MS_FRAMES[DIR_RIGHT])
else:
frames = self.FRAMES.get(direction, self.FRAMES[DIR_RIGHT])
self._set_tile(*frames[frame_idx % 3])
def set_death_frame(self, frame_idx):
if frame_idx >= len(self.DEATH_FRAMES):
frame_idx = len(self.DEATH_FRAMES) - 1
self._set_tile(*self.DEATH_FRAMES[frame_idx])
def set_score_frame(self, score_idx):
if score_idx >= len(self.SCORE_FRAMES):
score_idx = len(self.SCORE_FRAMES) - 1
self._set_tile(*self.SCORE_FRAMES[score_idx])
def update_sprite_pos(self):
self.sprite.x = int(self.x)
self.sprite.y = int(self.y)
def can_move(self, direction):
next_x, next_y = self.x, self.y
if direction == DIR_UP:
next_y -= PACMAN_SPEED
elif direction == DIR_DOWN:
next_y += PACMAN_SPEED
elif direction == DIR_LEFT:
next_x -= PACMAN_SPEED
elif direction == DIR_RIGHT:
next_x += PACMAN_SPEED
else:
print(
f"Checked if could move in None? {direction} direction - Returned False!"
)
return False
center_x = next_x + TILE_SIZE
center_y = next_y + TILE_SIZE
if center_x < 8 or center_x > (GAME_WIDTH - TILE_SIZE):
if direction in (DIR_UP, DIR_DOWN):
print(
"Tried to move up or down but center is too far left or right - Returned False"
)
return False
if next_x < -TILE_SIZE or next_x >= (GAME_WIDTH - TILE_SIZE):
# Using teleport tunnel
return True
SENSOR_OFFSET = 3
if direction == DIR_UP:
check_x, check_y = center_x, center_y - SENSOR_OFFSET
elif direction == DIR_DOWN:
check_x, check_y = center_x, center_y + SENSOR_OFFSET
elif direction == DIR_LEFT:
check_x, check_y = center_x - SENSOR_OFFSET, center_y
elif direction == DIR_RIGHT:
check_x, check_y = center_x + SENSOR_OFFSET, center_y
tx = int(check_x // TILE_SIZE)
ty = int(check_y // TILE_SIZE)
# print(f"CAN_MOVE: x,y: {self.x},{self.y} next_x,y: {next_x},{next_y}
# check_x,y: {check_x},{check_y} tx,ty: {tx},{ty}")
if tx < 0 or tx >= MAZE_COLS:
return ty == 14
if ty < 0 or ty >= MAZE_ROWS:
return False
if ty == 12 and tx in (13, 14):
return False
return MAZE_DATA[ty][tx] != WALL
def can_turn(self, direction):
target_tx, target_ty = int(self.tile_x), int(self.tile_y)
if direction == DIR_UP:
target_ty -= 1
elif direction == DIR_DOWN:
target_ty += 1
elif direction == DIR_LEFT:
target_tx -= 1
elif direction == DIR_RIGHT:
target_tx += 1
if target_tx < 0 or target_tx >= MAZE_COLS:
return target_ty == 14
if target_ty < 0 or target_ty >= MAZE_ROWS:
return False
if target_ty == 12 and target_tx in (13, 14):
return False
return MAZE_DATA[target_ty][target_tx] != WALL
def at_tile_center(self):
center_x = self.x + TILE_SIZE
center_y = self.y + TILE_SIZE
dist_x = abs((center_x - TILE_SIZE__2) % TILE_SIZE)
dist_y = abs((center_y - TILE_SIZE__2) % TILE_SIZE)
dist_x = min(dist_x, TILE_SIZE - dist_x)
dist_y = min(dist_y, TILE_SIZE - dist_y)
return dist_x <= PACMAN_SPEED and dist_y <= PACMAN_SPEED
def is_opposite(self, dir1, dir2):
return (
(dir1 == DIR_UP and dir2 == DIR_DOWN)
or (dir1 == DIR_DOWN and dir2 == DIR_UP)
or (dir1 == DIR_LEFT and dir2 == DIR_RIGHT)
or (dir1 == DIR_RIGHT and dir2 == DIR_LEFT)
)
def update(self):
# Handle reversals
if self.next_direction != DIR_NONE and self.is_opposite(
self.direction, self.next_direction
):
# We were just coming from this direction so it should be valid
#if self.can_move(self.next_direction):
self.direction = self.next_direction
self.next_direction = DIR_NONE
# Start from stop
elif self.direction == DIR_NONE and self.next_direction != DIR_NONE:
if self.can_move(self.next_direction):
self.direction = self.next_direction
self.next_direction = DIR_NONE
# Handle turns at intersections
elif self.at_tile_center():
if (
self.next_direction != DIR_NONE
and self.next_direction != self.direction
):
if self.can_turn(self.next_direction):
center_x = self.x + TILE_SIZE
center_y = self.y + TILE_SIZE
tile_x = int(center_x // TILE_SIZE)
tile_y = int(center_y // TILE_SIZE)
self.x = tile_x * TILE_SIZE + TILE_SIZE__2 - TILE_SIZE
self.y = tile_y * TILE_SIZE + TILE_SIZE__2 - TILE_SIZE
self.direction = self.next_direction
self.next_direction = DIR_NONE
if self.direction != DIR_NONE and not self.can_move(self.direction):
center_x = self.x + TILE_SIZE
center_y = self.y + TILE_SIZE
tile_x = int(center_x // TILE_SIZE)
tile_y = int(center_y // TILE_SIZE)
self.x = tile_x * TILE_SIZE + TILE_SIZE__2 - TILE_SIZE
self.y = tile_y * TILE_SIZE + TILE_SIZE__2 - TILE_SIZE
self.direction = DIR_NONE
# Move
if self.direction != DIR_NONE:
if self.can_move(self.direction):
if self.direction == DIR_UP:
self.y -= PACMAN_SPEED
elif self.direction == DIR_DOWN:
self.y += PACMAN_SPEED
elif self.direction == DIR_LEFT:
self.x -= PACMAN_SPEED
elif self.direction == DIR_RIGHT:
self.x += PACMAN_SPEED
if self.x < -TILE_SIZE_X_2:
self.x = GAME_WIDTH
elif self.x >= GAME_WIDTH:
self.x = -TILE_SIZE_X_2
self.anim_timer += 1
if self.anim_timer >= 3:
self.anim_timer = 0
self.anim_frame = (self.anim_frame + 1) % 3
self.set_frame(self.direction, self.anim_frame)
self.tile_x = int((self.x + TILE_SIZE) // TILE_SIZE)
self.tile_y = int((self.y + TILE_SIZE) // TILE_SIZE)
self.update_sprite_pos()
# =============================================================================
# GHOST CLASS
# =============================================================================
class Ghost:
"""Ghost enemy character."""
TYPE_BLINKY = 8 * TILE_SIZE
TYPE_PINKY = 10 * TILE_SIZE
TYPE_INKY = 12 * TILE_SIZE
TYPE_CLYDE = 14 * TILE_SIZE
def __init__(self, ghost_type, start_tile_x, start_tile_y, x_offset=0):
self.ghost_type = ghost_type
self.start_params = (start_tile_x, start_tile_y, x_offset)
self.sprite = displayio.TileGrid(
sprite_sheet,
pixel_shader=sprite_palette,
width=1,
height=2,
tile_width=TILE_SIZE_X_2,
tile_height=TILE_SIZE,
)
self.tile_x = start_tile_x
self.tile_y = start_tile_y
self.x = self.tile_x * TILE_SIZE - TILE_SIZE__2 + x_offset
self.y = self.tile_y * TILE_SIZE - TILE_SIZE__2
self.direction = DIR_LEFT
self.next_direction = DIR_NONE
self.in_house = ghost_type != Ghost.TYPE_BLINKY
self.house_timer = 0
if self.in_house:
self.direction = DIR_DOWN if ghost_type == Ghost.TYPE_PINKY else DIR_UP
self.anim_frame = 0
self.anim_timer = 0
self.mode = MODE_SCATTER
self.reverse_pending = False
self.frightened_timer = 0
# Scatter targets
if ghost_type == Ghost.TYPE_BLINKY:
self.scatter_target = (25, -3)
elif ghost_type == Ghost.TYPE_PINKY:
self.scatter_target = (2, -3)
elif ghost_type == Ghost.TYPE_INKY:
self.scatter_target = (27, 31)
else:
self.scatter_target = (0, 31)
self.set_frame(self.direction, 0)
self.update_sprite_pos()
def set_frame(self, direction, frame_idx):
base_y = self.ghost_type
base_x = 0
if self.mode == MODE_FRIGHTENED:
base_y = 8 * TILE_SIZE
if (
self.frightened_timer > (FRIGHTENED_DURATION - (level * 10) - 110)
and (self.frightened_timer // 10) % 2 == 0
):
base_x = 20 * TILE_SIZE
else:
base_x = 16 * TILE_SIZE
base_x += (frame_idx % 2) * TILE_SIZE_X_2
elif self.mode == MODE_EATEN:
base_y = 10 * TILE_SIZE
if direction == DIR_RIGHT:
base_x = 16 * TILE_SIZE
elif direction == DIR_LEFT:
base_x = 18 * TILE_SIZE
elif direction == DIR_UP:
base_x = 20 * TILE_SIZE