-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
2710 lines (2337 loc) · 88 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
import hub75
import random
import time
import machine
import math
import gc
# Constants for display dimensions
HEIGHT = 64
WIDTH = 64
# Initialize the display
display = hub75.Hub75(WIDTH, HEIGHT)
# Global variables for game state
global_score = 0
last_game = None
game_over = False
# Color definitions for Simon game
COLORS_BRIGHT = [
(255, 0, 0), # Red
(0, 255, 0), # Green
(0, 0, 255), # Blue
(255, 255, 0), # Yellow
]
# Adjusted color shades for inactive states
colors = [(int(r * 0.5), int(g * 0.5), int(b * 0.5)) for r, g, b in COLORS_BRIGHT]
inactive_colors = [
(int(r * 0.2), int(g * 0.2), int(b * 0.2)) for r, g, b in COLORS_BRIGHT
]
# Game state variables for Simon game
simon_sequence = []
user_sequence = []
# Variables for Snake game
score = 0
snake = [(32, 32)]
snake_length = 3
snake_direction = "UP"
green_targets = []
text = ""
# Constants for Breakout game
PADDLE_WIDTH = 10
PADDLE_HEIGHT = 2
BALL_SIZE = 2
BRICK_WIDTH = 8
BRICK_HEIGHT = 4
BRICK_ROWS = 5
BRICK_COLS = 8
# Possible joystick directions
JOYSTICK_UP = "UP"
JOYSTICK_DOWN = "DOWN"
JOYSTICK_LEFT = "LEFT"
JOYSTICK_RIGHT = "RIGHT"
JOYSTICK_UP_LEFT = "UP-LEFT"
JOYSTICK_UP_RIGHT = "UP-RIGHT"
JOYSTICK_DOWN_LEFT = "DOWN-LEFT"
JOYSTICK_DOWN_RIGHT = "DOWN-RIGHT"
# Dictionary mapping characters to hex strings for display
CHAR_DICT = {
"A": "3078ccccfccccc00",
"B": "fc66667c6666fc00",
"C": "3c66c0c0c0663c00",
"D": "f86c6666666cf800",
"E": "fe6268786862fe00",
"F": "fe6268786860f000",
"G": "3c66c0c0ce663e00",
"H": "ccccccfccccccc00",
"I": "7830303030307800",
"J": "1e0c0c0ccccc7800",
"K": "f6666c786c66f600",
"L": "f06060606266fe00",
"M": "c6eefefed6c6c600",
"N": "c6e6f6decec6c600",
"O": "386cc6c6c66c3800",
"P": "fc66667c6060f000",
"Q": "78ccccccdc781c00",
"R": "fc66667c6c66f600",
"S": "78cce0380ccc7800",
"T": "fcb4303030307800",
"U": "ccccccccccccfc00",
"V": "cccccccccc783000",
"W": "c6c6c6d6feeec600",
"X": "c6c66c38386cc600",
"Y": "cccccc7830307800",
"Z": "fec68c183266fe00",
"0": "78ccdcfceccc7c00",
"1": "307030303030fc00",
"2": "78cc0c3860ccfc00",
"3": "78cc0c380ccc7800",
"4": "1c3c6cccfe0c1e00",
"5": "fcc0f80c0ccc7800",
"6": "3860c0f8cccc7800",
"7": "fccc0c1830303000",
"8": "78cccc78cccc7800",
"9": "78cccc7c0c187000",
"!": "3078783030003000",
"#": "6c6cfe6cfe6c6c00",
"$": "307cc0780cf83000",
"%": "00c6cc183066c600",
"&": "386c3876dccc7600",
"?": "78cc0c1830003000",
" ": "0000000000000000",
".": "0000000000003000",
":": "0030000000300000",
"(": "0c18303030180c00",
")": "6030180c18306000",
}
NUMS = {
"0": ["01110", "10001", "10001", "10001", "01110"],
"1": ["00100", "01100", "00100", "00100", "01110"],
"2": ["11110", "00001", "01110", "10000", "11111"],
"3": ["11110", "00001", "00110", "00001", "11110"],
"4": ["10000", "10010", "10010", "11111", "00010"],
"5": ["11111", "10000", "11110", "00001", "11110"],
"6": ["01110", "10000", "11110", "10001", "01110"],
"7": ["11111", "00010", "00100", "01000", "10000"],
"8": ["01110", "10001", "01110", "10001", "01110"],
"9": ["01110", "10001", "01111", "00001", "01110"],
" ": ["00000", "00000", "00000", "00000", "00000"],
".": ["00000", "00000", "00000", "00000", "00001"],
":": ["00000", "00100", "00000", "00100", "00000"],
"/": ["00001", "00010", "00100", "01000", "10000"],
"|": ["00100", "00100", "00100", "00100", "00100"],
"-": ["00000", "00000", "11111", "00000", "00000"],
"=": ["00000", "11111", "00000", "11111", "00000"],
"+": ["00000", "00100", "01110", "00100", "00000"],
"*": ["00000", "10101", "01110", "10101", "00000"],
"(": ["00010", "00100", "00100", "00100", "00010"],
")": ["00100", "00010", "00010", "00010", "00100"],
}
def sleep_ms(ms):
"""
Sleep for the given number of milliseconds.
"""
time.sleep(ms / 1000)
def get_time():
return time.time()
def draw_character(x, y, character, red, green, blue):
"""
Draw a character at position (x, y) with the given RGB color.
"""
if character in CHAR_DICT:
hex_string = CHAR_DICT[character]
for row in range(8):
hex_value = hex_string[row * 2 : row * 2 + 2]
bin_value = f"{int(hex_value, 16):08b}"
for col in range(8):
if bin_value[col] == "1":
display.set_pixel(x + col, y + row, red, green, blue)
def draw_text(x, y, text, red, green, blue):
"""
Draw text starting from position (x, y) with the given RGB color.
"""
offset_x = x
for character in text:
draw_character(offset_x, y, character, red, green, blue)
offset_x += 9 # Move to the next character position
def draw_character_small(x, y, character, red, green, blue):
"""
Draw a small character at position (x, y) with the given RGB color.
"""
if character in NUMS:
matrix = NUMS[character]
for row in range(5):
for col in range(5):
if matrix[row][col] == "1":
display.set_pixel(x + col, y + row, red, green, blue)
def draw_text_small(x, y, text, red, green, blue):
"""
Draw small text starting from position (x, y) with the given RGB color.
"""
offset_x = x
for character in text:
draw_character_small(offset_x, y, character, red, green, blue)
offset_x += 6 # Move to the next character position
def draw_rectangle(x1, y1, x2, y2, red, green, blue):
"""
Draw a rectangle between (x1, y1) and (x2, y2) with the given RGB color.
"""
for x in range(min(x1, x2), max(x1, x2) + 1):
for y in range(min(y1, y2), max(y1, y2) + 1):
display.set_pixel(x, y, red, green, blue)
def display_score_and_time(score):
"""
Display the current score and time at the bottom of the display.
"""
global text, global_score
year, month, day, weekday, hour, minute, second, _ = rtc.datetime()
time_str = "{:02}:{:02}".format(hour, minute)
global_score = score
score_str = str(score)
time_x = WIDTH - (len(time_str) * 6)
time_y = HEIGHT - 6
score_x = 1
score_y = HEIGHT - 6
if text != score_str + " " + time_str:
text = score_str + " " + time_str
draw_rectangle(score_x, score_y, WIDTH, score_y + 5, 0, 0, 0)
draw_text_small(score_x, score_y, score_str, 255, 255, 255)
draw_text_small(time_x, time_y, time_str, 255, 255, 255)
# Optimized Grid Management
grid = bytearray(WIDTH * HEIGHT // 2) # Reduced grid size to save memory
def initialize_grid():
"""
Initialize the grid to be empty.
"""
global grid
grid = bytearray(WIDTH * HEIGHT // 2)
def get_grid_value(x, y):
"""
Get the value at position (x, y) in the grid.
"""
index = y * WIDTH + x
return (grid[index // 2] >> ((index % 2) * 4)) & 0x0F
def set_grid_value(x, y, value):
"""
Set the value at position (x, y) in the grid.
"""
index = y * WIDTH + x
half_index = index // 2
shift = (index % 2) * 4
grid[half_index] = (grid[half_index] & ~(0x0F << shift)) | ((value & 0x0F) << shift)
def flood_fill(
x, y, accessible_mark, non_accessible_mark, red, green, blue, max_steps=8000
):
"""
Perform flood fill starting from (x, y).
"""
stack = [(x, y)]
steps = 0
while stack and steps < max_steps:
x, y = stack.pop(0)
grid_value = get_grid_value(x, y)
if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT:
continue
if grid_value != 0:
continue
set_grid_value(x, y, accessible_mark)
steps += 1
if x + 1 < WIDTH:
stack.append((x + 1, y))
if x - 1 >= 0:
stack.append((x - 1, y))
if y + 1 < HEIGHT:
stack.append((x, y + 1))
if y - 1 >= 0:
stack.append((x, y - 1))
return len(stack) > 0 # Indicates if there's still work left
rtc = machine.RTC()
# Exception to restart the program / go back to the main menu
class RestartProgram(Exception):
pass
class Nunchuck:
"""
Class to handle Wii Nunchuk inputs over I2C.
"""
def __init__(self, i2c, poll=True, poll_interval=50):
self.i2c = i2c
self.address = 0x52
self.buffer = bytearray(6) # Buffer to store sensor data
# Initialization sequence for the Nunchuk
self.i2c.writeto(self.address, b"\xf0\x55")
self.i2c.writeto(self.address, b"\xfb\x00")
# Timestamp of the last polling update
self.last_poll = time.ticks_ms()
# Polling interval in milliseconds
self.polling_threshold = poll_interval if poll else -1
def update(self):
"""
Update the buffer with new data from the Nunchuk.
"""
self.i2c.writeto(self.address, b"\x00")
self.i2c.readfrom_into(self.address, self.buffer)
def __poll(self):
"""
Internal method to handle polling based on the threshold.
"""
if (
self.polling_threshold > 0
and time.ticks_diff(time.ticks_ms(), self.last_poll)
> self.polling_threshold
):
self.update()
self.last_poll = time.ticks_ms()
def accelerator(self):
"""
Get accelerometer data.
"""
self.__poll()
return (
(self.buffer[2] << 2) + ((self.buffer[5] & 0x0C) >> 2),
(self.buffer[3] << 2) + ((self.buffer[5] & 0x30) >> 4),
(self.buffer[4] << 2) + ((self.buffer[5] & 0xC0) >> 6),
)
def buttons(self):
"""
Get button states (C and Z buttons).
"""
self.__poll()
c_button = not (self.buffer[5] & 0x02)
z_button = not (self.buffer[5] & 0x01)
if c_button and z_button:
#machine.reset()
raise RestartProgram()
return c_button, z_button
def joystick(self):
"""
Get joystick positions.
"""
self.__poll()
return (self.buffer[0], self.buffer[1])
def joystick_left(self):
"""
Check if joystick is tilted to the left.
"""
self.__poll()
return self.buffer[0] < 55
def joystick_right(self):
"""
Check if joystick is tilted to the right.
"""
self.__poll()
return self.buffer[0] > 200
def joystick_up(self):
"""
Check if joystick is tilted up.
"""
self.__poll()
return self.buffer[1] > 200
def joystick_down(self):
"""
Check if joystick is tilted down.
"""
self.__poll()
return self.buffer[1] < 55
def joystick_center(self):
"""
Check if joystick is in the center position.
"""
self.__poll()
return 100 < self.buffer[0] < 155 and 100 < self.buffer[1] < 155
def joystick_x(self):
"""
Get X-axis value of the joystick.
"""
self.__poll()
return (self.buffer[0] >> 2) - 34
def joystick_y(self):
"""
Get Y-axis value of the joystick.
"""
self.__poll()
return (self.buffer[1] >> 2) - 34
def is_shaking(self):
"""
Detect shaking motion using accelerometer data.
"""
x, y, z = self.accelerator()
return max(x, y, z) > 800 # Threshold for detection
class Joystick:
"""
Class to handle joystick inputs, either via analog inputs or I2C (Nunchuk).
"""
def __init__(self):
self.joystick_mode = "i2c"
if self.joystick_mode == "i2c":
self.i2c = machine.I2C(0, scl=machine.Pin(21), sda=machine.Pin(20))
self.nunchuck = Nunchuck(self.i2c)
def read_direction(self, possible_directions, debounce=True):
"""
Read the joystick direction based on possible directions.
"""
if self.joystick_mode == "i2c":
x, y = self.nunchuck.joystick()
# Map joystick positions to directions
if x < 100 and y < 100 and JOYSTICK_DOWN_LEFT in possible_directions:
return JOYSTICK_DOWN_LEFT
elif x > 150 and y < 100 and JOYSTICK_DOWN_RIGHT in possible_directions:
return JOYSTICK_DOWN_RIGHT
elif x < 100 and y > 150 and JOYSTICK_UP_LEFT in possible_directions:
return JOYSTICK_UP_LEFT
elif x > 150 and y > 150 and JOYSTICK_UP_RIGHT in possible_directions:
return JOYSTICK_UP_RIGHT
elif x < 100 and JOYSTICK_LEFT in possible_directions:
return JOYSTICK_LEFT
elif x > 150 and JOYSTICK_RIGHT in possible_directions:
return JOYSTICK_RIGHT
elif y < 100 and JOYSTICK_DOWN in possible_directions:
return JOYSTICK_DOWN
elif y > 150 and JOYSTICK_UP in possible_directions:
return JOYSTICK_UP
else:
return None
return None
def is_pressed(self):
"""
Check if the joystick button is pressed.
"""
if self.joystick_mode == "i2c":
_, z = self.nunchuck.buttons()
return z
return False
def hsb_to_rgb(hue, saturation, brightness):
hue_normalized = (hue % 360) / 60
hue_index = int(hue_normalized)
hue_fraction = hue_normalized - hue_index
value1 = brightness * (1 - saturation)
value2 = brightness * (1 - saturation * hue_fraction)
value3 = brightness * (1 - saturation * (1 - hue_fraction))
if hue_index == 0:
red, green, blue = brightness, value3, value1
elif hue_index == 1:
red, green, blue = value2, brightness, value1
elif hue_index == 2:
red, green, blue = value1, brightness, value3
elif hue_index == 3:
red, green, blue = value1, value2, brightness
elif hue_index == 4:
red, green, blue = value3, value1, brightness
elif hue_index == 5:
red, green, blue = brightness, value1, value2
else:
red, green, blue = 0, 0, 0
return int(red * 255), int(green * 255), int(blue * 255)
# Game Classes
class SimonGame:
"""
Class representing the Simon Says game.
"""
def __init__(self):
"""
Initialize the Simon game with empty sequences.
"""
self.sequence = []
self.user_input = []
def draw_quad_screen(self):
"""
Draw the four quadrants of the screen with inactive colors.
"""
half_width = WIDTH // 2
half_height = (HEIGHT - 6) // 2 # Adjust for score display area
draw_rectangle(0, 0, half_width - 1, half_height - 1, *inactive_colors[0])
draw_rectangle(half_width, 0, WIDTH - 1, half_height - 1, *inactive_colors[1])
draw_rectangle(0, half_height, half_width - 1, HEIGHT - 7, *inactive_colors[2])
draw_rectangle(
half_width, half_height, WIDTH - 1, HEIGHT - 7, *inactive_colors[3]
)
def flash_color(self, index, duration=0.5):
"""
Flash a specific color on the screen.
Args:
index (int): Index of the color to flash.
duration (float): Duration to display the color.
"""
x = index % 2
y = index // 2
half_width = WIDTH // 2
half_height = (HEIGHT - 6) // 2
draw_rectangle(
x * half_width,
y * half_height,
(x + 1) * half_width - 1,
(y + 1) * half_height - 1,
*colors[index],
)
sleep_ms(int(duration * 1000))
draw_rectangle(
x * half_width,
y * half_height,
(x + 1) * half_width - 1,
(y + 1) * half_height - 1,
*inactive_colors[index],
)
def play_sequence(self):
"""
Play the current sequence by flashing the colors.
"""
for color_index in self.sequence:
self.flash_color(color_index)
sleep_ms(500)
def get_user_input(self, joystick):
"""
Get the user's input via the joystick.
Args:
joystick (Joystick): The joystick object.
Returns:
str: The direction selected by the user.
"""
while True:
direction = joystick.read_direction(
[
JOYSTICK_UP_LEFT,
JOYSTICK_UP_RIGHT,
JOYSTICK_DOWN_LEFT,
JOYSTICK_DOWN_RIGHT,
]
)
if direction:
return direction
sleep_ms(100)
def translate_joystick_to_color(self, direction):
"""
Translate joystick direction to a color index.
Args:
direction (str): Direction from the joystick.
Returns:
int: Corresponding color index.
"""
mapping = {
JOYSTICK_UP_LEFT: 0,
JOYSTICK_UP_RIGHT: 1,
JOYSTICK_DOWN_LEFT: 2,
JOYSTICK_DOWN_RIGHT: 3,
}
return mapping.get(direction, None)
def check_user_sequence(self):
"""
Check if the user's input matches the game sequence.
Returns:
bool: True if sequences match, False otherwise.
"""
return self.user_input == self.sequence[: len(self.user_input)]
def start_game(self):
"""
Start a new game by resetting sequences and drawing the initial screen.
"""
self.sequence = []
self.user_input = []
self.draw_quad_screen()
def main_loop(self, joystick):
"""
Main game loop for the Simon game.
Args:
joystick (Joystick): The joystick object.
"""
global global_score, game_over
game_over = False
self.start_game()
while not game_over:
try:
c_button, _ = joystick.nunchuck.buttons()
if c_button: # C-button ends the game
game_over = True
self.sequence.append(random.randint(0, 3))
display_score_and_time(len(self.sequence) - 1)
self.play_sequence()
self.user_input = []
for _ in range(len(self.sequence)):
direction = self.get_user_input(joystick)
selected_color = self.translate_joystick_to_color(direction)
if selected_color is not None:
self.flash_color(selected_color, duration=0.2)
self.user_input.append(selected_color)
if not self.check_user_sequence():
global_score = len(self.sequence) - 1
game_over = True
return
else:
break
sleep_ms(1000)
gc.collect()
except RestartProgram:
game_over = True
return
class SnakeGame:
"""
Class representing the Snake game.
"""
def __init__(self):
"""
Initialize the Snake game variables.
Args:
mode (str): "single" for singleplayer, "zero" for zero-player.
"""
self.snake = [(32, 32)]
self.snake_length = 3
self.snake_direction = "UP"
self.score = 0
self.green_targets = []
self.target = self.random_target()
self.step_counter = 0
self.step_counter2 = 0
self.running = True
def restart_game(self):
"""
Restart the game by resetting variables and clearing the display.
"""
self.snake = [(32, 32)]
self.snake_length = 3
self.snake_direction = "UP"
self.score = 0
self.green_targets = []
display.clear()
self.place_target()
def random_target(self):
"""
Generate a random position for the target.
Returns:
tuple: Coordinates of the target.
"""
return (random.randint(1, WIDTH - 2), random.randint(1, HEIGHT - 8))
def place_target(self):
"""
Place the target on the display.
"""
self.target = self.random_target()
display.set_pixel(self.target[0], self.target[1], 255, 0, 0)
def place_green_target(self):
"""
Place a green target on the display.
"""
x, y = random.randint(1, WIDTH - 2), random.randint(1, HEIGHT - 8)
self.green_targets.append((x, y, 256))
display.set_pixel(x, y, 0, 255, 0)
def update_green_targets(self):
"""
Update the lifespan of green targets and remove them if necessary.
"""
new_green_targets = []
for x, y, lifespan in self.green_targets:
if lifespan > 1:
new_green_targets.append((x, y, lifespan - 1))
else:
display.set_pixel(x, y, 0, 0, 0)
self.green_targets = new_green_targets
def check_self_collision(self):
"""
Check for collision of the snake with itself.
If collision is detected, the game ends.
"""
global global_score, game_over
head_x, head_y = self.snake[0]
body = self.snake[1:]
potential_moves = {
"UP": (head_x, head_y - 1),
"DOWN": (head_x, head_y + 1),
"LEFT": (head_x - 1, head_y),
"RIGHT": (head_x + 1, head_y),
}
safe_moves = {
direction: pos
for direction, pos in potential_moves.items()
if pos not in body
}
if potential_moves[self.snake_direction] not in safe_moves.values():
if safe_moves:
self.snake_direction = random.choice(list(safe_moves.keys()))
else:
global_score = self.score
game_over = True
return
def update_snake_position(self):
"""
Update the position of the snake based on its current direction.
"""
head_x, head_y = self.snake[0]
if self.snake_direction == "UP":
head_y -= 1
elif self.snake_direction == "DOWN":
head_y += 1
elif self.snake_direction == "LEFT":
head_x -= 1
elif self.snake_direction == "RIGHT":
head_x += 1
head_x %= WIDTH
head_y %= HEIGHT
self.snake.insert(0, (head_x, head_y))
if len(self.snake) > self.snake_length:
tail = self.snake.pop()
display.set_pixel(tail[0], tail[1], 0, 0, 0)
def check_target_collision(self):
"""
Check if the snake has collided with the target.
If so, increase the snake length and score, and place a new target.
"""
head_x, head_y = self.snake[0]
if (head_x, head_y) == self.target:
self.snake_length += 2
self.place_target()
self.score += 1
def check_green_target_collision(self):
"""
Check if the snake has collided with a green target.
If so, reduce the snake length.
"""
head_x, head_y = self.snake[0]
for x, y, lifespan in self.green_targets:
if (head_x, head_y) == (x, y):
self.snake_length = max(self.snake_length // 2, 2)
self.green_targets.remove((x, y, lifespan))
display.set_pixel(x, y, 0, 0, 0)
def draw_snake(self):
"""
Draw the snake on the display with a color gradient.
"""
hue = 0
for idx, (x, y) in enumerate(self.snake[: self.snake_length]):
hue = (hue + 5) % 360
red, green, blue = hsb_to_rgb(hue, 1, 1)
display.set_pixel(x, y, red, green, blue)
for idx in range(self.snake_length, len(self.snake)):
x, y = self.snake[idx]
display.set_pixel(x, y, 0, 0, 0)
def find_nearest_target(self, head_x, head_y, green_targets, red_target):
def manhattan_distance(x1, y1, x2, y2):
return abs(x1 - x2) + abs(y1 - y2)
min_distance_green = float('inf')
nearest_green_target = None
for x, y, _ in green_targets:
distance = manhattan_distance(head_x, head_y, x, y)
if distance < min_distance_green:
min_distance_green = distance
nearest_green_target = (x, y)
distance_red = manhattan_distance(head_x, head_y, red_target[0], red_target[1])
if nearest_green_target and min_distance_green <= distance_red * 1.5:
return nearest_green_target
else:
return red_target
def update_direction(self):
"""
Update the snake's direction towards the nearest target.
"""
head_x, head_y = self.snake[0]
target_x, target_y = self.find_nearest_target(head_x, head_y, self.green_targets, self.target)
opposite_directions = {'UP': 'DOWN', 'DOWN': 'UP', 'LEFT': 'RIGHT', 'RIGHT': 'LEFT'}
new_direction = self.snake_direction # Default to current direction
if head_x == target_x:
if head_y < target_y and self.snake_direction != 'UP':
new_direction = 'DOWN'
elif head_y > target_y and self.snake_direction != 'DOWN':
new_direction = 'UP'
elif head_y == target_y:
if head_x < target_x and self.snake_direction != 'LEFT':
new_direction = 'RIGHT'
elif head_x > target_x and self.snake_direction != 'RIGHT':
new_direction = 'LEFT'
else:
if abs(head_x - target_x) < abs(head_y - target_y):
if head_x < target_x and self.snake_direction != 'LEFT':
new_direction = 'RIGHT'
elif head_x > target_x and self.snake_direction != 'RIGHT':
new_direction = 'LEFT'
else:
if head_y < target_y and self.snake_direction != 'UP':
new_direction = 'DOWN'
elif head_y > target_y and self.snake_direction != 'DOWN':
new_direction = 'UP'
# Prevent moving in the opposite direction immediately
if new_direction == opposite_directions[self.snake_direction]:
new_direction = self.snake_direction
return new_direction
def main_loop(self, joystick, mode="single"):
"""
Main game loop for the Snake game.
Args:
joystick (Joystick): The joystick object.
"""
global game_over
game_over = False
self.restart_game()
step_counter = 0
#if mode == "zero":
# self.mode = "zero"
while not game_over:
try:
c_button, _ = joystick.nunchuck.buttons()
if c_button: # C-button ends the game
game_over = True
self.step_counter += 1
if mode == "zero":
self.step_counter2 += 1
if self.step_counter2 % 1024 == 0:
self.place_green_target()
self.update_green_targets()
if mode == "single":
if self.step_counter % 1024 == 0:
self.place_green_target()
self.update_green_targets()
if mode == "zero":
direction = self.update_direction()
self.snake_direction = direction
else:
direction = joystick.read_direction(
[JOYSTICK_UP, JOYSTICK_DOWN, JOYSTICK_LEFT, JOYSTICK_RIGHT]
)
if direction:
self.snake_direction = direction
self.check_self_collision()
self.update_snake_position()
self.check_target_collision()
self.check_green_target_collision()
self.draw_snake()
display_score_and_time(self.score)
sleep_ms(max(30, int(90 - max(10, self.snake_length / 3))) )
gc.collect()
except RestartProgram:
game_over = True
return
class PongGame:
"""
Class representing the Pong game.
"""
def __init__(self):
"""
Initialize the Pong game variables.
"""
self.paddle_height = 8
self.paddle_speed = 2
self.ball_speed = [1, 1]
self.ball_position = [WIDTH // 2, HEIGHT // 2]
self.left_paddle_y = HEIGHT // 2 - self.paddle_height // 2
self.right_paddle_y = HEIGHT // 2 - self.paddle_height // 2
self.previous_left_score = 0
self.left_score = 0
self.lives = 3
def draw_paddles(self):
"""
Draw the paddles on the display.
"""
# Clear previous paddle positions
for y in range(HEIGHT):
display.set_pixel(0, y, 0, 0, 0)
display.set_pixel(WIDTH - 1, y, 0, 0, 0)
# Draw left paddle
for y in range(self.left_paddle_y, self.left_paddle_y + self.paddle_height):
display.set_pixel(0, y, 255, 255, 255)
# Draw right paddle
for y in range(self.right_paddle_y, self.right_paddle_y + self.paddle_height):
display.set_pixel(WIDTH - 1, y, 255, 255, 255)
def draw_ball(self):
"""
Draw the ball on the display.
"""
x, y = self.ball_position
display.set_pixel(x, y, 255, 255, 255)
def clear_ball(self):
"""
Clear the ball from its current position.
"""
x, y = self.ball_position
display.set_pixel(x, y, 0, 0, 0)
def update_ball(self):
"""
Update the ball's position and handle collisions.
"""
global global_score, game_over
self.clear_ball()
self.ball_position[0] += self.ball_speed[0]
self.ball_position[1] += self.ball_speed[1]
x, y = self.ball_position
# Handle collision with top and bottom walls
if y <= 0 or y >= HEIGHT - 1:
self.ball_speed[1] = -self.ball_speed[1]
# Handle collision with left paddle
if x == 1 and self.left_paddle_y <= y < self.left_paddle_y + self.paddle_height:
self.ball_speed[0] = -self.ball_speed[0]
self.left_score += 1
# Handle collision with right paddle
elif (
x == WIDTH - 2
and self.right_paddle_y <= y < self.right_paddle_y + self.paddle_height
):
self.ball_speed[0] = -self.ball_speed[0]