from machine import Pin, I2C, ADC
import ssd1306
import time
import urandom
i2c = I2C(0, sda=Pin(0), scl=Pin(1))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
jx = ADC(26)
jy = ADC(27)
btn = Pin(15, Pin.IN, Pin.PULL_UP)
taille = 4
largeur = 128 // taille
hauteur = 64 // taille
snake = [(8, 8), (7, 8), (6, 8)]
direction = (1, 0)
nouvelle_direction = (1, 0)
food = (15, 10)
score = 0
commence = False
perdu = False
def carre(x, y):
for i in range(taille):
for j in range(taille):
oled.pixel(x + i, y + j, 1)
def texte_centre(txt, y):
x = (128 - len(txt) * 8) // 2
if x < 0:
x = 0
oled.text(txt, x, y)
def debut():
oled.fill(0)
texte_centre("SNAKE", 10)
oled.text("joystick pour jouer", 0, 28)
oled.text("bouton pour start", 0, 42)
oled.show()
def fin():
oled.fill(0)
texte_centre("GAME OVER", 10)
oled.text("score: " + str(score), 25, 30)
oled.text("appuie bouton", 10, 45)
oled.show()
def dessiner():
oled.fill(0)
oled.text(str(score), 0, 0)
for p in snake:
carre(p[0] * taille, p[1] * taille)
carre(food[0] * taille, food[1] * taille)
oled.show()
def nouvelle_food():
while True:
x = urandom.getrandbits(8) % largeur
y = urandom.getrandbits(8) % hauteur
if (x, y) not in snake:
return (x, y)
def reset():
global snake, direction, nouvelle_direction, food, score, perdu, commence
snake = [(8, 8), (7, 8), (6, 8)]
direction = (1, 0)
nouvelle_direction = (1, 0)
food = nouvelle_food()
score = 0
perdu = False
commence = True
def lire_joystick():
global nouvelle_direction
x = jx.read_u16()
y = jy.read_u16()
if x < 20000:
if direction != (-1, 0):
nouvelle_direction = (1, 0)
elif x > 45000:
if direction != (1, 0):
nouvelle_direction = (-1, 0)
elif y < 20000:
if direction != (0, -1):
nouvelle_direction = (0, 1)
elif y > 45000:
if direction != (0, 1):
nouvelle_direction = (0, -1)
def avancer():
global snake, direction, food, score, perdu
direction = nouvelle_direction
tete_x = snake[0][0]
tete_y = snake[0][1]
dx = direction[0]
dy = direction[1]
nv = (tete_x + dx, tete_y + dy)
if nv[0] < 0 or nv[0] >= largeur or nv[1] < 0 or nv[1] >= hauteur:
perdu = True
return
if nv in snake:
perdu = True
return
snake = [nv] + snake
if nv == food:
score = score + 1
food = nouvelle_food()
else:
snake.pop()
debut()
while True:
if commence == False:
if btn.value() == 0:
time.sleep_ms(200)
reset()
time.sleep_ms(50)
elif perdu == True:
fin()
if btn.value() == 0:
time.sleep_ms(200)
reset()
time.sleep_ms(50)
else:
lire_joystick()
avancer()
dessiner()
time.sleep(0.15)