from machine import Pin, ADC, SPI
import time
import random
class Max7219:
def __init__(self, spi, cs):
self.spi = spi
self.cs = cs
self.cs.init(Pin.OUT, True)
self.write_cmd(0x0F, 0x00)
self.write_cmd(0x0C, 0x01)
self.write_cmd(0x0B, 0x07)
self.write_cmd(0x09, 0x00)
self.write_cmd(0x0A, 0x05)
self.clear()
def write_cmd(self, cmd, data):
self.cs.value(0)
self.spi.write(bytearray([cmd, data]))
self.cs.value(1)
def clear(self):
for i in range(1, 9): self.write_cmd(i, 0)
def set_row(self, row, value):
self.write_cmd(row + 1, value)
spi = SPI(0, baudrate=1000000, polarity=0, phase=0, sck=Pin(2), mosi=Pin(3))
cs = Pin(5)
display = Max7219(spi, cs)
joy_x = ADC(Pin(26))
joy_y = ADC(Pin(27))
btn_start = Pin(17, Pin.IN, Pin.PULL_UP) # boton 1: iniciar
btn_pause = Pin(18, Pin.IN, Pin.PULL_UP) # boton 2: pausa
btn_reset = Pin(19, Pin.IN, Pin.PULL_UP) # boton 3: reset
jugando = False
pausado = False
serpiente = [[2, 4], [3, 4], [4, 4]]
manzana = [6, 4]
direccion = [0, -1]
def generar_manzana():
global manzana
while True:
nueva = [random.randint(0, 7), random.randint(0, 7)]
if nueva not in serpiente:
manzana = nueva
break
def reset_juego():
global serpiente, manzana, direccion, jugando, pausado
serpiente = [[2, 4], [3, 4], [4, 4]]
manzana = [6, 4]
direccion = [0, -1]
jugando = False
pausado = False
actualizar_matriz()
def actualizar_matriz():
display.clear()
buffer = [0] * 8
buffer[manzana[1]] |= (1 << (7 - manzana[0]))
for seg in serpiente:
buffer[seg[1]] |= (1 << (7 - seg[0]))
for i in range(8):
display.set_row(i, buffer[i])
def leer_direccion():
global direccion
x_val = joy_x.read_u16()
y_val = joy_y.read_u16()
limite_inf = 20000
limite_sup = 45000
if x_val < limite_inf and direccion != [1, 0]:
direccion = [-1, 0]
elif x_val > limite_sup and direccion != [-1, 0]:
direccion = [1, 0]
elif y_val < limite_inf and direccion != [0, -1]:
direccion = [0, 1]
elif y_val > limite_sup and direccion != [0, 1]:
direccion = [0, -1]
def mover_serpiente():
global jugando
nueva_cabeza = [serpiente[0][0] + direccion[0], serpiente[0][1] + direccion[1]]
if nueva_cabeza[0] < 0 or nueva_cabeza[0] > 7 or nueva_cabeza[1] < 0 or nueva_cabeza[1] > 7:
reset_juego()
return
if nueva_cabeza in serpiente:
reset_juego()
return
serpiente.insert(0, nueva_cabeza)
if nueva_cabeza == manzana:
generar_manzana()
else:
serpiente.pop()
last_update = time.ticks_ms()
reset_juego()
while True:
if not btn_start.value() and not jugando:
jugando = True
time.sleep(0.2)
if not btn_pause.value() and jugando:
pausado = not pausado
time.sleep(0.2)
if not btn_reset.value():
reset_juego()
time.sleep(0.2)
if jugando and not pausado:
leer_direccion()
if time.ticks_diff(time.ticks_ms(), last_update) > 300:
mover_serpiente()
actualizar_matriz()
last_update = time.ticks_ms()
if not jugando or pausado:
actualizar_matriz()
time.sleep(0.1)