# 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
# Check self collision if snake.count(new_head) > 1: game_over = True def game_loop(): global game_over, next_dir snake game command prompt code
generate_food() clear_screen() set_cursor_visible(False) set_title("Snake Game - Terminal")
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). # Top border top = '+' + '-'*WIDTH
# 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])
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() PowerShell works too
# Draw snake for i, (sx, sy) in enumerate(snake): if i == 0: lines[sy][sx] = '@' # head else: lines[sy][sx] = 'O'
# Apply queued direction (no 180° turns) if next_dir: if (next_dir == 'up' and direction != 'down') or \ (next_dir == 'down' and direction != 'up') or \ (next_dir == 'left' and direction != 'right') or \ (next_dir == 'right' and direction != 'left'): direction = next_dir
# Draw food if food: fx, fy = food lines[fy][fx] = '*'
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.

