Game Development 13 min read

Build a Classic Snake Game in Python with Pygame – Step-by-Step Tutorial

Learn how to create a fully functional Snake game in Python using Pygame, covering installation, core game logic, rendering, collision detection, and game loop implementation, with detailed code examples and explanations to help beginners build and customize their own classic arcade game.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Build a Classic Snake Game in Python with Pygame – Step-by-Step Tutorial

Introduction

As a Python beginner, it's easy to feel you need to master everything before coding. Instead, find real problems and implement solutions, such as using Python for calculus or building a simple calculator, and gradually improve your programming skills.

Game Overview

The tutorial guides you to create a simple Snake game where the snake moves to eat food without hitting walls or itself.

Game screenshot
Game screenshot

Installation

pip install -U pygame

Key Logic

The snake's body is represented by a list of coordinate tuples. A move function updates the head position based on direction and handles growth when food is eaten.

Movement logic: if the snake hasn't eaten, remove the last coordinate; then insert a new head based on direction (x, y). The snake cannot reverse direction.

Food detection: when the snake's head coordinates match the food's coordinates, the score increases and new food is generated at a random position not occupied by the snake.

Game over detection: the game ends if the snake collides with the wall or its own body, which is detected by comparing the length of the snake's coordinate list with the length of a set created from it.

Snake Module

# Snake class
class Snack(object):
    def __init__(self):
        self.item = [(3, 25), (2, 25), (1, 25), (1,24), (1,23)]
        self.x = 0
        self.y = -1

    def move(self, enlarge):
        if not enlarge:
            self.item.pop()
        head = (self.item[0][0] + self.x, self.item[0][1] + self.y)
        self.item.insert(0, head)

    def eat_food(self, food):
        global score
        snack_x, snack_y = self.item[0]
        food_x, food_y = food.item
        if food_x == snack_x and food_y == snack_y:
            score += 100
            return 1
        else:
            return 0

    def toward(self, x, y):
        if self.x * x >= 0 and self.y * y >= 0:
            self.x = x
            self.y = y

    def get_head(self):
        return self.item[0]

    def draw(self, screen):
        # draw head
        pygame.draw.circle(screen, (255,0,0), (10+20*self.item[0][0], 10+20*self.item[0][1]), 15, 15)
        # draw body
        for i, j in self.item[1:]:
            pygame.draw.circle(screen, (255,255,0), (10+20*i, 10+20*j), 10, 10)

Food Module

# Food class
class Food(object):
    def __init__(self):
        self.item = (4,5)

    def _draw(self, screen, i, j):
        pygame.draw.circle(screen, (255,0,255), (10+20*i, 10+20*j), 10, 10)

    def update(self, screen, enlarge, snack):
        if enlarge:
            self.item = np.random.randint(1, BOARDWIDTH-2), np.random.randint(1, BOARDHEIGHT-2)
            while self.item in snack.item:
                self.item = np.random.randint(1, BOARDWIDTH-2), np.random.randint(1, BOARDHEIGHT-2)
        self._draw(screen, self.item[0], self.item[1])

Board Initialization

# Initialize board
def init_board(screen):
    board_width = BOARDWIDTH
    board_height = BOARDHEIGHT
    color = (10,255,255)
    width = 0
    for i in range(board_width):
        pos = (i*20, 0, 20, 20)
        pygame.draw.rect(screen, color, pos, width)
        pos = (i*20, (board_height-1)*20, 20, 20)
        pygame.draw.rect(screen, color, pos, width)
    for i in range(board_height-1):
        pos = (0, 20+i*20, 20, 20)
        pygame.draw.rect(screen, color, pos, width)
        pos = ((board_width-1)*20, 20+i*20, 20, 20)
        pygame.draw.rect(screen, color, pos, width)

Game Over Module

# Game over detection
def game_over(snack):
    broad_x, broad_y = snack.get_head()
    flag = 0
    old = len(snack.item)
    new = len(set(snack.item))
    if new < old:
        flag = 1
    if broad_x == 0 or broad_x == BOARDWIDTH-1:
        flag = 1
    if broad_y == 0 or broad_y == BOARDHEIGHT-1:
        flag = 1
    return True if flag else False

Game Initialization

# Game initialization
def game_init():
    pygame.init()
    screen = pygame.display.set_mode((BOARDWIDTH*20, BOARDHEIGHT*20))
    pygame.display.set_caption('Snake Game')
    return screen

Main Game Loop

# Main game function
def game(screen):
    snack = Snack()
    food = Food()
    font = pygame.font.SysFont('SimHei', 20)
    is_fail = 0
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()
        screen.fill((0,0,100))
        init_board(screen)
        keys = pygame.key.get_pressed()
        press(keys, snack)
        if is_fail:
            font2 = pygame.font.Font(None, 40)
            print_text(screen, font, 0, 0, text)
            print_text(screen, font2, 400, 200, "GAME OVER")
        if not is_fail:
            enlarge = snack.eat_food(food)
            text = u"score: {}  Python爬虫".format(score)
            print_text(screen, font, 0, 0, text)
            food.update(screen, enlarge, snack)
            snack.move(enlarge)
            is_fail = game_over(snack=snack)
            snack.draw(screen)
        pygame.display.update()
        time.sleep(0.1)

With this tutorial you can run the Snake game and further extend it with features such as background music or improved graphics.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonGame DevelopmentSnake GamePygame
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.