This article is participating in Python Theme Month. See the link to the event for more details

Snake is one of the most popular arcade games of all time. In this game, the player’s main goal is to catch the maximum amount of fruit without bumping into or hitting the wall. When learning Python or Pygame, think of creating a snake game as a challenge. This is one of the best beginner-friendly projects that every new programmer should embrace. Learning to build video games is fun and fun to learn.

We will use Pygame to create the snake game. Pygame is an open source library designed specifically for making video games. It has built-in graphics and sound libraries. It’s also beginner friendly and cross-platform.

๐Ÿ›ฌ installation

To install Pygame, you need to open a terminal or command prompt and type the following command:

pip install pygame
Copy the code

With Pygame installed, we’re ready to create our cool snake game.

๐Ÿ›ฐ Step-by-step approach to creating a snake game with Pygame:

๐Ÿ’Œ Step 1: First, we are importing the necessary libraries.

  • After that, we define the width and height of the window in which the game will run.
  • And define the color in RGB format that we will use to display text in the game.
# import libraries
import pygame
import time
import random

snake_speed = 15

# Window size
window_x = 720
window_y = 480

# Define color
black = pygame.Color(0.0.0)
white = pygame.Color(255.255.255)
red = pygame.Color(255.0.0)
green = pygame.Color(0.255.0)
blue = pygame.Color(0.0.255)
Copy the code

๐Ÿ“ Step 2: After importing the library, we need to use itpygame.init()Method to initialize Pygame.

  • Create a game window using the width and height defined in the previous step.
  • Here Pygame.time.clock () is further used to change the speed of the snake in the main logic of the game.
# Initialize PyGame
pygame.init()

Initialize the game window
pygame.display.set_caption('GeeksforGeeks Snakes')
game_window = pygame.display.set_mode((window_x, window_y))

# FPS controller
fps = pygame.time.Clock()
Copy the code

๐ŸŽฏ Step 3: Initialize the position and size of the snake.

  • After the snake position is initialized, the fruit position is randomly initialized at any position of the defined height and width.
  • By setting the direction to RIGHT, we ensured that whenever the user runs the program/game, the snake must move to the RIGHT onto the screen.
# Define the default location of the snake
snake_position = [100.50]

# Define the first 4 blocks of the snake body
snake_body = [ [100.50],
				[90.50],
				[80.50],
				[70.50]]# Fruit location
fruit_position = [random.randrange(1, (window_x//10)) * 10,
				random.randrange(1, (window_y//10)) * 10]
fruit_spawn = True

Set the default snake direction to the right
direction = 'RIGHT'
change_to = direction
Copy the code

๐Ÿฅ‡ Step 4: Create a function to display the player’s score.

  • In this function, we first create a font object, where the font color will appear.
  • We then used the render to create a background surface that we would change every time our score was updated.
  • Create a rectangle object for the text surface object (the text will be refreshed here)
  • Then, we use blit to display our score. Screen.blit (background,(x,y))
# Initial score
score = 0

# Display scoring function
def show_score(choice, color, font, size) :
	
	# Create a font object score_font
	score_font = pygame.font.SysFont(font, size)
	
	Core_surface creates a display surface object
	score_surface = score_font.render('Score : ' + str(score), True, color)
	
	Create a rectangle object for the text surface object
	score_rect = score_surface.get_rect()
	
	# Display text
	game_window.blit(score_surface, score_rect)
Copy the code

๐ŸŽด Step 5: Now create a game over function that will represent the score of a snake hit by a wall or itself.

  • In the first line, we create a font object to display the score.
  • Then we create the text surface to render the score.
  • After that, we set the position of the text in the middle of the playable area.
  • Display the score using blit and update the score by updating the surface using Flip ().
  • We use sleep(2) to wait 2 seconds before closing the window with quit().
# Game over feature
def game_over() :
	
	# Create font object my_font
	my_font = pygame.font.SysFont('times new roman'.50)
	
	# Create the text surface on which text will be drawn
	game_over_surface = my_font.render('Your Score is : ' + str(score), True, red)
	
	Create a rectangle object for the text surface object
	game_over_rect = game_over_surface.get_rect()
	
	# Set text position
	game_over_rect.midtop = (window_x/2, window_y/4)
	
	# blit will draw text on the screen
	game_window.blit(game_over_surface, game_over_rect)
	pygame.display.flip()
	
	We will exit the program after 2 seconds
	time.sleep(2)
	
	# Deactivate pyGame library
	pygame.quit()
	
	# Exit program
	quit()
Copy the code

โฐ Step 6: Now we will create our main function, which will do the following:

  • We will verify the key responsible for the snake’s movement, and then we will create a special condition that does not allow the snake to immediately move in the opposite direction.
  • After that, if the snake and the fruit collide, we will increase the score by 10 and the new fruit will be crossed.
  • After that, we’re checking to see if the snake was hit by the wall. If a snake crashes into a wall, we call the game over function.
  • If the snake bumps itself, the game over function is called.
  • Finally, we will display the score using the show_score function created earlier.
# Main Function
while True:
	
	# Handle critical events
	for event in pygame.event.get():
		if event.type == pygame.KEYDOWN:
			if event.key == pygame.K_UP:
				change_to = 'UP'
			if event.key == pygame.K_DOWN:
				change_to = 'DOWN'
			if event.key == pygame.K_LEFT:
				change_to = 'LEFT'
			if event.key == pygame.K_RIGHT:
				change_to = 'RIGHT'

	If both keys are pressed at the same time
        # We don't want the snake to move in two directions at once
	if change_to == 'UP' anddirection ! ='DOWN':
		direction = 'UP'
	if change_to == 'DOWN' anddirection ! ='UP':
		direction = 'DOWN'
	if change_to == 'LEFT' anddirection ! ='RIGHT':
		direction = 'LEFT'
	if change_to == 'RIGHT' anddirection ! ='LEFT':
		direction = 'RIGHT'

	# moving snake
	if direction == 'UP':
		snake_position[1] - =10
	if direction == 'DOWN':
		snake_position[1] + =10
	if direction == 'LEFT':
		snake_position[0] - =10
	if direction == 'RIGHT':
		snake_position[0] + =10

	# Snake body growth mechanism
        If the fruit and snake collide, then the score is increased by 10
	snake_body.insert(0.list(snake_position))
	if snake_position[0] == fruit_position[0] and snake_position[1] == fruit_position[1]:
		score += 10
		fruit_spawn = False
	else:
		snake_body.pop()
		
	if not fruit_spawn:
		fruit_position = [random.randrange(1, (window_x//10)) * 10,
						random.randrange(1, (window_y//10)) * 10]
		
	fruit_spawn = True
	game_window.fill(black)
	
	for pos in snake_body:
		pygame.draw.rect(game_window, green, pygame.Rect(
		pos[0], pos[1].10.10))
		
	pygame.draw.rect(game_window, white, pygame.Rect(
	fruit_position[0], fruit_position[1].10.10))

	# End of game condition
	if snake_position[0] < 0 or snake_position[0] > window_x-10:
		game_over()
	if snake_position[1] < 0 or snake_position[1] > window_y-10:
		game_over()
	
	# Touch the snake
	for block in snake_body[1] :if snake_position[0] == block[0] and snake_position[1] == block[1]:
			game_over()
	
	# Continuously display scores
	show_score(1, white, 'times new roman'.20)
	
	# Refresh the game screen
	pygame.display.update()

	# Frames per second/refresh rate
	fps.tick(snake_speed)
Copy the code

Here’s the implementation

Quick summary — Python snake game

In fact, the source code has been listed, but certainly there are friends want to directly take the complete, need to be able to leave a message in the comment area, has not been put on GitHub, directly put in the article and feel the code is too long

This is a series of articles that will continue to update Python, Java, HTML, and more. I hope this tutorial series has been helpful to you, and the bloggers are still learning, and I hope to correct anything that went wrong. If you enjoyed this article and are interested in seeing more of it, you can check it out here (Github/Gitee). This is a summary of all my original works and source code. Follow me for more information.

More on this at ๐Ÿงต

  • Python exception handling | Python theme month
  • Python Multithreading tutorial | Python theme month
  • Python Socket programming essentials | Python theme month
  • 30 Python tutorials and tips | Python theme month
  • Python statements, expressions, and indentation | Python theme month
  • Python keywords, identifiers, and variables | Python theme month
  • How to write comments and multi-line comments in Python | Python Theme Month
  • Learn about Python numbers and type conversions with examples | Python theme month
  • Python data types — Basic to advanced learning | Python topic month
  • Object-oriented programming in Python – classes, Objects and Members | Python theme month

๐Ÿฐ Past excellent articles recommended:

  • 20 Python Tips Everyone must Know | Python Theme month
  • 100 Basic Python Interview Questions Part 1 (1-20) | Python topic month
  • 100 Basic Python Interview Questions Part 2 (21-40) | Python topic month
  • 100 Basic Python Interview Questions Part 3 (41-60) | Python topic month
  • 100 Basic Python Interview Questions Part 4 (61-80) | Python topic month
  • 100 Basic Python Interview Questions Part 5 (81-100) | Python topic month

If you do learn something new from this post, like it, bookmark it and share it with your friends. ๐Ÿค— Finally, don’t forget โค or ๐Ÿ“‘ for support