We've already learned how to create a window using pygame. Now let's learn how to use pyGame to make a classic little game, Snake Eating.
- First we need to import the modules to be used:
import pygame, sys, random from pygame.locals import *
The pygame.locals module contains various constants used by pygame, and its contents are automatically put into the namespace of the Pygame module.
- After the module is imported, we can define the color we will use, according to your preferences.
# define color pinkColor = pygame.Color(255, 182, 193) blackColor = pygame.Color(0, 0, 0) whiteColor = pygame.Color(255, 255, 255)
pygame.Color() is an object used to describe color.
Color(name) -> Color Color(r, g, b , a) -> Color Color(rgbvalue) –>Color # Method & Attribute of Color Object pygame.Color.r : Get or set Color The red value of the object pygame.Color.g : Get or set Color Green value of object pygame.Color.b : Get or set Color Blue value of object pygame.Color.a : Get or set Color Object alpha value pygame.Color.cmy : Get or set Color Object cmy value pygame.Color.hsva : Get or set Color Object hsav value pygame.Color.hsla : Get or set Color Object hsla value pygame.Color.i 1i2i3 : Get or set Color Object I1I2I3 describe pygame.Color.normalize : Return a Color Object RGBA(Display Channel) Value pygame.Color.correct gamma : Color Object requests a determination gamma value pygame.Color.set length : Setting Color The number of elements in an object is 1, 2, 3, or 4
- When the game is over, we need to exit the game, so we need to define a function for the game to exit. Simply, we need to exit the pygame window first, and then exit the program:
# Define the end-of-game function def gameover(): # Exit pygame window pygame.quit() # Exit Procedure sys.exit()
- After defining the end function, we need to define an entry function for entering the game, where the main code of the game is written:
def main(): # Initialization pygame.init() # Define a variable to control speed time_clock = pygame.time.Clock() # Create windows and define titles screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Retro Snaker")
First, we need to initialize pygame, create a good game window, and by the way define a variable to control speed, which is used for the movement of snakes.
- Then initialize some variables for snakes and food, and treat the entire interface as many 20x20 squares, each representing a unit.
# Defining the Initialization Variables of Snakes snakePosition = [100, 100] # Snake head position # Define a list of snake-eating lengths, with several elements representing several segments of the body. Here we define five segments of the body. snakeSegments = [[100, 100], [80, 100], [60, 100], [40, 100], [20, 100]] # Initialize food location foodPostion = [300, 300] # Number of food, 0 means eaten, 1 means not eaten foodTotal = 1 # Initial direction, right direction = 'right' # Define a variable that changes direction. Keyboard changeDirection = direction
- After initializing the data, use the while loop to listen for events and keep the snake moving forward through the loop.
while True: # Getting events from queues for event in pygame.event.get(): # Determine whether it is an exit event if event.type == QUIT: pygame.quit() sys.exit() # Key event elif event.type == KEYDOWN: # If it's the right-click head or d, the snake moves to the right. if event.key == K_RIGHT or event.key == K_d: changeDirection = 'right' # If it's left key or a, the snake moves to the left. if event.key == K_LEFT or event.key == K_a: changeDirection = 'left' if event.key == K_UP or event.key == K_w: changeDirection = 'up' if event.key == K_DOWN or event.key == K_s: changeDirection = 'down' # The Esc key on the keyboard indicates exit. if event.key == K_ESCAPE: pygame.event.post(pygame.event.Event(QUIT))
KEYDOWN is a keyboard key event, while K_RIGHT, K_LEFT, K_d, K_a and so on represent keys on the corresponding keyboard.
- To confirm the direction of the snake's movement, it can't move in the opposite direction. For example, when the snake moves to the right, it can't control it to move to the left, only up or down.
# Identify the direction and determine whether the reverse motion has been entered if changeDirection == 'right' and not direction == 'left': direction = changeDirection if changeDirection == 'left' and not direction == 'right': direction = changeDirection if changeDirection == 'up' and not direction == 'down': direction = changeDirection if changeDirection == 'down' and not direction == 'up': direction = changeDirection
- Determining snake head movement by adding or subtracting pixels up or down by 20 PX is equivalent to moving up or down by one step.
# Move snake head in direction if direction == 'right': snakePosition[0] += 20 if direction == 'left': snakePosition[0] -= 20 if direction == 'up': snakePosition[1] -= 20 if direction == 'down': snakePosition[1] += 20 # Increase the length of snakes snakeSegments.insert(0, list(snakePosition)) # Judge whether food is eaten or not if snakePosition[0] == foodPostion[0] and snakePosition[1] == foodPostion[1]: foodTotal = 0 else: snakeSegments.pop() # Remove the last unit of snake body from the list at a time # If the food is zero, the food is regenerated. if foodTotal == 0: x = random.randrange(1, 32) y = random.randrange(1, 24) foodPostion = [int(x * 20), int(y * 20)] foodTotal = 1 # Drawing pygame display layer screen.fill(blackColor)
- Set the colour lengths and widths of snakes and food
for position in snakeSegments: # Snake body is white # Chemical snake pygame.draw.rect(screen, pinkColor, Rect(position[0], position[1], 20, 20)) pygame.draw.rect(screen, whiteColor, Rect(foodPostion[0], foodPostion[1], 20, 20))
- Updates are displayed on the screen surface
pygame.display.flip()
- Judging whether the game is over
# Judging whether the game is over if snakePosition[0] > 620 or snakePosition[0] < 0: gameover() elif snakePosition[1] > 460 or snakePosition[1] < 0: gameover() # If you touch your body for body in snakeSegments[1:]: if snakePosition[0] == body[0] and snakePosition[1] == body[1]: gameover() # Control the speed of the game time_clock.tick(5)
- Entry function
if __name__ == '__main__': main()
Then you can run the code, as shown below
Complete code
import pygame, sys, random from pygame.locals import * # define color pinkColor = pygame.Color(255, 182, 193) blackColor = pygame.Color(0, 0, 0) whiteColor = pygame.Color(255, 255, 255) # Define the end-of-game function def gameover(): pygame.quit() sys.exit() def main(): # Initialization pygame.init() # Define a variable to control speed time_clock = pygame.time.Clock() # Create windows and define titles screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Retro Snaker") # Defining the Initialization Variables of Snakes snakePosition = [100, 100] # Snake head position # Define a list of snake-eating lengths, with several elements representing several segments of the body snakeSegments = [[100, 100], [80, 100], [60, 100], [40, 100], [20, 100]] # Initialize food location foodPostion = [300, 300] # Number of food, 1 is not eaten, 0 is eaten. foodTotal = 1 # Initial direction, right direction = 'right' # Define a variable that changes direction. Keyboard changeDirection = direction # Control snake movement by keyboard while True: # Getting events from queues for event in pygame.event.get(): # Determine whether it is an exit event if event.type == QUIT: pygame.quit() sys.exit() # Key event elif event.type == KEYDOWN: # If it's the right-click head or d, the snake moves to the right. if event.key == K_RIGHT or event.key == K_d: changeDirection = 'right' # If it's left key or a, the snake moves to the left. if event.key == K_LEFT or event.key == K_a: changeDirection = 'left' if event.key == K_UP or event.key == K_w: changeDirection = 'up' if event.key == K_DOWN or event.key == K_s: changeDirection = 'down' # The Esc key on the keyboard indicates exit. if event.key == K_ESCAPE: pygame.event.post(pygame.event.Event(QUIT)) # Identify the direction and determine whether the reverse motion has been entered if changeDirection == 'right' and not direction == 'left': direction = changeDirection if changeDirection == 'left' and not direction == 'right': direction = changeDirection if changeDirection == 'up' and not direction == 'down': direction = changeDirection if changeDirection == 'down' and not direction == 'up': direction = changeDirection # Move snake head in direction if direction == 'right': snakePosition[0] += 20 if direction == 'left': snakePosition[0] -= 20 if direction == 'up': snakePosition[1] -= 20 if direction == 'down': snakePosition[1] += 20 # Increase the length of snakes snakeSegments.insert(0, list(snakePosition)) # Judge whether food is eaten or not if snakePosition[0] == foodPostion[0] and snakePosition[1] == foodPostion[1]: foodTotal = 0 else: snakeSegments.pop() # Remove the last unit of snake body from the list at a time # If the food is zero, the food is regenerated. if foodTotal == 0: x = random.randrange(1, 32) y = random.randrange(1, 24) foodPostion = [int(x * 20), int(y * 20)] foodTotal = 1 # Drawing pygame display layer screen.fill(blackColor) for position in snakeSegments: # Snake body is white # Chemical snake pygame.draw.rect(screen, pinkColor, Rect(position[0], position[1], 20, 20)) pygame.draw.rect(screen, whiteColor, Rect(foodPostion[0], foodPostion[1], 20, 20)) # Updates are displayed on the screen surface pygame.display.flip() # Judging whether the game is over if snakePosition[0] > 620 or snakePosition[0] < 0: gameover() elif snakePosition[1] > 460 or snakePosition[1] < 0: gameover() # If you touch your body for body in snakeSegments[1:]: if snakePosition[0] == body[0] and snakePosition[1] == body[1]: gameover() # Control the speed of the game time_clock.tick(5) # Start the entry function if __name__ == '__main__': main()