Below is a compact but fully-working Snake game written in Python with the popular Pygame library. Copy the whole snippet into snake.py, install pygame (pip install pygame) and run python snake.py.
# snake.py
import pygame, sys, random
pygame.init()
# --- Config -------------------------------------------------------------
CELL_SIZE = 25 # Size of one grid square (px)
GRID_W, GRID_H = 24, 20 # Grid dimensions (# of squares)
SCREEN_W, SCREEN_H = GRID_W*CELL_SIZE, GRID_H*CELL_SIZE
FPS = 10 # Initial speed (frames/sec)
BG_COLOR = (30, 30, 30)
SNAKE_COLOR = (0, 220, 0)
FOOD_COLOR = (220, 30, 30)
FONT = pygame.font.SysFont("consolas", 24, bold=True)
# ------------------------------------------------------------------------
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
clock = pygame.time.Clock()
pygame.display.set_caption("Snake (Python + Pygame)")
def random_position():
return (random.randint(0, GRID_W-1), random.randint(0, GRID_H-1))
class Snake:
def __init__(self):
self.body = [(GRID_W//2, GRID_H//2)]
self.direction = (1, 0) # moving right
self.grow_next = False
def move(self):
head_x, head_y = self.body[0]
dx, dy = self.direction
new_head = ((head_x + dx) % GRID_W, (head_y + dy) % GRID_H)
# Check self-collision
if new_head in self.body:
return False
self.body.insert(0, new_head)
if not self.grow_next:
self.body.pop() # remove tail
else:
self.grow_next = False # consumed the grow token
return True
def change_dir(self, new_dx, new_dy):
# Prevent 180° turn
if (new_dx, new_dy) == (-self.direction[0], -self.direction[1]):
return
self.direction = (new_dx, new_dy)
class Food:
def __init__(self, snake_cells):
self.position = self.spawn(snake_cells)
def spawn(self, snake_cells):
pos = random_position()
while pos in snake_cells: # ensure not inside snake
pos = random_position()
return pos
def draw(self):
x, y = self.position
rect = pygame.Rect(x*CELL_SIZE, y*CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, FOOD_COLOR, rect)
def draw_grid():
for x in range(0, SCREEN_W, CELL_SIZE):
pygame.draw.line(screen, (40,40,40), (x,0), (x,SCREEN_H))
for y in range(0, SCREEN_H, CELL_SIZE):
pygame.draw.line(screen, (40,40,40), (0,y), (SCREEN_W,y))
def draw_snake(snake):
for idx, (x,y) in enumerate(snake.body):
rect = pygame.Rect(x*CELL_SIZE, y*CELL_SIZE, CELL_SIZE, CELL_SIZE)
color = SNAKE_COLOR if idx else (0, 255, 80) # brighter head
pygame.draw.rect(screen, color, rect)
def game_over_screen(score):
msg1 = FONT.render("GAME OVER", True, (255,50,50))
msg2 = FONT.render(f"Score: {score}", True, (200,200,200))
msg3 = FONT.render("Press R to Restart / Q to Quit", True, (200,200,200))
screen.blit(msg1, msg1.get_rect(center=(SCREEN_W/2, SCREEN_H/2-40)))
screen.blit(msg2, msg2.get_rect(center=(SCREEN_W/2, SCREEN_H/2)))
screen.blit(msg3, msg3.get_rect(center=(SCREEN_W/2, SCREEN_H/2+40)))
pygame.display.flip()
wait_restart()
def wait_restart():
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT: pygame.quit(); sys.exit()
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_r: main() # restart
if e.key == pygame.K_q: pygame.quit(); sys.exit()
clock.tick(15)
def main():
snake = Snake()
food = Food(snake.body)
score = 0
speed = FPS
while True:
# --- Input -------------------------------------------------------
for e in pygame.event.get():
if e.type == pygame.QUIT: pygame.quit(); sys.exit()
if e.type == pygame.KEYDOWN:
if e.key in (pygame.K_RIGHT, pygame.K_d): snake.change_dir( 1, 0)
elif e.key in (pygame.K_LEFT, pygame.K_a): snake.change_dir(-1, 0)
elif e.key in (pygame.K_UP, pygame.K_w): snake.change_dir( 0,-1)
elif e.key in (pygame.K_DOWN, pygame.K_s): snake.change_dir( 0, 1)
elif e.key == pygame.K_ESCAPE: pygame.quit(); sys.exit()
# --- Update ------------------------------------------------------
if not snake.move(): # self-hit? -> game over
game_over_screen(score)
# Check food collision
if snake.body[0] == food.position:
snake.grow_next = True
score += 1
speed = min(25, speed + 0.5) # gradually speed up
food = Food(snake.body)
# --- Draw --------------------------------------------------------
screen.fill(BG_COLOR)
draw_grid()
draw_snake(snake)
food.draw()
score_text = FONT.render(f"{score}", True, (180,180,180))
screen.blit(score_text, (8,8))
pygame.display.flip()
clock.tick(speed)
if __name__ == "__main__":
main()
How it works (quick overview):
- Grid logic – The game treats the window as a GRID_W × GRID_H grid of square cells.
- Snake body – List of (x, y) tuples; head is body[0]. On every tick we insert a new head and pop the tail (unless we just ate food).
- Food – Randomly spawns in any empty cell.
- Wrapping – The snake wraps around the screen edges thanks to modulo math (
% GRID_W/GRID_H).
- Controls – Arrow keys or WASD. ESC to quit. After you lose, press R to restart or Q to exit.
Enjoy hacking on it! Ideas to extend:
• Add obstacles or walls
• Implement a high-score file
• Animate smoother snake motion (use rectangles with interpolation)
• Add sound effects or a menu system 🎵