[Python] snake not eating food

Discussão em 'Python' iniciado por Stack, Outubro 5, 2024.

  1. Stack

    Stack Membro Participativo

    I'm working on a simple Snake game in Python using curses, and I'm having an issue with the snake not properly eating the food. The snake seems to move over the food, but it doesn't get longer. Can someone please help me identify what's causing this issue and how I can fix it?

    import curses
    from random import randint

    def create_food(snake, box):
    food = None
    while food is None:
    food = [randint(box[0]+1, box[1]-1), randint(box[2]+1, box[3]-1)]
    if food in snake:
    food = None
    return food

    def main(stdscr):
    curses.curs_set(0)
    stdscr.timeout(100)

    sh, sw = stdscr.getmaxyx()
    w = curses.newwin(sh, sw, 0, 0)
    w.keypad(1)

    box = [3, sh-3, 3, sw-3]
    snake = [
    [sh//2, sw//2],
    [sh//2, sw//2-1],
    [sh//2, sw//2-2]
    ]

    food = create_food(snake, box)

    key = curses.KEY_RIGHT

    while True:
    next_key = w.getch()
    key = key if next_key == -1 else next_key

    head = [snake[0][0], snake[0][1]]

    if key == curses.KEY_DOWN:
    head[0] += 1
    elif key == curses.KEY_UP:
    head[0] -= 1
    elif key == curses.KEY_LEFT:
    head[1] -= 1
    elif key == curses.KEY_RIGHT:
    head[1] += 1

    snake.insert(0, head)

    if head == food:
    food = None
    else:
    tail = snake.pop()

    w.addch(food[0], food[1], curses.ACS_PI)

    w.addch(tail[0], tail[1], ' ')

    w.addch(snake[0][0], snake[0][1], '*')

    if (
    snake[0][0] in [box[0], box[1]] or
    snake[0][1] in [box[2], box[3]] or
    snake[0] in snake[1:]
    ):
    break

    curses.wrapper(main)



    i need the snake to get longer when eats food

    Continue reading...

Compartilhe esta Página