Okay, here's a basic text-based Snake game designed to run in the Windows Command Prompt or PowerShell terminal. It uses the msvcrt module for non-blocking keyboard input and os.system('cls') for clearing the screen, which are specific to Windows environments.
Features:
- Snake movement (Up, Down, Left, Right using W, A, S, D).
- Food generation.
- Snake grows when it eats food.
- Game over if the snake hits the wall or itself.
- Score display.
Code (snake_game.py):
import msvcrt # For non-blocking keyboard input (Windows specific)
import os # For clearing the screen (cls)
import time # For pausing the game loop
import random # For placing food
# --- Game Settings ---
WIDTH = 40 # Width of the game area (characters)
HEIGHT = 20 # Height of the game area (characters)
DELAY = 0.15 # Speed of the snake (lower is faster)
# --- Game Characters ---
SNAKE_HEAD_CHAR = 'O'
SNAKE_BODY_CHAR = 'o'
FOOD_CHAR = 'F'
WALL_CHAR_H = '-'
WALL_CHAR_V = '|'
WALL_CHAR_C = '+' # Corner
EMPTY_CHAR = ' '
# --- Game State ---
score = 0
snake = [] # List of (x, y) coordinates for the snake segments
snake_dir = (1, 0) # Initial direction: right (dx, dy)
food_pos = (0, 0) # (x, y) coordinate for the food
game_over = False
def setup_game():
"""Initializes the game state."""
global score, snake, snake_dir, food_pos, game_over
score = 0
game_over = False
snake_dir = (1, 0) # Start moving right
# Initial snake position (center)
start_x = WIDTH // 2
start_y = HEIGHT // 2
snake = [
(start_x, start_y), # Head
(start_x - 1, start_y), # Body segment 1
(start_x - 2, start_y) # Body segment 2
]
place_food()
def place_food():
"""Places food randomly, ensuring it's not on the snake."""
global food_pos
while True:
x = random.randint(1, WIDTH - 2) # Avoid walls
y = random.randint(1, HEIGHT - 2) # Avoid walls
food_pos = (x, y)
if food_pos not in snake:
break # Found a valid spot
def draw_game():
"""Clears the screen and draws the current game state."""
os.system('cls') # Clear the Windows terminal
# Create a 2D buffer for drawing
# Initialize with empty spaces
buffer = [[EMPTY_CHAR for _ in range(WIDTH)] for _ in range(HEIGHT)]
# Draw Walls
for x in range(WIDTH):
buffer[0][x] = WALL_CHAR_H # Top wall
buffer[HEIGHT-1][x] = WALL_CHAR_H # Bottom wall
for y in range(HEIGHT):
buffer[y][0] = WALL_CHAR_V # Left wall
buffer[y][WIDTH-1] = WALL_CHAR_V # Right wall
# Corners
buffer[0][0] = WALL_CHAR_C
buffer[0][WIDTH-1] = WALL_CHAR_C
buffer[HEIGHT-1][0] = WALL_CHAR_C
buffer[HEIGHT-1][WIDTH-1] = WALL_CHAR_C
# Draw Food
fx, fy = food_pos
if 0 < fx < WIDTH -1 and 0 < fy < HEIGHT - 1: # Check bounds just in case
buffer[fy][fx] = FOOD_CHAR
# Draw Snake
# Body first
for i, (sx, sy) in enumerate(snake):
if 0 < sx < WIDTH -1 and 0 < sy < HEIGHT - 1: # Check bounds
if i > 0: # Body segment
buffer[sy][sx] = SNAKE_BODY_CHAR
# Head last (to overwrite body if snake is very short)
head_x, head_y = snake[0]
if 0 < head_x < WIDTH -1 and 0 < head_y < HEIGHT - 1: # Check bounds
buffer[head_y][head_x] = SNAKE_HEAD_CHAR
# Print the buffer to the console
for row in buffer:
print("".join(row))
# Print Score
print(f"Score: {score}")
if game_over:
print("--- GAME OVER ---")
print(f"Final Score: {score}")
def handle_input():
"""Checks for keyboard input and updates snake direction."""
global snake_dir
new_dir = snake_dir # Default to current direction
if msvcrt.kbhit(): # Check if a key has been pressed
try:
key = msvcrt.getch().lower() # Read the key (returns bytes, convert to lower)
# Use bytes for comparison or decode first
# Decoding might be safer if locale issues arise, but bytes are simpler here
if key == b'w' and snake_dir != (0, 1): # Go Up (cannot reverse from Down)
new_dir = (0, -1)
elif key == b's' and snake_dir != (0, -1): # Go Down (cannot reverse from Up)
new_dir = (0, 1)
elif key == b'a' and snake_dir != (1, 0): # Go Left (cannot reverse from Right)
new_dir = (-1, 0)
elif key == b'd' and snake_dir != (-1, 0): # Go Right (cannot reverse from Left)
new_dir = (1, 0)
elif key == b'q': # Quit game
global game_over
game_over = True
except Exception:
# Ignore other keys or potential errors
pass
snake_dir = new_dir
def update_game():
"""Moves the snake, checks for collisions and food."""
global snake, food_pos, score, game_over
if game_over:
return
# Calculate new head position
head_x, head_y = snake[0]
dx, dy = snake_dir
new_head = (head_x + dx, head_y + dy)
new_head_x, new_head_y = new_head
# Check for Wall Collision
if not (0 < new_head_x < WIDTH - 1 and 0 < new_head_y < HEIGHT - 1):
game_over = True
return
# Check for Self Collision
if new_head in snake[1:]: # Don't check collision with the *current* head position
game_over = True
return
# Add new head
snake.insert(0, new_head)
# Check for Food Collision
if new_head == food_pos:
score += 1
place_food() # Place new food
# Don't remove the tail - this makes the snake grow
else:
# Remove tail segment if no food was eaten
snake.pop()
# --- Main Game Loop ---
setup_game()
while not game_over:
handle_input()
update_game()
draw_game()
time.sleep(DELAY) # Control game speed
# Keep the final screen visible for a moment after game over
# Or wait for another key press
print("\nPress any key to exit.")
while True:
if msvcrt.kbhit():
msvcrt.getch() # Consume the key press
break
time.sleep(0.1)
How to Run:
- Save: Save the code above as a Python file (e.g.,
snake_game.py).
- Open Terminal: Open a Command Prompt (
cmd.exe) or PowerShell on your Windows machine.
- Navigate: Use the
cd command to navigate to the directory where you saved the file. For example:
cd C:\Users\YourUsername\Documents\PythonGames
- Run: Execute the script using Python:
python snake_game.py
Controls:
W: Move Up
A: Move Left
S: Move Down
D: Move Right
Q: Quit Game (optional, added for convenience)
Enjoy your basic terminal Snake game!