Last Updated on September 17, 2023 by GeeksGod
Course : Create snake with Python PyGame
Free Udemy Coupon: Python PyGame Snake Game
In this article, we will discuss how to create a 2D snake game using Python and the Pygame module. Pygame is a powerful game development library that provides low-level access to audio, keyboard, mouse, joystick, graphics, and even high-level modules for video playback.
Introduction to Snake Game
The snake game is one of the most classic and influential arcade games in the universe of video games. Since its inception, it has been played by countless players. It was originally found on arcade machines but is now available even on phones.
With the help of Pygame, we can recreate this iconic game and have a better understanding of game development. Pygame is a set of Python bindings for the SDL multimedia library. It is compatible with various operating systems and hardware platforms, including Linux with Raspberry Pi, Microsoft Windows, Apple Mac OS X, BeOS, FreeBSD, OpenBSD, Sharp Zaurus, iPAQ, HTC Dream phone, and even Android.
Python and Pygame Requirements
Before diving into building the snake game, it is important to have some foundational knowledge of Python programming. Basic knowledge of object-oriented programming concepts such as classes and objects will also be useful. Additionally, we will be using the “random” module to generate random numbers for our game.
Upon completing this course, you will not only have a functional snake game, but also the skills to create your own 2D games. The course includes all the necessary source code for you to follow along and learn at your own pace.
Section 1: Setting up the Game Environment
Before we start coding, we need to set up the game environment. This involves installing Python and Pygame on your computer. Rest assured, we will guide you through the process step-by-step.
Step 1: Install Python
To begin, you need to install Python on your machine. Python is a popular programming language known for its simplicity and readability. Visit the official Python website to download and install the latest version. Make sure you select the appropriate version for your operating system.
Step 2: Install Pygame
Next, you will need to install Pygame. Open your command prompt or terminal and enter the following command:
pip install pygame
This command will install the latest version of Pygame from the Python Package Index (PyPI).
Section 2: Building the Snake Game
Now that we have our game environment set up, it’s time to start building the snake game. We will break this down into several steps to make it easier to follow along.
Step 1: Importing the Required Modules
In order to use Pygame and its functionalities, we need to import the necessary modules. Open your favorite Python IDE or text editor and create a new Python file. Begin by importing the following modules:
import pygame import random
These modules will allow us to create the game window, handle user input, and generate random numbers.
Step 2: Initializing the Game
Next, we need to initialize Pygame and create a game window. Add the following code:
pygame.init() width, height = 640, 480 screen = pygame.display.set_mode((width, height))
This code initializes all the Pygame modules, including the ones responsible for graphics, sound, and input handling. It also sets the dimensions of the game window to 640 pixels wide and 480 pixels high.
Step 3: Creating the Snake
Now, let’s create the snake. Add the following code:
snake_size = 10 snake_speed = 15 snake_x = random.randint(0, width - snake_size) snake_y = random.randint(0, height - snake_size)
In these few lines of code, we define the size and speed of the snake. We also generate random starting coordinates for the snake’s initial position.
Step 4: Handling User Input
To make the snake move, we need to handle user input. Add the following code:
direction = "RIGHT" clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: direction = "UP" elif event.key == pygame.K_DOWN: direction = "DOWN" elif event.key == pygame.K_LEFT: direction = "LEFT" elif event.key == pygame.K_RIGHT: direction = "RIGHT" pygame.display.update() clock.tick(snake_speed)
This code constantly checks for user input and updates the snake’s direction accordingly. We also update the game window and set the game’s frame rate using the clock object.
Step 5: Moving the Snake
With user input handled, we can now move the snake. Add the following code:
if direction == "UP": snake_y -= snake_size elif direction == "DOWN": snake_y += snake_size elif direction == "LEFT": snake_x -= snake_size elif direction == "RIGHT": snake_x += snake_size
These few lines of code move the snake’s head according to the current direction. The snake’s body will follow as we add more code later.
Step 6: Drawing the Snake
Finally, let’s draw the snake on the game window. Add the following code:
screen.fill((0, 0, 0)) pygame.draw.rect(screen, (255, 255, 255), (snake_x, snake_y, snake_size, snake_size))
This code fills the game window with a black color and then draws a white rectangle representing the snake’s head based on its current position and size.
Section 3: Enhancing the Game
Now that we have the basic functionality of the snake game, we can enhance it with additional features. Let’s add some food for the snake to eat and make it grow.
Step 1: Adding Food for the Snake
In order to make the game more challenging, we need to add some food for the snake to eat. Add the following code:
food_size = 10 food_x = random.randint(0, width - food_size) food_y = random.randint(0, height - food_size)
These few lines of code define the size and random coordinates for the food. We generate the coordinates within the game window bounds.
Step 2: Drawing the Food
Next, let’s draw the food on the game window. Add the following code:
pygame.draw.rect(screen, (255, 0, 0), (food_x, food_y, food_size, food_size))
This code draws a red rectangle representing the food on the window based on its position and size. With this, the snake can now detect when it collides with the food.
Step 3: Snake-Food Collision
Now, let’s handle the collision between the snake and the food. Add the following code:
if snake_x == food_x and snake_y == food_y: food_x = random.randint(0, width - food_size) food_y = random.randint(0, height - food_size) # Increase the length of the snake # ...
This code checks if the snake’s head collides with the food. If a collision occurs, we generate new random coordinates for the food and increase the snake’s length. We will implement the snake’s length in the next step.
Step 4: Snake’s Body Length
Finally, let’s implement the length of the snake’s body. Add the following code:
snake_list =  snake_length = 1 snake_head =  snake_head.append(snake_x) snake_head.append(snake_y) snake_list.append(snake_head) if len(snake_list) > snake_length: del snake_list for x in snake_list: pygame.draw.rect(screen, (0, 255, 0), (x, x, snake_size, snake_size))
These lines of code define a list to store the coordinates of every segment of the snake’s body. The length of the snake is represented by the “snake_length” variable. The code then draws rectangles for each segment of the snake’s body using the stored coordinates.
Section 4: Conclusion
Congratulations! You have successfully created a snake game using Python and Pygame. By following the steps outlined in this article, you have gained valuable insights into game development and Python programming.
Remember to practice and experiment with the code to further enhance and customize your snake game. Learning game development is an ongoing process, and the possibilities are endless.
Free Udemy Coupon: Python PyGame Snake Game
If you are interested in learning more about Python game development, we highly recommend checking out our Udemy course on “Python PyGame Snake Game.” This course provides in-depth tutorials, coding exercises, and projects to help you master Python game development with Pygame.
Take advantage of our free Udemy coupon to enroll in this course and start your journey into the world of Python game development today!
Once again, congratulations on your achievement and happy coding!