gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
heollo
- User
heollo
- Assistant
Hello! How can I assist you today?
- User
what is 3+3
- Assistant
3 + 3 equals 6.
- User
make snake game using curses as a display
- Assistant
heollo
Hello! How can I assist you today?
what is 3+3
3 + 3 equals 6.
make snake game using curses as a display
Creating a simple Snake game using the curses library in Python is a fun project! Below is a basic implementation of the Snake game. You can run this code in your terminal.
Make sure you have Python installed on your machine. If you don't already have the curses library, it comes installed with Python on Unix-based systems (like Linux and macOS). For Windows, you might want to use the windows-curses package.
Here's how to create a simple Snake game using curses:
import curses
import random
# Set up the window
stdscr = curses.initscr()
curses.curs_set(0) # Hide the cursor
sh, sw = stdscr.getmaxyx() # Get height and width of the window
w = curses.newwin(sh, sw, 0, 0) # Create a new window
w.keypad(1) # Enable key input
w.timeout(100) # Refresh every 100 milliseconds
# Initial snake and food positions
snk_x = sw // 4
snk_y = sh // 2
snake = [
[snk_y, snk_x],
[snk_y, snk_x - 1],
[snk_y, snk_x - 2]
]
food = [sh // 2, sw // 2]
w.addch(int(food[0]), int(food[1]), curses.ACS_PI)
# Game logic variables
key = curses.KEY_RIGHT
score = 0
while True:
next_key = w.getch() # Get user's input
key = key if next_key == -1 else next_key # Don't change direction if no key pressed
# New head of the snake
new_head = [snake[0][0], snake[0][1]]
# Change the direction of the snake
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
# Check for collision with borders
if (
new_head[0] in [0, sh] or
new_head[1] in [0, sw] or
new_head in snake
):
curses.endwin() # Exit the window
quit() # End game
# Insert new head
snake.insert(0, new_head)
# Check if snake has eaten the food
if snake[0] == food:
score += 1
food = None
while food is None: # Generate new food position
nf = [
random.randint(1, sh-1),
random.randint(1, sw-1)
]
food = nf if nf not in snake else None
w.addch(int(food[0]), int(food[1]), curses.ACS_PI) # Draw the food
else:
# Remove the last segment of the snake
tail = snake.pop()
w.addch(int(tail[0]), int(tail[1]), ' ') # Clear the tail
# Draw the snake
w.addch(int(snake[0][0]), int(snake[0][1]), curses.ACS_CKBOARD)
snake.py.snake.py.python snake.py.Enjoy coding your Snake game!
Not yet included in a published release.