Below is a minimal but fully-playable Snake clone using only the Python standard library (no external packages).
Save it as snake.py and run with:
Use the arrow keys to steer, press Q to quit, and R to restart after a game-over.
python
#!/usr/bin/env python3
"""
Classic Snake game in pure Python (standard library only).
Arrow keys to move, Q to quit, R to restart.
"""
import random
import sys
import tty
import termios
import time
import os
# ---------- CONFIG ----------
WIDTH, HEIGHT = 60, 20 # play-field size (characters)
INITIAL_SPEED = 0.15 # seconds between frames
# ----------------------------
# ---------- UTILS ----------
class _Getch:
"""Non-blocking single-key reader."""
def __call__(self):
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return ch
getch = _Getch()
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
# ---------- GAME ----------
class SnakeGame:
def __init__(self):
self.reset()
def reset(self):
self.snake = [(WIDTH//2, HEIGHT//2)]
self.dx, self.dy = 1, 0
self.food = self._new_food()
self.game_over = False
self.score = 0
def _new_food(self):
while True:
pos = (random.randint(1, WIDTH-2), random.randint(1, HEIGHT-2))
if pos not in self.snake:
return pos
def step(self):
if self.game_over:
return
# compute new head
hx, hy = self.snake[0]
nx, ny = hx + self.dx, hy + self.dy
# collision with walls
if nx <= 0 or nx >= WIDTH-1 or ny <= 0 or ny >= HEIGHT-1:
self.game_over = True
return
# collision with self
if (nx, ny) in self.snake:
self.game_over = True
return
# move snake
self.snake.insert(0, (nx, ny))
# food eaten?
if (nx, ny) == self.food:
self.score += 1
self.food = self._new_food()
else:
self.snake.pop()
def change_dir(self, key):
"""Change direction if not opposite."""
dirs = {'\x1b[A': (0, -1), '\x1b[B': (0, 1),
'\x1b[C': (1, 0), '\x1b[D': (-1, 0)}
if key in dirs:
ndx, ndy = dirs[key]
if (ndx, ndy) != (-self.dx, -self.dy):
self.dx, self.dy = ndx, ndy
def draw(self):
clear()
print(f"Score: {self.score} (Q=quit R=restart)")
# top wall
print('#' * WIDTH)
for y in range(1, HEIGHT-1):
line = ['#']
for x in range(1, WIDTH-1):
if (x, y) == self.food:
line.append('*')
elif (x, y) in self.snake:
line.append('O' if (x, y) == self.snake[0] else 'o')
else:
line.append(' ')
line.append('#')
print(''.join(line))
# bottom wall
print('#' * WIDTH)
if self.game_over:
print("GAME OVER! Press R to restart or Q to quit.")
def run(self):
while True:
self.draw()
if self.game_over:
key = getch()
if key.lower() == 'q':
break
if key.lower() == 'r':
self.reset()
continue
# non-blocking arrow key read (3-byte escape sequences)
key = getch()
if key == '\x1b':
key += getch() + getch()
self.change_dir(key)
if key.lower() == 'q':
break
self.step()
time.sleep(INITIAL_SPEED)
if __name__ == "__main__":
SnakeGame().run()