from sense_hat import SenseHat, ACTION_PRESSED
from time import sleep
from random import randint

sense = SenseHat()
sense.clear()

# Farben
snake_color = [0, 255, 0]
food_color = [255, 0, 0]
blank = [0, 0, 0]

# Anfangswerte
snake = [(4, 4)]
direction = (1, 0)  # Start: nach rechts
food = ()
game_over = False

def place_food():
    global food
    while True:
        food = (randint(0, 7), randint(0, 7))
        if food not in snake:
            break
    sense.set_pixel(food[0], food[1], food_color)

def draw_snake():
    sense.clear()
    for segment in snake:
        sense.set_pixel(segment[0], segment[1], snake_color)
    sense.set_pixel(food[0], food[1], food_color)

def move_snake():
    global game_over
    head_x, head_y = snake[0]
    dx, dy = direction
    new_head = (head_x + dx, head_y + dy)

    # Kollision prüfen (Wand oder eigener Körper)
    if (
        new_head[0] < 0 or new_head[0] > 7 or
        new_head[1] < 0 or new_head[1] > 7 or
        new_head in snake
    ):
        game_over = True
        return

    snake.insert(0, new_head)
    if new_head == food:
        place_food()  # Neues Essen platzieren
    else:
        snake.pop()  # Letztes Element entfernen

def joystick_moved(event):
    global direction
    if event.action != ACTION_PRESSED:
        return
    if event.direction == "up" and direction != (0, 1):
        direction = (0, -1)
    elif event.direction == "down" and direction != (0, -1):
        direction = (0, 1)
    elif event.direction == "left" and direction != (1, 0):
        direction = (-1, 0)
    elif event.direction == "right" and direction != (-1, 0):
        direction = (1, 0)

# Joystick registrieren
sense.stick.direction_any = joystick_moved

# Spielstart
place_food()

while not game_over:
    move_snake()
    draw_snake()
    sleep(0.5)

# Game Over Anzeige
sense.show_message("Game Over", text_colour=[255, 0, 0])
sense.clear()
