from machine import Pin, I2C, ADC
import ssd1306
import time
import random
# Configurar el I2C y la pantalla OLED
i2c = I2C(-1, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# Configurar los pines del joystick
adc_x = ADC(Pin(32))
adc_y = ADC(Pin(33))
adc_x.atten(ADC.ATTN_11DB)
adc_y.atten(ADC.ATTN_11DB)
def read_joystick():
x = adc_x.read()
y = adc_y.read()
return x, y
# Inicializar la posición de la viborita y la comida
snake = [(10, 10)]
food = (20, 20)
direction = (1, 0) # Dirección inicial: derecha
def move_snake():
global snake, food, direction
head = (snake[0][0] + direction[0] * 8, snake[0][1] + direction[1] * 8)
# Comprobar si la viborita come la comida
if head == food:
snake.insert(0, head)
for _ in range(3): # Parpadeo de la comida
oled.rect(food[0], food[1], 8, 8, 1)
oled.show()
time.sleep(0.1)
oled.rect(food[0], food[1], 8, 8, 0)
oled.show()
time.sleep(0.1)
food = (random.randint(0, oled_width//8 - 1) * 8,
random.randint(0, oled_height//8 - 1) * 8)
else:
snake.pop()
snake.insert(0, head)
# Comprobar si la viborita se choca
if head in snake[1:] or head[0] < 0 or head[0] >= oled_width or head[1] < 0 or head[1] >= oled_height:
raise Exception("Game Over")
def draw():
oled.fill(0)
for segment in snake:
oled.rect(segment[0], segment[1], 8, 8, 1)
oled.rect(food[0], food[1], 8, 8, 1)
oled.show()
def update_direction():
global direction
x, y = read_joystick()
if x < 1000:
direction = (-1, 0) # Izquierda
elif x > 3000:
direction = (1, 0) # Derecha
if y < 1000:
direction = (0, -1) # Arriba
elif y > 3000:
direction = (0, 1) # Abajo
# Bucle principal del juego
try:
while True:
update_direction()
move_snake()
draw()
time.sleep(0.5)
except Exception as e:
oled.fill(0)
oled.text(str(e), 0, 0)
oled.show()