create snake game with unicode characters in python

To create a snake game with Unicode characters in Python, we can use the built-in curses library. This library allows us to create text-based user interfaces and games by defining custom character sets and handling keyboard inputs.

Below is a sample code for creating a Snake game:

main.py
import curses
from random import randint

# Initialize curses screen
screen = curses.initscr()
curses.curs_set(0)

# Set initial position of the snake
snake = [[4, 10], [4, 9], [4, 8]]
snake_direction = curses.KEY_RIGHT

# Set initial position of the food
food = [10, 20]

# Define custom character set for the snake and food
snake_char = u'\u25A0'
food_char = u'\u2022'

# Set up colors for the snake and food
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)

# Draw the initial snake and food
for y, x in snake:
    screen.addstr(y, x, snake_char, curses.color_pair(1))
screen.addstr(food[0], food[1], food_char, curses.color_pair(2))

# Set up game loop
while True:
    # Listen for keyboard input
    key = screen.getch()
    if key in [curses.KEY_RIGHT, curses.KEY_LEFT, curses.KEY_UP, curses.KEY_DOWN]:
        snake_direction = key

    # Move the snake based on player input
    x, y = snake[0]
    if snake_direction == curses.KEY_RIGHT:
        x += 1
    elif snake_direction == curses.KEY_LEFT:
        x -= 1
    elif snake_direction == curses.KEY_UP:
        y -= 1
    elif snake_direction == curses.KEY_DOWN:
        y += 1
    snake.insert(0, [x,y])
    
    # Handle collision with food
    if snake[0] == food:
        food = None
        while food is None:
            new_food = [randint(1, curses.LINES-1), randint(1, curses.COLS-1)]
            food = new_food if new_food not in snake else None
        screen.addstr(food[0], food[1], food_char, curses.color_pair(2))
    else:
        # Remove tail of snake if there is no food eaten
        last = snake.pop()
        screen.addstr(last[0], last[1], ' ')

    # Handle collision with walls or snake body
    if snake[0][0] in [0,curses.LINES] or snake[0][1] in [0,curses.COLS] or snake[0] in snake[1:]:
        curses.endwin()
        quit()

    # Draw snake after move
    screen.addstr(snake[0][0], snake[0][1], snake_char, curses.color_pair(1))

    # Refresh screen
    screen.refresh()
2059 chars
70 lines

This code defines a snake that is represented by the '#' character and moves around the screen. The snake eats food, which is represented by 'O', to grow longer. If the snake hits the wall or itself, the game is over. The game loop handles keyboard input and updates the screen accordingly. By using Unicode characters and custom character sets, we can create more visually interesting games even in the console.

gistlibby LogSnag