'''
Description:
Author: Yan
version: 1.0.0
Date: 2026-04-12 13:04:05
LastEditors: Yan
LastEditTime: 2026-04-12 14:54:37
'''
from machine import *
from ssd1306 import SSD1306_I2C
from random import randint
from time import sleep
scl_Pin = 22
sda_Pin = 21
joy_x_Pin = 34
joy_y_Pin = 35
res_sw_Pin = 25
res_sw = Pin(res_sw_Pin,Pin.IN,Pin.PULL_UP)
i2c = SoftI2C(scl=scl_Pin,sda = sda_Pin)
oled = SSD1306_I2C(128,64,i2c)
joy_x = ADC(Pin(joy_x_Pin))
joy_x.atten(ADC.ATTN_11DB)
joy_y = ADC(Pin(joy_y_Pin))
joy_y.atten(ADC.ATTN_11DB)
def game_init():
global food_x, food_y, snake, dir_x, dir_y, step, game_over
food_x = randint(0,120)
food_y = randint(0,60)
snake = [[60,30],[55,30],[50,30]]
dir_x = 6
dir_y = 0
step = 6
game_over = False
game_init()
while True:
oled.fill(0)
sleep(0.5)
if res_sw.value() == 0:
game_init()
sleep(0.2)
if game_over:
oled.text("GAME OVER",25,20)
oled.text("Press button",10,40)
oled.text("to restart",20,50)
oled.show()
continue
joy_x_value = joy_x.read()
joy_y_value = joy_y.read()
if joy_x_value > 3000:
dir_x = -step
dir_y = 0
if joy_x_value < 1000:
dir_x = step
dir_y = 0
if joy_y_value > 3000:
dir_y = -step
dir_x = 0
if joy_y_value < 1000:
dir_y = step
dir_x = 0
# snake = [[60,30],[55,30],[50,30]]
head_x = snake[0][0] + dir_x
head_y = snake[0][1] + dir_y
new_head = [head_x,head_y]
snake.insert(0,new_head)
if head_x < 0 or head_x > 120 or head_y < 0 or head_y > 60:
game_over = True
for snake_x,snake_y in snake:
oled.text("o",snake_x,snake_y)
oled.text("*",food_x,food_y)
oled.show()
if abs(head_x - food_x) < 3 and abs(head_y-food_y) < 3:
food_x = randint(0,120)
food_y = randint(0,60)
else:
snake.pop()