# Top border top = '+' + '-'*WIDTH + '+' print(top) for y in range(HEIGHT): line = '|' + ''.join(lines[y]) + '|' print(line) bottom = '+' + '-'*WIDTH + '+' print(bottom) print(f"Score: score Use arrow keys. Press Q to quit.") def update(): global snake, direction, next_dir, game_over, score, food
while not game_over: # Handle input key = get_key() if key == 'quit': game_over = True break if key in ['up', 'down', 'left', 'right']: next_dir = key # Game update at fixed intervals now = time.time() if now - last_tick >= TICK_TIME: update() last_tick = now # Draw everything gotoxy(0, 0) draw() time.sleep(0.01) # small delay to reduce CPU usage
generate_food() clear_screen() set_cursor_visible(False) set_title("Snake Game - Terminal")
def set_cursor_visible(visible): if os.name == 'nt': # Windows: hide/show cursor using ANSI or console API (simplified) sys.stdout.write('\033[?25l' if not visible else '\033[?25h') else: sys.stdout.write('\033[?25l' if not visible else '\033[?25h') sys.stdout.flush() snake game command prompt code
# Move snake snake.appendleft(new_head) if not ate: snake.pop() else: score += 1 generate_food()
def gotoxy(x, y): """Move cursor to column x, row y (0-indexed)""" sys.stdout.write(f'\033[y+1;x+1H')
# Draw food if food: fx, fy = food lines[fy][fx] = '*' # Top border top = '+' + '-'*WIDTH
WIDTH = 40 # Playfield width (columns) HEIGHT = 20 # Playfield height (rows) TICK_TIME = 0.12 # Speed – lower = faster snake | Problem | Fix | |---------|-----| | Arrow keys not working on Windows | Make sure you are in a real Command Prompt (not some embedded terminal). PowerShell works too. | | No output / cursor flickering | On some terminals, try running fullscreen or increase TICK_TIME to 0.15. | | “termios” module not found on Windows | That’s fine – the Windows branch uses msvcrt . | | Game runs too fast / slow | Adjust TICK_TIME (lower = faster). | Example Gameplay Screenshot (Text Representation) +----------------------------------------+ | | | O | | @ | | | | * | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | +----------------------------------------+ Score: 5 Use arrow keys. Press Q to quit.
It uses only the standard library ( curses for Unix-like systems, but for Windows we use a cross‑platform approach with msvcrt and manual console handling).
# Check self collision if snake.count(new_head) > 1: game_over = True def game_loop(): global game_over, next_dir | | No output / cursor flickering |
# Check food collision ate = (new_head == food)
# Calculate new head head = snake[0] if direction == 'up': new_head = (head[0], head[1] - 1) elif direction == 'down': new_head = (head[0], head[1] + 1) elif direction == 'left': new_head = (head[0] - 1, head[1]) else: # right new_head = (head[0] + 1, head[1])
I’ll provide a that works on Windows (Command Prompt / PowerShell) and Linux/macOS terminals. Full Code (Save as snake_game.py ) """ SNAKE GAME - Command Prompt / Terminal Version Works on Windows (cmd), Linux, macOS. Uses only standard library. """ import os import sys import time import random import threading from collections import deque --- Platform-specific input handling --- if os.name == 'nt': # Windows import msvcrt def get_key(): if msvcrt.kbhit(): key = msvcrt.getch() if key == b'\xe0': # arrow keys prefix key = msvcrt.getch() if key == b'H': return 'up' elif key == b'P': return 'down' elif key == b'K': return 'left' elif key == b'M': return 'right' elif key == b'q' or key == b'Q': return 'quit' return None else: # Unix-like (Linux, macOS) import termios, tty def get_key(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) if ch == '\x1b': # escape sequence next = sys.stdin.read(2) if next == '[A': return 'up' elif next == '[B': return 'down' elif next == '[C': return 'right' elif next == '[D': return 'left' elif ch == 'q' or ch == 'Q': return 'quit' finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return None --- Console control helpers --- def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear')
# Check wall collision if new_head[0] < 0 or new_head[0] >= WIDTH or new_head[1] < 0 or new_head[1] >= HEIGHT: game_over = True return
def set_title(title): if os.name == 'nt': os.system(f'title title') else: sys.stdout.write(f'\033]2;title\007') WIDTH = 40 HEIGHT = 20 SNAKE_START = [(WIDTH//2, HEIGHT//2)] START_DIR = 'right' TICK_TIME = 0.12 # seconds per move --- Game state --- snake = deque(SNAKE_START) direction = START_DIR next_dir = START_DIR food = None score = 0 game_over = False --- Helper functions --- def generate_food(): global food while True: fx = random.randint(0, WIDTH-1) fy = random.randint(0, HEIGHT-1) if (fx, fy) not in snake: food = (fx, fy) break