import pyxel
from random import randint
import random
TITLE = "blocus"
WIDTH = 500
HEIGHT = 500
CASE = 20
FRAME_REFRESH=2
x_food = 3
y_food = 5

global direction
global food

pyxel.init(WIDTH, HEIGHT, title=TITLE)
snake = [[3,3],[2,3],[1,3]]
score = 0
couleur = 0
result = 0
direction = [1,0]
food = [x_food, y_food]

def update():
    global couleur
    global direction
    global food
    global score
    if pyxel.frame_count % 1 == 0: #permet d'attendre qu'il ce soit passé 30 (si %30) frames pour faire le code
        couleur += 1
        if couleur > 15:
            couleur = 1
    if pyxel.frame_count % FRAME_REFRESH==1:
        head =[snake[0][0]+ direction [0], snake[0][1]+ direction[1]]
        snake.insert(0, head)
        if snake[0] == food: #manger la nouriture
            x_food = randint(1, 5)
            y_food = randint(1, 5)
            food = [x_food, y_food]
            score += 1
        else :
            snake.pop(-1)
    if pyxel.btn(pyxel.KEY_ESCAPE): #changement de direction 
        pass
    elif pyxel.btn(pyxel.KEY_RIGHT) and direction in ([0, 1], [0,-1]):
        direction =[1, 0]
    elif pyxel.btn(pyxel.KEY_LEFT) and direction in ([0, 1], [0,-1]):
        direction =[-1, 0]
    elif pyxel.btn(pyxel.KEY_UP) and direction in ([1, 0], [-1,0]):
        direction =[0, -1]
    elif pyxel.btn(pyxel.KEY_DOWN) and direction in ([1, 0], [-1,0]):
        direction =[0, 1]
    if snake[0] in snake[1:] \
            or snake[0][0] < 0 \
            or snake[0][0] > WIDTH/CASE - 1 \
            or snake[0][1] < 0 \
            or snake[0][1] > HEIGHT/CASE - 1:
                exit()

def draw():
    global food
    global result
    if pyxel.frame_count % 15 == 0: #changement de couleur du fruit
        result += 1
        if result == 1 :
            result = 7
        elif result == 8 :
            result = 0
    pyxel.cls(0)
    for anneaux in snake[1:]:#corps du serpent
        x, y = anneaux[0], anneaux[1]
        pyxel.rect(x * CASE, y * CASE, CASE, CASE,couleur)
    x_head, y_head = snake[0]
    pyxel.rect(x_head * CASE, y_head * CASE, CASE, CASE, 7)
    pyxel.text(4, 4, f"manque d'inspiration : {score}", 7)#hahaha fun title
    x_food, y_food = food
    pyxel.rect(x_food * CASE, y_food * CASE,CASE, CASE, result )
    
    
pyxel.run(update, draw)