Python

 

Introduction

The Snake game is one of the most popular arcade games that can be played on any platform. It involves controlling a snake on the screen, eating food to grow longer, and avoiding collisions with the walls or the snake’s own body. In this guide, we will learn how to create this classic game using Python and the Pygame library.

In this tutorial, we will cover the key aspects of game development, including handling user input, detecting collisions, creating game objects, and updating the screen. By the end of this tutorial, you will have a fully functional Snake game that you can customize and expand on your own!

Objective

The objective of this project is to create a simple version of the Snake game using Python and the Pygame library. The player will control a snake, which grows in length as it eats food. The game ends if the snake collides with the wall or itself. Players can restart the game after it ends.

Code: Python Snake Game


import pygame
import time
import random

# Initialize Pygame
pygame.init()

# Set up the screen
width = 600
height = 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Snake Game')

# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

# Snake block size and speed
snake_block = 10
snake_speed = 15

# Font settings
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)

# Score function
def your_score(score):
    value = score_font.render("Your Score: " + str(score), True, white)
    screen.blit(value, [0, 0])

# Snake function
def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(screen, green, [x[0], x[1], snake_block, snake_block])

# Message function
def message(msg, color):
    mesg = font_style.render(msg, True, color)
    screen.blit(mesg, [width / 6, height / 3])

# Main function
def gameLoop():
    game_over = False
    game_close = False

    # Snake starting position
    x1 = width / 2
    y1 = height / 2
    x1_change = 0
    y1_change = 0

    # Snake body
    snake_List = []
    Length_of_snake = 1

    # Food position
    foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0

    # Game loop
    while not game_over:

        while game_close:
            screen.fill(blue)
            message("You Lost! Press Q-Quit or C-Play Again", red)
            your_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= width or x1 < 0 or y1 >= height or y1 < 0: game_close = True x1 += x1_change y1 += y1_change screen.fill(blue) pygame.draw.rect(screen, white, [foodx, foody, snake_block, snake_block]) snake_Head = [] snake_Head.append(x1) snake_Head.append(y1) snake_List.append(snake_Head) if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        your_score(Length_of_snake - 1)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1

        pygame.time.Clock().tick(snake_speed)

    pygame.quit()
    quit()

# Run the game
gameLoop()
        

Program Explanation

Here’s a breakdown of the main components of the Snake game:

  • Initialization: We initialize Pygame, set up the screen dimensions, and define colors for the game.
  • Snake Movement: The snake is controlled using the arrow keys. The snake moves in a given direction, and its position is updated on the screen.
  • Game Over Conditions: The game ends when the snake collides with the wall or itself.
  • Food Mechanism: Each time the snake eats the food, the snake grows longer, and new food is randomly placed on the screen.
  • Game Loop: The game keeps running in a loop, checking for events (like key presses) and updating the screen continuously until the player quits or restarts the game.

How to Run the Program

  1. Ensure you have Python installed on your system. You can download it from here.
  2. Install Pygame using the command: pip install pygame
  3. Copy and paste the provided Python code into a text file and save it with a .py extension, for example, snake_game.py.
  4. Run the game by opening a terminal or command prompt and typing: python snake_game.py.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)