Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.9 kB
0
Indexable
Never
import random
import curses

# Initialize curses
stdscr = curses.initscr()
curses.curs_set(0)  # Hide cursor
sh, sw = stdscr.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)

# Initial snake and food coordinates
snake_x = sw // 4
snake_y = sh // 2
snake = [
    [snake_y, snake_x],
    [snake_y, snake_x - 1],
    [snake_y, snake_x - 2]
]

food = [sh // 2, sw // 2]
w.addch(food[0], food[1], curses.ACS_PI)  # Food symbol

# Initial direction and score
key = curses.KEY_RIGHT
score = 0

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

    # Check if snake hits the wall or itself
    if (
        snake[0][0] in [0, sh] or
        snake[0][1] in [0, sw] or
        snake[0] in snake[1:]
    ):
        curses.endwin()
        print("Game Over!")
        print(f"Your score: {score}")
        break

    # New head position
    new_head = [snake[0][0], snake[0][1]]

    # Determine direction based on key pressed
    if key == curses.KEY_DOWN:
        new_head[0] += 1
    if key == curses.KEY_UP:
        new_head[0] -= 1
    if key == curses.KEY_LEFT:
        new_head[1] -= 1
    if key == curses.KEY_RIGHT:
        new_head[1] += 1

    # Insert new head into snake
    snake.insert(0, new_head)

    # Check if snake eats food
    if snake[0] == food:
        score += 1
        food = None
        while food is None:
            nf = [
                random.randint(1, sh - 1),
                random.randint(1, sw - 1)
            ]
            food = nf if nf not in snake else None
        w.addch(food[0], food[1], curses.ACS_PI)
    else:
        tail = snake.pop()
        w.addch(int(tail[0]), int(tail[1]), ' ')

    # Draw snake
    w.addch(int(snake[0][0]), int(snake[0][1]), curses.ACS_CKBOARD)

# End curses
curses.endwin()
Leave a Comment