avatar
7 minutes read

Using Python's pygame library to implement automatic target tracking in Snake games

1、 Project background

Snake game is a classic game where players need to control a snake to move on the screen, eat food, and avoid hitting their own body or walls. Traditional Snake games typically require players to manually control the direction of snake movement, but in this article, we will introduce how to use Python's pygame library to create a Snake game that automatically tracks targets. By automatically tracking targets, the game becomes more challenging and fun.

u=3757233895,313568442&fm=253&fmt=auto&app=138&f=JPEG.webp #2、 Preparation work Before starting, make sure you have installed Python and pygame libraries. You can use the following command to install pygame through pip:

#Import the required libraries
Import pygame # Import pygame library
Import time # Import time library
Import Random # Import Random Library
#Initialize pygame
Pygame. init() # Initialize pygame
#Set screen width and height
Dis_ Width=800 # Set screen width to 800
Dis_ Height=600 # Set screen height to 600
#Creating Screen Objects
Dis=pygame.display.set_ Mode (dis_width, dis_height) # Create a screen object, set width and height
Pygame.display.set_ Caption ('Snake Game ') # Set window title to' Snake Game '
#Set game parameters
Snake_ Block=10 # Set the size of Snake blocks to 10
Snake_ Speed=30 # Set the movement speed of the greedy snake to 30
#Load custom images
Head_ Img=pygame. image. load ('ball. PNG ') # Load custom image
Head_ Img=pygame. transform. scale (head_img, (snakeublock, snakeublock)) # Adjust image size to fit snake block size
```# # 1、 Project background
Snake game is a classic game where players need to control a snake to move on the screen, eat food, and avoid hitting their own body or walls. Traditional Snake games typically require players to manually control the direction of snake movement, but in this article, we will introduce how to use Python's pygame library to create a Snake game that automatically tracks targets. By automatically tracking targets, the game becomes more challenging and fun.
#2、 Preparation work
Before starting, make sure you have installed Python and pygame libraries. You can use the following command to install pygame through pip:

#Import the required libraries Import pygame # Import pygame library Import time # Import time library Import Random # Import Random Library #Initialize pygame Pygame. init() # Initialize pygame #Set screen width and height Dis_ Width=800 # Set screen width to 800 Dis_ Height=600 # Set screen height to 600 #Creating Screen Objects Dis=pygame.display.set_ Mode (dis_width, dis_height) # Create a screen object, set width and height Pygame.display.set_ Caption ('Snake Game ') # Set window title to' Snake Game ' #Set game parameters Snake_ Block=10 # Set the size of Snake blocks to 10 Snake_ Speed=30 # Set the movement speed of the greedy snake to 30 #Load custom images Head_ Img=pygame. image. load ('ball. PNG ') # Load custom image Head_ Img=pygame. transform. scale (head_img, (snakeublock, snakeublock)) # Adjust image size to fit snake block size

Next, we will set the elements in the game, including snake blocks, food blocks, and the initial position and direction of the snake. In snake_ Continue to add the following code to the game.py file:```
#Defining the Snake Function
Def snake (snake block, snake list): # Define a snake function that takes snake block size and snake list as parameters
For x in snake_ List: # Traversing the list of greedy snakes
Pygame. raw. rect (dis, (0, 255, 0), [x [0], x [1], snake_ Block, snake_ Draw Snake Blocks on the Screen
#Define game loop
Def gameLoop (x1=1, y1=1): # Define game loop function
Game_ Over=False # Initialize the game end flag to False
Game_ Close=False # Initialize game close flag to False
#Initialize Snake Position
X1=dis_ Width/2 # Initialize the x-coordinate of the greedy snake's head to half the screen width
Y1=dis_ Height/2 # Initialize the y-coordinate of the greedy snake's head to half the screen height
X1_ Change=0 # Initialize the greedy snake's x-direction change to 0
Y1_ Change=0 # Initialize the y-direction change of the greedy snake to 0
Snake_ List=[] # Initialize the greedy snake list to be empty
Length_ Of_ Snake=1 # Initialize the length of the greedy snake to 1
#Randomly generate food positions
Foodx=round (random. randrange (0, dis_width - snakeublock)/10.0) * 10.0 # Randomly generate food x-coordinates
Food=round (random. randrange (0, dis_height - snakeublock)/10.0) * 10.0 # Randomly generate food y coordinates
While not game_ Over: # Loop before the game ends
#Automatic tracking of food
If x1<foodx: # If the x-coordinate of the greedy snake's head is smaller than the x-coordinate of the food
X1_ Change=snake_ Block # Set the x-direction change to the size of the Snake block
Y1_ Change=0 # Set the y-direction change to 0
```# 5、 Game loop and button settings:
Next, we need to implement the main loop of the game, including rendering the game interface, processing events, updating game status, and calling automatic tracking functions and their button settings. Continue to add the following code to the file:```
#After the score is reached, pause the game and display the button as follows:
If Length_ Of_ Snake -1>=88: # If the score reaches 88
#Display clearance prompts
Font=pygame. font. Font (None, 50) # Set font and size
Text=font. render ("success!!!", True, (255, 255, 255)) # Renders clearance prompt text
Dis. blit (text, (dis_width//2-200, dis_height//2-50)) # Draw clearance prompt text to the middle of the screen
#Draw reopen and pause buttons
Continue_ Button=pygame. raw. rect (dis, (0, 255, 0),
(dis_width//2-100, dis_height//2+50, 100, 50)) # Draw the reopen button
Pause_ Button=pygame. raw. rect (dis, (255, 0, 0), (dis_width//2, dis_height//2+50, 100, 50)) # Draw pause button
#Draw button text
Font=pygame. font. Font (None, 30) # Set font and size
Text=font. render ("Reopen", True, (255, 255, 255)) # Renders the text of the reopen button
Dis. blit (text, (dis_width//2-80, dis_height//2+65)) # Draw the text of the reopen button to the middle of the screen
Text=font. render ("stop", True, (255, 255, 255)) # rendering pause button text
Dis. blit (text, (dis)_
```# 6、 Game End and Exit
Pygame. display. update() # Update screen display
#Update food location
If x1==foodx and y1==food: # If the coordinates of the greedy snake's head are equal to the food coordinates
Foodx=round (random. randrange (0, dis_width - snakeublock)/10.0) * 10.0 # Randomly generate new food x-coordinates
Food=round (random. randrange (0, dis_height - snakeublock)/10.0) * 10.0 # Generate new food y coordinates randomly
Length_ Of_ Snake+=1 # Increase the length of the greedy snake by 1
Time. sleep (snake_speed/100000.0) # Control game speed
Pygame. quit() # Exit pygame
Quit() # Exit the game
GameLoop()

0 Comment