make a snake game using python and pygame with code examples

Python is a great language to learn programming for everyone, including beginners. Python is extremely user-friendly and easy to pick up, with its syntax designed to be more like plain English, making it easier to read and understand. With Python, you can create games, applications, web scraping scripts, and much more.

Pygame is a Python library used for making games. It builds on the low-level capabilities of SDL (Simple DirectMedia Layer), allowing game developers to focus on the game’s logic, instead of the underlying hardware. Pygame also provides some high-level features, such as image and sound support, which help to make the game more visually pleasing.

In this article, we will create a classic Snake game using Python and Pygame. We will cover each step, from setting up the environment to building the game mechanics.

Setting up the environment

First, we need to install the Pygame module. We can install it using the pip package manager by running the following command in the terminal:

pip install pygame

After installing Pygame, we will create a new file called snake.py. This is where we will write the code for our game. To start, we need to import the Pygame module and initialize it with the following code.

import pygame

pygame.init()

Now that we have initialized Pygame, we can proceed to the game screen.

The game screen

The game screen is where the user will see and interact with the game. We will create a new window, set the size of the window, give it a title, and set the background color.

width = 500
height = 500

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")

background_color = (255, 255, 255) # White
screen.fill(background_color)
pygame.display.update()

The pygame.display.set_mode() function creates a new window with dimensions of width and height. We then set the title of the window to "Snake Game" with pygame.display.set_caption(). Next, we set the background color of the window to white with the color code (255, 255, 255) and fill the screen with the screen.fill() method. We then update the display with pygame.display.update().

The game loop

The game loop is responsible for updating the game state, handling user input, and rendering the game. We will initialize the game loop with the following code.

game_over = False

while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

We initialize game_over to False. The while loop will continue running until game_over becomes True. The for loop will run through each event in the event queue and check if the event is a QUIT event. If the event is a QUIT event, we set game_over to True, breaking out of the game loop.

The Snake

Next, we will create the snake. The snake will be made up of several squares, which will be represented by rectangles.

snake_block_size = 10
snake_color = (0, 0, 0) # Black

snake_list = []
snake_length = 1

initial_x = width / 2
initial_y = height / 2

snake_head = [initial_x, initial_y]
snake_list.append(snake_head)

while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

    # Draw the snake
    for block in snake_list:
        pygame.draw.rect(screen, snake_color, [block[0], block[1], snake_block_size, snake_block_size])

    pygame.display.update()

We set the snake_block_size to 10 and the snake_color to black. We then initialize an empty list snake_list, which will store the coordinates of the snake’s body.

Next, we initialize the snake_length to 1, and the initial position of the snake’s head to the center of the screen. We append the coordinates of the snake’s head to snake_list.

In the game loop, we iterate over snake_list and draw each block in black using pygame.draw.rect(). We then update the display.

Moving the Snake

Now that we have the snake on the screen, we can move it. We will set up keyboard input to control the snake’s movement.

snake_speed = 15

while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

        # Check for arrow key input
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -snake_block_size
                y_change = 0
            elif event.key == pygame.K_RIGHT:
                x_change = snake_block_size
                y_change = 0
            elif event.key == pygame.K_UP:
                x_change = 0
                y_change = -snake_block_size
            elif event.key == pygame.K_DOWN:
                x_change = 0
                y_change = snake_block_size

    # Update the snake's position based on keyboard input
    snake_head[0] += x_change
    snake_head[1] += y_change

    # Draw the snake
    for block in snake_list:
        pygame.draw.rect(screen, snake_color, [block[0], block[1], snake_block_size, snake_block_size])

    pygame.display.update()

We set the snake_speed to 15. In the game loop, we check for arrow key input using pygame.KEYDOWN. Based on the key pressed, we set the x_change and y_change variables.

We then add x_change and y_change to the snake_head coordinates to update the position of the snake’s head. We then draw the snake’s body with pygame.draw.rect(). Finally, we update the display.

Growing the Snake

When the snake eats food, it should grow longer. We will add this functionality to the game.

# Generate random food coordinates
food_x = round((width - snake_block_size) / 10.0) * 10.0
food_y = round((height - snake_block_size) / 10.0) * 10.0

food_color = (255, 0, 0) # Red

while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

        # Check for arrow key input
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -snake_block_size
                y_change = 0
            elif event.key == pygame.K_RIGHT:
                x_change = snake_block_size
                y_change = 0
            elif event.key == pygame.K_UP:
                x_change = 0
                y_change = -snake_block_size
            elif event.key == pygame.K_DOWN:
                x_change = 0
                y_change = snake_block_size

    # Update the snake's position based on keyboard input
    snake_head[0] += x_change
    snake_head[1] += y_change

    # Check if the snake has hit the wall
    if snake_head[0] >= width or snake_head[0] < 0 or snake_head[1] >= height or snake_head[1] < 0:
        game_over = True

    # Check if the snake has hit itself
    for block in snake_list[1:]:
        if snake_head[0] == block[0] and snake_head[1] == block[1]:
            game_over = True

    # Check if the snake has eaten the food
    if snake_head[0] == food_x and snake_head[1] == food_y:
        food_x = round((width - snake_block_size) / 10.0) * 10.0
        food_y = round((height - snake_block_size) / 10.0) * 10.0
        snake_length += 1

    # Remove the snake's tail
    if len(snake_list) > snake_length:
        del snake_list[0]

    # Add the snake's new position to the list
    snake_list.append(list(snake_head))

    # Draw the snake
    for block in snake_list:
        pygame.draw.rect(screen, snake_color, [block[0], block[1], snake_block_size, snake_block_size])

    # Draw the food
    pygame.draw.rect(screen, food_color, [food_x, food_y, snake_block_size, snake_block_size])

    pygame.display.update()

We set the food_x and food_y to randomly generated coordinates, which are rounded to the nearest 10 pixels. We set the food_color to red.

In the game loop, we check if the snake’s head has hit the wall using the width and height variables. We also check if the snake has hit itself by iterating over snake_list[1:]. If the snake has hit the wall or itself, we set game_over to True.

We check if the snake has eaten the food by checking if the snake_head coordinates match the food_x and food_y coordinates. If the snake has eaten the food, we update the food_x and food_y coordinates to randomly generated coordinates and increase snake_length by 1.

We remove the snake’s tail if its length is greater than snake_length using del snake_list[0]. We then add the snake’s new position to the list with snake_list.append(list(snake_head)). Finally, we draw the snake’s body and the food with pygame.draw.rect().

Conclusion

In this article, we have created a classic Snake game using Python and Pygame. We have covered each step of the process, from setting up the environment to building the game mechanics. Hopefully, this article provides a good introduction to Pygame game development and encourages you to explore further. The complete code for the game can be found below.

import pygame

pygame.init()

width = 500
height = 500

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")

background_color = (255, 255, 255) # White
screen.fill(background_color)
pygame.display.update()

snake_block_size = 10
snake_color = (0, 0, 0) # Black

snake_list = []
snake_length = 1

initial_x = width / 2
initial_y = height / 2

snake_head = [initial_x, initial_y]
snake_list.append(snake_head)

snake_speed = 15

food_x = round((width - snake_block_size) / 10.0) * 10.0
food_y = round((height - snake_block_size) / 10.0) * 10.0

food_color = (255, 0, 0) # Red

game_over = False

while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

        # Check for arrow key input
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -snake_block_size
                y_change = 0
            elif event.key == pygame.K_RIGHT:
                x_change = snake_block_size
                y_change = 0
            elif event.key == pygame.K_UP:
                x_change = 0
                y_change = -snake_block_size
            elif event.key == pygame.K_DOWN:
                x_change = 0
                y_change = snake_block_size

    # Update the snake's position based on keyboard input
    snake_head[0] += x_change
    snake_head[1] += y_change

    # Check if the snake has hit the wall
    if snake_head[0] >= width or snake_head[0] < 0 or snake_head[1] >= height or snake_head[1] < 0:
        game_over = True

    # Check if the snake has hit itself
    for block in snake_list[1:]:
        if snake_head[0] == block[0] and snake_head[1] == block[1]:
            game_over = True

    # Check if the snake has eaten the food
    if snake_head[0] == food_x and snake_head[1] == food_y:
        food_x = round((width - snake_block_size) / 10.0) * 10.0
        food_y = round((height - snake_block_size) / 10.0) * 10.0
        snake_length += 1

    # Remove the snake's tail
    if len(snake_list) > snake_length:
        del snake_list[0]

    # Add the snake's new position to the list
    snake_list.append(list(snake_head))

    # Draw the snake
    screen.fill(background_color)
    for block in snake_list:
        pygame.draw.rect(screen, snake_color, [block[0], block[1], snake_block_size, snake_block_size])

    # Draw the food
    pygame.draw.rect(screen, food_color, [food_x, food_y, snake_block_size, snake_block_size])

    pygame.display.update()

pygame.quit()

I can provide more information on the previous topics covered in the article.

Python

Python is a popular high-level programming language that is used in various applications, including scientific computing, web development, and artificial intelligence. It was created in the late 1980s by Guido van Rossum, and its syntax is easy to read and write, making it an excellent choice for beginners.

Python supports object-oriented programming, structured programming, and functional programming. It also provides several libraries and frameworks for specific use cases. Python is an interpreted language, which means the code is compiled and executed on-the-fly.

Python is a great language for game development because it is easy to read, write, and debug. Pygame, a module available for Python, provides a lightweight library for development of games and multimedia applications.

Pygame

Pygame is a set of Python modules used for game and multimedia programming. It is a cross-platform library based on the Simple DirectMedia Layer (SDL) library, which provides low-level access to graphics, audio, and input devices.

Pygame provides several features that make it easy to create games, including image and sound support, collision detection, and keyboard and mouse input. It also supports several languages, including Python, C, and C++. Pygame is compatible with several platforms, including Windows, MacOS, and Linux.

To use Pygame, you need to install it first. You can install Pygame using pip, the package installer for Python, by running the following command in the terminal:

pip install pygame

Once installed, you can import Pygame into your Python program and create a game window, add game objects, and handle input events.

Game Screens

A screen is a window on which a game is displayed. In Pygame, you can create and manipulate screens using the Pygame.display module. To create a screen, you need to call the set_mode() function, which creates a new window with the specified size.

import pygame

pygame.init()

width = 500
height = 500

screen = pygame.display.set_mode((width, height))

The set_mode() function takes a tuple with two integers: the width and height of the window. Once you have created the screen, you can set the title of the window using the set_caption() function.

pygame.display.set_caption("Snake Game")

You can also set the background color of the window using the fill() method of the Surface type. The Surface type represents an image on which Pygame can draw.

background_color = (255, 255, 255) # White
screen.fill(background_color)

To update the display, you need to call the update() method of the display module.

pygame.display.update()

Game Loop

The game loop is the heart of any game. It handles the game logic, input processing, and rendering. In Pygame, the game loop is implemented using a while loop.

while not game_over:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

    # Update game state

    # Render frame
    pygame.display.update()

The loop runs until the game is over. In each iteration, it handles the events, updates the game state, and renders a frame. The event.get() method returns a list of all the events in the queue. By iterating over this list, we can handle each event.

Snake Game

The Snake game is a classic arcade game in which the player controls a snake that moves around the screen, eating food to grow longer while avoiding collision with the walls or the snake’s body. The player loses the game when the snake hits the wall or itself.

In this article, we created a simple Snake game using Python and Pygame. We covered each step of the process, from setting up the environment to building game mechanics. We also introduced various concepts related to game programming, such as game screens and the game loop.

The code for the game is simple and easy to follow. However, there is still room for improvement. For example, we could implement scoring, add levels with increasing difficulty, and introduce different obstacles and power-ups.

Popular questions

  1. What is Pygame, and how is it used in game development?

Pygame is a set of Python modules used for game and multimedia programming. It is a cross-platform library based on the Simple DirectMedia Layer (SDL) library, which provides low-level access to graphics, audio, and input devices. Pygame provides several features that make it easy to create games, including image and sound support, collision detection, and keyboard and mouse input.

  1. What is the game loop in Pygame?

The game loop is the heart of any game. It handles the game logic, input processing, and rendering. In Pygame, the game loop is implemented using a while loop.

  1. How do you create a game screen in Pygame?

To create a screen in Pygame, you need to use the set_mode() function, which creates a new window with the specified size. The set_mode() function takes a tuple with two integers: the width and height of the window. Once you have created the screen, you can set the title of the window using the set_caption() function and set the background color using the fill() method.

  1. How do you move the snake in the Snake game?

To move the snake in the Snake game, we handle arrow key input using pygame.KEYDOWN. Based on the key pressed, we set the x_change and y_change variables. We then add `x

Tag

Python-SnakeGame

As an experienced software engineer, I have a strong background in the financial services industry. Throughout my career, I have honed my skills in a variety of areas, including public speaking, HTML, JavaScript, leadership, and React.js. My passion for software engineering stems from a desire to create innovative solutions that make a positive impact on the world. I hold a Bachelor of Technology in IT from Sri Ramakrishna Engineering College, which has provided me with a solid foundation in software engineering principles and practices. I am constantly seeking to expand my knowledge and stay up-to-date with the latest technologies in the field. In addition to my technical skills, I am a skilled public speaker and have a talent for presenting complex ideas in a clear and engaging manner. I believe that effective communication is essential to successful software engineering, and I strive to maintain open lines of communication with my team and clients.
Posts created 3227

Leave a Reply

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top