from machine import Pin, I2C
from neopixel import NeoPixel
from time import sleep
from random import randint
from pico_i2c_lcd import I2cLcd
i2c = I2C(0, sda=Pin(20), scl=Pin(21), freq=100000)
I2C_ADDR = i2c.scan()[0]
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
score = 0
def pressUp(event):
global dir
dir = 'n'
def pressDown(event):
global dir
dir = 's'
def pressLeft(event):
global dir
dir = 'w'
def pressRight(event):
global dir
dir = 'e'
def c(x, y):
return 8*y + x
def newApple():
global apX, apY
while posInSnake(apX, apY):
apX = randint(0, 7)
apY = randint(0, 7)
np[c(apX,apY)] = (200, 0, 0)
def posInSnake(x, y, begin=0):
global snakelst
end = len(snakelst)-begin
isit = False
for glied in snakelst[:end]:
if glied[0]==x and glied[1]==y:
isit = True
return isit
def snakeMove(dir):
global kopfX, kopfY, snakelst, lenght, apX, apY, score
if dir == 'n':
kopfY -= 1
elif dir == 's':
kopfY += 1
elif dir == 'e':
kopfX += 1
elif dir == 'w':
kopfX -= 1
np[c(kopfX,kopfY)] = (0, 0, 255)
if dir != '':
snakelst += [ (kopfX, kopfY) ]
if len(snakelst) > lenght:
end = snakelst.pop(0)
clsPix(end[0], end[1])
if kopfX==apX and kopfY==apY:
lenght += 1
score += 1
lcd.clear()
lcd.putstr("Score:" + str(score))
newApple()
if not(0<=kopfX<=7 and 0<=kopfY<=7) or posInSnake(kopfX, kopfY, 1):
for i in range(0, 64):
np[i] = (0, 0, 0)
for i in range(0, 8):
np[c(i, i)] = (200, 0, 0)
np[c(i, 7-i)] = (200, 0, 0)
np.write()
sleep(1)
newGame()
def clsPix(x, y):
if (x+y)%2==0:
np[c(x,y)] = (50, 100, 50)
else:
np[c(x,y)] = (50, 100, 00)
def newGame():
global kopfX, kopfY, apX, apY, snakelst, score, lenght, dir
for x in range(0, 8):
for y in range(0, 8):
clsPix(x, y)
kopfX = randint(-1, 6)
kopfY = randint(0, 7)
score = 0
lcd.clear()
lcd.putstr("Score:" + str(score))
snakelst = [ (kopfX, kopfY) ]
lenght = 1
dir = ''
apX = randint(0, 7)
apY = randint(0, 7)
snakeMove('e')
newApple()
np.write()
######### main ##################
Up = Pin(18, Pin.IN, Pin.PULL_DOWN)
Up.irq(trigger=Pin.IRQ_RISING, handler=pressUp)
Down = Pin(17, Pin.IN, Pin.PULL_DOWN)
Down.irq(trigger=Pin.IRQ_RISING, handler=pressDown)
Left = Pin(16, Pin.IN, Pin.PULL_DOWN)
Left.irq(trigger=Pin.IRQ_RISING, handler=pressLeft)
Right = Pin(19, Pin.IN, Pin.PULL_DOWN)
Right.irq(trigger=Pin.IRQ_RISING, handler=pressRight)
pin = Pin(0, Pin.OUT)
np = NeoPixel(pin, 64)
newGame()
while True:
snakeMove(dir)
np.write()
sleep(.5)