Contents:
- Installing Pygame and Understanding It
- Initialization and Modules
- Displays and Surfaces: Drawing the Game Board
- Images and Rectangles
- Thinking Over and Describing the Game Rules
- Creating the Game from Scratch
- Running Python
- Creating the Game Board
- Creating the Snake
- Describing the Movements Snakes
- Considering obstacles - the boundaries of the playing field
- Adding food for the snake
- Increasing the length of the snake
- Adding a score display
- Final code
- What's next?

Course with employment: “Profession Python Developer»
Learn MorePygame is a widely used game development library compatible with Windows, macOS, Linux, and Android operating systems. It provides developers with powerful tools for describing gameplay and integrating various controls, such as keyboard, mouse, and accelerometers. In addition, Pygame supports sound and video effects, allowing you to create engaging and interactive gaming experiences. Using Pygame significantly simplifies the game development process, making it accessible to both beginners and experienced programmers.
Pygame was first released by Pete Shinners in October 2000. Over the 22 years of its existence, this library has formed an active developer community, and numerous books dedicated to working with Pygame have been written. As of July 2022, the latest stable version of the library is 2.1.2. Pygame continues to be a popular tool for Python game development, providing developers with all the tools they need to create engaging gaming projects.
Let's explore Pygame's structure and create our first game—the classic Snake game—in Python. This project is often chosen by students for programming courses, as it allows them to master the fundamental principles of game development. Pygame is a powerful library that simplifies the creation of games and multimedia applications. In this tutorial, we'll cover in detail the steps required to implement Snake, including setting up the environment, developing the game logic, and developing visual elements.
Installing Pygame and Getting Started
Pygame is a wrapper for the SDL (Simple DirectMedia Layer) library, rather than a standalone library. SDL enables interaction with various external devices, such as the mouse and keyboard. Pygame makes working with these devices much easier for Python developers. Pygame makes creating games and multimedia applications more accessible, allowing programmers to focus on logic and design rather than low-level hardware aspects.
Installing Pygame is a simple process. To do this, open a terminal or command prompt and enter the pip command. This command will automatically download and install Pygame on your computer, providing access to all the features and capabilities of the game development library. Make sure you have the latest version of Python installed to avoid possible installation errors.
If you encounter any installation errors, we recommend consulting the official documentation. This resource details installation instructions for different operating systems and offers solutions to common issues. Using official materials will help you quickly troubleshoot problems and complete the installation process successfully.
Initialization and Modules
The Pygame library is a set of tools written in Python and includes several modules, each of which provides access to various devices. These modules contain the methods needed to interact with devices. For example, the display module is responsible for working with graphical output on the screen, and the joystick module allows you to read data about movements and presses on the joystick. Pygame is a popular solution for game developers, as it simplifies the creation of graphics and the management of user input. Thanks to its structure and functionality, Pygame makes it easy to develop interactive applications and games in Python, making it an ideal choice for both beginners and experienced developers.
After importing Pygame, you need to initialize the library using the pygame.init() command. This action will allow you to take advantage of all the methods and functions that Pygame provides. Without this initialization, your code may lose cross-platform compatibility and fail to run on other operating systems. Proper initialization is a key step in developing games and multimedia applications using Pygame.
Displays and Surfaces: Drawing the Game Board
In addition to its modules, Pygame offers several hardware-independent Python classes. One key class is Surface, which represents a rectangular drawing area. In practice, this class serves as the basis for creating the game board. Surface is widely used in Pygame, and we will also make extensive use of it during the development of the Snake game.
In Pygame, all information is displayed on the game board, which is represented in the code by the display class. The game board can occupy the entire screen or just part of it. To create a display, use the .set_mode() function, which returns a Surface that represents the visible area of the window. It is this Surface that is passed to drawing functions such as pygame.draw.circle(), and its contents are displayed on the screen using pygame.display.flip(). While this may seem complicated, it is simpler in practice. Both classes will be used in the development of the Snake game.
Images and Rectangles
There are two main ways to work with images in Pygame: you can create them directly on the screen or load them from the file system. Both methods allow you to overwrite, load, and save images in various formats, such as PNG and JPG. Using images from a file simplifies the process of adding graphics to projects, while creating images from scratch gives you more control over their visual appearance. Pygame supports graphics, making it an excellent tool for developing games and multimedia applications. Images are not standalone elements. They are integrated into Surface objects, which can be modified and displayed on screens in a variety of ways. Surface objects allow you to control how images are displayed, scaled, and otherwise, making them essential for creating visually appealing content. Surface objects in Pygame are represented as rectangles, which is common to many other elements, such as images and windows. Rectangles play a key role in game development, so Pygame provides a special Rect class specifically designed for working with them. The Rect class is used for a variety of tasks, including creating shapes for characters such as players and enemies, and managing interactions between them. Using Rect objects simplifies the process of handling collisions and interactions in gameplay.
Designing and Describing Game Rules
Before starting to develop code, it's important to consider the core rules that will govern gameplay. Let's look at the basic rules for the game "Snake," which affect gameplay. These rules will help create an engaging and balanced gaming experience, providing interest and challenge for players. It's important to consider aspects such as snake control, victory and defeat conditions, and rules for interacting with the playing field and objects. These elements are key to creating a high-quality and exciting game that will keep users engaged.
- The goal of the game is to score as many points as possible by increasing the length of the snake:
- Absorbing a special object on the game screen increases the length of the snake by one block;
- The player starts from the left side of the screen;
- The player can move left, right, up or down;
- The player cannot move beyond the screen boundaries; colliding with the boundaries ends the game;
- The game ends when the snake crashes into itself;
- The game also ends when the user closes the window.
Creating a Game from Scratch
Although Snake is a simple game, the process of developing it requires writing a significant amount of code. We divided the game creation into sequential stages, each of which is responsible for the implementation of a specific element of the gameplay.
Launching Python
For writing Python code, we recommend using specialized text editors. There are various options that provide the convenience and functionality necessary for effective development. Choosing the right editor depends on your needs and preferences.
- Use specialized IDEs: IntelliJ IDEA or Visual Studio Code. We recommend this method - for example, we wrote all the code for this article in Visual Studio Code.
- Use the terminal on macOS or Linux or use the command line in Windows. To do this, you will first need to install Python on the system. We wrote about this in detail in a separate article.
After installing and running Python, you need to load the Pygame library. This library provides convenient tools for developing games and multimedia applications in Python. To install Pygame, open a command prompt and enter pip install pygame. Once the installation is complete, you can import Pygame into your project using the import pygame command. You are now ready to create full-fledged games and graphical applications using the powerful features this library provides.
Now we are completely ready to start developing the game. To continue writing code, you need to create an empty Python file with the .py extension. This file will be the basis for all the logic of your game and will help organize the structure of your project.
Creating the playing field
To create a game window using Pygame, you need to use the display.set_mode() function, specifying the desired window dimensions in pixels. It is also important to use the init() and quit() methods to correctly initialize the library at the beginning of the program and terminate it at the end. This will ensure the stable operation of your game project. Pygame provides many options for customizing and controlling gameplay, so it's important to organize your code properly around these functions.
The update() method is used to update the screen contents. There's also a flip() method, which performs a similar function. The main difference between the two is that update() only updates the changes that have been made, while flip() redraws the entire screen. However, if update() is called without parameters, it will also update the entire screen. This knowledge is useful for optimizing performance in graphics applications, allowing you to choose the most appropriate method depending on your interface updating requirements.
When this code runs, the game screen will immediately close. This happens because the code jumps to the pygame.quit() line, which disables the library and closes the game field. To prevent this, it is necessary to use a while loop, which will keep the game screen running and prevent it from closing prematurely. By implementing a while loop, you will ensure that the game runs indefinitely until the condition for its termination is met. This allows the player to interact with the game without the risk of it closing unexpectedly.
In addition, two new entities have been introduced into the code: the game title and a function for monitoring game events. To display the game title in the window, the pygame.display.set_caption(») command is used, where the title is specified in quotation marks. The event.get() function allows you to receive all game-related events in the terminal, which helps track user interaction with the gameplay. These changes improve user experience and make the game more interactive.
Let's run the code and analyze the results.

The game window no longer closes automatically. However, we also can't close it manually - when we click the "Exit" button, the window does not respond. To fix this problem, we need to make changes to the code by adding a QUIT event, which will ensure the window closes correctly.
The exit button now functions correctly. When you click it, the game window will close, providing ease of use.
Creating a snake
First, we need to initialize the variables that determine the color. These variables will be used to set the color of the screen, the snake, and the food in the game. Pygame uses a standard RGB color scheme, where each color is formed from a combination of red, green, and blue, the intensity of which can be adjusted. This allows you to create a variety of color schemes and customize the visual elements of the game for a better experience.
Our snake is shaped like a rectangle, so we use the draw.rect() function to create it. This feature allows you to set both the size and color of the rectangle, making it ideal for displaying a snake in a game. By choosing the right parameters, you can create a visually appealing and functional game element.
Run the code and analyze the result.

Project completed. A blue square, which will represent our snake, appears in the center of the screen.
Describing the snake's movements
The snake's movement is controlled using the Pygame KEYDOWN class. This class handles four main events received from the keyboard: K_UP, K_DOWN, K_LEFT, and K_RIGHT. These events correspond to the snake's movements up, down, left, and right. When any of the KEYDOWN class events is triggered, the snake's position changes. For convenience, we'll set the movement step to 10 pixels. Proper control settings improve the gameplay and make it more engaging.
To implement the snake's movement logic, we need to define two variables that will store the coordinates of the snake's first cell on the x and y axes. Let's call them x1_change and y1_change. These variables will control the snake's movement, ensuring its position in the game space is updated correctly.
The snake begins its journey across the game board, exploring new territories. Each step brings it closer to its goal, and the player must manage its route, avoiding collisions with borders and their own bodies. This is a classic game that requires strategic thinking and quick reactions. With each piece collected, the snake grows, making the game more exciting and challenging. Effective management and smart planning will help the player achieve the best results while enjoying the gameplay.

We take into account obstacles - the boundaries of the game If the snake reaches the edge of the screen, the player loses and the game ends. To implement this rule, you can use an if statement that will check the snake's x and y coordinates to determine whether they are outside the playing field. Let's look at how to add the appropriate code for this check. Now, if the snake reaches the edge of the screen, the game will end, and a loss notification will appear on the screen. This adds an element of tension and strategy, forcing players to be more mindful of their actions to avoid game over.

Adding food for
Now let's add the "food" element. For this, we'll use the random library to make food appear in random places on the game board. As the snake passes food, its length will increase. This will be implemented in the next step. We'll also give the player the option to end the game or restart it after losing.
Now, when you launch the game, in addition to the snake, food will be displayed, represented by a black square. This adds a new element to the gameplay, allowing players to collect food to extend the snake and increase the game's difficulty. The aesthetics of the game become more expressive thanks to this element.

When the game completion condition is met, a message will be displayed on the screen offering to either exit the game or start it again. This allows players to easily choose their next steps, improving the overall gaming experience. The ability to restart the game provides a chance for new achievements and allows players to explore different strategies.

Increasing the length of the snake
Let's supplement our code to increase the length The snake's movement when eating food. To do this, we'll create a list that will store the snake's current length. It's also important to keep in mind the rule: if the snake's head collides with its body, the game ends. This will add an element of complexity and realism to the game, making it more engaging for players.
We've changed the color of the game board and the snake, increasing their contrast to improve visual perception. These changes help players better navigate the game and improve overall comfort during gameplay. Improved contrast makes elements more noticeable, which contributes to a more engaging and immersive gaming experience.

Adding the display
Let's add a display of the current game's score. To do this, we'll create a Your_score function that will display the snake's length, subtracting 1 from it. This is necessary because 1 is the snake's initial size and is not considered an achievement by the player. This way, the player will be able to see their progress in the game, which will help increase interest and engagement.
We'll define a rule for calculating the snake's length by subtracting 1 from its current length. This will allow us to accurately track changes in the snake's size and ensure correct management of its length during the game.
Now the current score is displayed on the playing field. This allows players and spectators to monitor changes in the game in real time, significantly improving the overall perception of the gameplay. The current score will be updated automatically, providing accurate information on the state of the match.

Work on the "Snake" project is complete. We have successfully implemented all of the planned gameplay that was defined at the beginning of development.
Final Code
Our code is presented in full, without any comments. It is developed with best practices in mind and optimized for efficiency. We strive to ensure maximum performance and reliability, making our code an ideal solution for a variety of tasks.
What's next?
You can learn more about Pygame and its capabilities in the official library documentation. For a deeper dive into game development and exploring other projects, we recommend using specialized books that will help you master various aspects of game creation with Pygame.
- "Learn Python by Making Awesome Games" by Al Sweigart;
- "Beginning Game Development with Python and Pygame: From Novice to Professional" by Will McGoogan;
- "Program Arcade Games: With Python and Pygame" by Paul Vincent Craven.
Learn more about coding and programming in our Telegram channel. Subscribe to stay up-to-date with interesting content and updates!
Also read:
- Where to learn Python: 7 courses to master the language from scratch and get a job
- How to write a game in JavaScript
- Kubernetes overview for programmers: how it is structured, how it works, and how it relates to clouds

