from machine import Pin, SPI
from ili9341 import Display
from xpt2046 import Touch
import time
import random
# --- Initialisation matériel ---
spi = SPI(1, baudrate=40000000, sck=Pin(10), mosi=Pin(11), miso=Pin(12))
display = Display(spi, dc=Pin(14), cs=Pin(13), rst=Pin(15), height=240, width=320, rotation=90)
touch = Touch(spi, cs=Pin(9))
# --- Paramètres du jeu ---
WIDTH = 320
HEIGHT = 240
GRID = 10
snake = [(100, 100), (90, 100), (80, 100)]
direction = (10, 0)
egg = (random.randrange(0, WIDTH//GRID)*GRID,
random.randrange(0, HEIGHT//GRID)*GRID)
def draw_square(x, y, color):
display.fill_rectangle(x, y, GRID, GRID, color)
def safe(pos):
"""Vérifie si une position est sûre (dans l'écran et pas sur le serpent)."""
x, y = pos
if not (0 <= x < WIDTH and 0 <= y < HEIGHT):
return False
if pos in snake:
return False
return True
def auto_direction():
"""IA : tente d'aller vers l'œuf, sinon suit un chemin sûr."""
global direction
sx, sy = snake[0]
ex, ey = egg
# Tentative 1 : aller vers l'œuf
candidates = []
if ex > sx: candidates.append((GRID, 0))
if ex < sx: candidates.append((-GRID, 0))
if ey > sy: candidates.append((0, GRID))
if ey < sy: candidates.append((0, -GRID))
# On garde seulement les directions sûres
candidates = [d for d in candidates
if safe((sx + d[0], sy + d[1]))]
if candidates:
direction = candidates[0]
return
# Tentative 2 : mouvement de secours (éviter blocage)
fallback = [(GRID,0), (-GRID,0), (0,GRID), (0,-GRID)]
for d in fallback:
if safe((sx + d[0], sy + d[1])):
direction = d
return
def move_snake():
global egg
head_x, head_y = snake[0]
dx, dy = direction
new_head = (head_x + dx, head_y + dy)
# Sécurité ultime
if not safe(new_head):
return # l'IA empêche normalement d'arriver ici
snake.insert(0, new_head)
# Mange œuf
if new_head == egg:
egg = (random.randrange(0, WIDTH//GRID)*GRID,
random.randrange(0, HEIGHT//GRID)*GRID)
draw_square(egg[0], egg[1], 0xF800)
else:
tail = snake.pop()
draw_square(tail[0], tail[1], 0x0000)
draw_square(new_head[0], new_head[1], 0x07E0)
def reset_game():
global snake, direction, egg
display.clear()
snake = [(100, 100), (90, 100), (80, 100)]
direction = (10, 0)
egg = (random.randrange(0, WIDTH//GRID)*GRID,
random.randrange(0, HEIGHT//GRID)*GRID)
draw_square(egg[0], egg[1], 0xF800)
# --- Boucle principale ---
display.clear()
draw_square(egg[0], egg[1], 0xF800)
while True:
auto_direction()
move_snake()
time.sleep(0.05)