# Gyro Snake example, 2018.10.26 tklua@wifiboy.org

import time
from machine import I2C, Pin
from mpu9250 import MPU9250

i2c = I2C(scl=Pin(22), sda=Pin(23))
sensor = MPU9250(i2c)

ax = ay = score = dx = dy = 0; sx = sy = 3; f=[]
for i in range(256): f.append(0)
    
f[sy*16+sx] = 1
ax = wb.rand(16); ay = wb.rand(15)+1; 
f[ay*16+ax] = 3

wb.cls(); wb.colors(wb.YELLOW, wb.BLACK)
while True:
    
    for i in range(256):
        if f[i]==2: wb.box(int(i%16)*8, int(i/16)*8, 8, 8, wb.BLACK); f[i]=0
        elif f[i]==1: wb.box(int(i%16)*8, int(i/16)*8, 8, 8, wb.WHITE)
        elif f[i]==3: wb.box(int(i%16)*8, int(i/16)*8, 8, 8, wb.RED)
            
    f[sy*16+sx]=2

    if sensor.acceleration[0]>2: dx = 1; dy=0
    elif sensor.acceleration[0]<-2: dx = -1; dy=0
    elif sensor.acceleration[1]>2: dy = 1; dx=0
    elif sensor.acceleration[1]<-2: dy = -1; dx=0
        
    sx += dx
    if sx>15: sx = 0
    if sx<0: sx = 15
    sy += dy
    if sy>15: sy = 1
    if sy<1: sy = 15
    if sx == ax and sy == ay:
        score += 1
        while sx == ax and sy == ay:
            ax = wb.rand(16); ay = wb.rand(15)+1; 
        f[ay*16+ax] = 3     
    f[sy*16+sx]=1
    wb.str("SCORE %04d"%(score), 20, 0, 2, 1)
    time.sleep(0.05)
