[Python] Python games - Snake Adventure

1, Foreword

It's been a long time since I last updated my blog. I feel that if I don't update it again, my habit of blogging will be abolished. Ha ha. Since the beginning of school in September last year, there have been many things, such as the final examination of the semester, the application for soft books of laboratory projects, the design of new projects and the intensive training of courses, and there is not much time; Then this semester I went to the second semester of my junior year. After the handover of my laboratory work, I was ready for the postgraduate entrance examination. After that, I didn't have much time to write a blog, so I quickly updated it and shared some knowledge and experience with you. I hope my favorite partners can praise, collect and pay attention to it, ha ha.

2, Snake adventure games

1, Game introduction

1.1 game operation and rules
(1) After the game starts, control the greedy snake to move and look for food through the up, down, left and right keys on the keyboard;
(2) Greedy snakes will increase their body length by one unit for each food they eat;
(3) In normal mode, if the greedy snake touches the wall or bites itself, the game fails;
(4) In the wall piercing mode, the greedy snake can pass through the wall, but after biting itself, the game fails.

2, Overall game design

2.1 overall design framework of the game

3, Compilation language and description of library files used

3.1 Python language
Python is a cross platform computer programming language. It is an object-oriented dynamic type language. It was originally designed to write automatic scripts (shells). Python language has very concise and clear syntax characteristics. With the continuous updating of versions and the addition of new language functions, it is more and more used in the development of independent and large-scale projects. At present, the related technologies based on Python language are developing rapidly, the number of users is increasing sharply, and there are more and more related resources.
3.2 pygame Library
Pygame is a cross platform Pyth. The author of Pygame is Pete Shinners. The protocol is GNU Lesser General Public License. Pygame contains images and sounds. Based on SDL, it allows the development of real-time video games without being bound by low-level languages (such as machine language and assembly language). Based on such an assumption, all required game functions and concepts (mainly images) are completely simplified into game logic itself, and all resource structures can be provided by high-level languages, such as Python.
3.3 random library
Random is the library that generates random numbers, that is, the random number generator. Random generates pseudo-random numbers or sequence values calculated by a complex method. Therefore, a different seed value is required for each operation. Different seed values lead to different sequence values.
3.4 time library
The time library is a standard library for processing time in Python. It is used for the expression of computer time, provides the function of obtaining system time and formatting output, provides system level accurate timing function, and can also be used for program performance analysis.
3.5 sys Library
sys.exit ([arg]) is used to exit the program, sys Exit (n) exit the program. When exiting normally, exit(0). This is achieved by throwing a SystemExit exception, so the cleanup operation try specified by the clause of the finally statement is followed, and the exit attempt of the outer layer can be intercepted. The optional parameter arg can be an integer that gives the exit status (zero by default) or other types of objects. If it is an integer, zero is considered "successful termination" and any non-zero value, etc. is considered "abnormal termination".

4, Game design and Implementation

4.1 overall design of the game

  • 1. Define snake greedy objects, including snake head and snake body. The snake head is set separately, and the snake body is stored with a list;
    2. Define the food object, including the initialization of the food object, the setting of random color and random position;
    3. Define the initialization interface, in which three buttons with text of "normal mode", "wall piercing mode" and "exit" are set for players to choose;
    4. Define normal mode, including game window display, main loop and settings to judge the death of greedy snake;
    5. Define the wall piercing mode, including game window display, main loop and settings to judge the death of greedy snake;
    6. Define the game end window, including the settings of window display and final score display.

4.2 analysis of main functions

  • 4.2.1 new_food() function
    The initialization function of the food object, and the incoming formal parameter is the coordinate of the head of the greedy snake. After the greedy snake eats the food, a new food is generated through this function. Judge whether the newly generated food coordinates are the same as the snake head coordinates by passing in formal parameters. If they are the same, regenerate the new coordinates.
  • 4.2.2 start_game() function
    The main loop function of normal mode, through which the initialization of greedy snake and food, the player's control of greedy snake movement, the judgment update of snake head and snake body and score statistics are realized.
  • 4.2.3 die_snake() function
    In the normal mode, the death judgment function of the greedy snake, and the incoming formal parameters are the coordinate data of the head and body of the greedy snake. Set the boolean variable die in this function_ If there is no death, it is set to False. If there is no death, it is set to False. By traversing the snake body storage list, judge whether the snake body coordinates are the same as the snake head coordinates. If they are the same, it is determined that the greedy snake bites itself and dies. At the same time, judge whether the greedy snake hits the wall and whether the x and y coordinates of the snake head are the width and height of the window. If they exceed, they will die.
  • 4.2.4 start_kgame() function
    The main loop function of the through wall mode is used to initialize the greedy snake and food in the through wall mode, control the movement of the greedy snake by the player, judge and update the snake head and snake body, and count the scores.
  • 4.2.5 through_snake() function
    The death judgment function of greedy snake in the through wall mode, and the incoming formal parameters are the coordinate data of greedy snake head and snake body. Set the boolean variable die in this function_ Flag, if death is set to true and returned, no death is False. By traversing the snake body storage list, judge whether the snake body coordinates are the same as the snake head coordinates. If they are the same, it is determined that the greedy snake bites itself and dies.
  • 4.2.6 show_end() function
    At the end of the game, end the interface setting function. In this function, the initialization of the end interface form is performed, the final score of the game player is displayed in the form, and the pygame library quit method is called in the change function to stop the library.
  • 4.2.7 into_game() function
    Game initial interface implementation function, which initializes the game initial interface form. Set the three click buttons with the text of "normal mode", "wall piercing mode" and "exit" in the interface form, and call the button function (see 6.2.8 for details) to monitor the player's click through the setting cycle.
  • 4.2.8 button() function
    Game initial interface button monitoring function, which realizes the monitoring of player's mouse click events and keyboard input events. And according to the player's choice, run the trigger function corresponding to the button. That is, click the "normal mode" button to run the main loop function of normal mode, and so on.

5, Run module code structure

In the running module, initialize the pygame library, set the game background music, set the parameters of the display window and set the display of the initial interface of the game. The specific result code is as follows:

6, Game running test (screenshot)

  1. Game initial selection interface

  2. Normal mode operation interface

  3. Through wall mode operation interface

  4. Game end interface

    7, Game complete code

import sys
import time
import pygame
from random import *
# Position class, through its constructor, sets x and y
class Position(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
# Generate random food
def new_food(head):
    while True:
        new_food = Position(randint(0, 48) * 20, randint(0, 29) * 20)
        # Judge whether the newly generated things coincide with the greedy snake head. If they coincide, they will not create a key
        if new_food.x != head.x and new_food.y != head.y:
            break
        else:
            continue
    return new_food
# Draw, draw greedy snakes and food in the form
# Color: color, position: coordinates
def rect(color, position):
    pygame.draw.circle(window, color, (position.x, position.y), 10)
# When exiting the game due to the difference between the initial interface and the midpoint of the game
def exit_end():
    pygame.quit()
    quit()
# At the end of the game, the setting of the form displaying scores
def show_end():
    # Design window
    # Define window size
    small_window = pygame.display.set_mode((960, 600))
    init_background = pygame.image.load("image/init_bgimg.jpg")
    small_window.blit(init_background, (0, 0))
    # Define title
    pygame.display.set_caption("Snake Adventure")
    # Define background picture
    font = pygame.font.SysFont("simHei", 40)
    fontsurf = font.render('game over! Your score is: %s' % score, False, black)
    small_window.blit(fontsurf, (250, 200))
    pygame.display.update()
    time.sleep(2)
    pygame.quit()
    sys.exit()
# Normal mode death setting
# head: snake_body: snake body
def die_snake(head, snake_body):
    # Define a marker. The default value is false. When true, it is determined that the greedy snake touches itself and dies
    die_flag = False
    # Traverse the list of positions and postures of greedy snake, starting from the first one (the first 0 snake head)
    for body in snake_body[1:]:
        # If the xy of the snake's head is equal to the xy of the snake's body, the collision is determined and the flag is set to true
        if head.x == body.x and head.y == body.y:
            die_flag = True
    # If the xy of the snake head is outside the display form, or the flag is true, the end interface will be displayed and the game will exit
    if head.x < 0 or head.x > 960 or head.y < 0 or head.y > 600 or die_flag:
        pygame.mixer.music.stop()
        show_end()
# Normal mode main body setting
def start_game():
    # Global variable that defines the number of save points
    global score
    global color
    color = (randint(10, 255), randint(10, 255), randint(10, 255))
    # Define the variable to store the motion direction entered by the player's keyboard, initially to the right
    run_direction = "right"
    # The variable that defines the movement direction of the greedy snake. Initially, type the direction for the player
    run = run_direction
    # Instantiate snake head, snake body and food object
    head = Position(160, 160)
    # Initialize the snake body length to 3 units
    snake_body = [Position(head.x, head.y + 20), Position(head.x, head.y + 40), Position(head.x, head.y + 60)]
    # Initialize food location
    food = Position(300, 300)
    # Dead cycle
    while True:
        window.blit(background, (0,0))
        # Monitor the movement direction value of game player keyboard input, and change it to up, down, right or left according to input.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                show_end()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    run_direction = "up"
                elif event.key == pygame.K_RIGHT:
                    run_direction = "right"
                elif event.key == pygame.K_LEFT:
                    run_direction = "left"
                elif event.key == pygame.K_DOWN:
                    run_direction = "down"
        # food
        rect(color, food)
        # Snakehead
        rect(black, head)
        # Snake body
        for pos in snake_body:
            rect(white, pos)
        # Judge whether the original movement direction of the greedy snake and the movement direction entered by the player's keyboard violate the normal movement
        if run == "up" and not run_direction == "down":
            run = run_direction
        elif run == "down" and not run_direction == "up":
            run = run_direction
        elif run == "left" and not run_direction == "right":
            run = run_direction
        elif run == "right" and not run_direction == "left":
            run = run_direction
        # Insert snake head position into snake body list
        snake_body.insert(0, Position(head.x, head.y))
        # Update the snake head xy according to the direction entered by the player
        if run == "up":
            head.y -= 20
        elif run == "down":
            head.y += 20
        elif run == "left":
            head.x -= 20
        elif run == "right":
            head.x += 20
        # Determine whether to die
        die_snake(head, snake_body)
        # Judge the coordinates of snake head and food. If they are equal, add points and generate new food
        if head.x == food.x and head.y == food.y:
            score += 1
            food = new_food(head)
            color = (randint(10, 255), randint(10, 255), randint(10, 255))
        else:
            snake_body.pop()
        font = pygame.font.SysFont("simHei", 25)
        mode_title = font.render('Normal mode', False, grey)
        socre_title = font.render('score: %s' % score, False, grey)
        window.blit(mode_title, (50, 30))
        window.blit(socre_title, (50, 65))
        # Draw update
        pygame.display.update()
        # Set snake speed through frame rate
        clock.tick(8)
# Through wall mode setting
# head: snake_body: snake body
def through_snake(head, snake_body):
    # Define flag bit
    die_flag = False
    # Traverse. When the snake head touches the snake body, the flag is true and exits the game
    for body in snake_body[1:]:
        if head.x == body.x and head.y == body.y:
            die_flag = True
    if die_flag:
        pygame.mixer.music.stop()
        show_end()
    else:  # When the xy of the snake head comes out of the window
        # Four kinds of through wall conditions are set separately
        if head.x < 0:
            head.x = 960
        if head.x > 960:
            head.x = 0
        if head.y < 0:
            head.y = 600
        if head.y > 600:
            head.y = 0
# Through wall mode host settings
def start_kgame():
    global score
    global color
    color = (randint(10, 255), randint(10, 255), randint(10, 255))
    # Defines the initial orientation of the snake
    run_direction = "up"
    run = run_direction
    # Instantiate snake head, snake body and food object
    head = Position(160, 160)
    # Three grid
    snake_body = [Position(head.x, head.y + 20), Position(head.x, head.y + 40), Position(head.x, head.y + 60)]
    # Initialize object location
    food = Position(300, 300)
    # Dead loop, monitor keyboard key value
    while True:
        window.blit(background, (0, 0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                show_end()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    run_direction = "up"
                elif event.key == pygame.K_RIGHT:
                    run_direction = "right"
                elif event.key == pygame.K_LEFT:
                    run_direction = "left"
                elif event.key == pygame.K_DOWN:
                    run_direction = "down"
        # food
        rect(color, food)
        # Snakehead
        rect(black, head)
        # Snake body
        for pos in snake_body:
            rect(white, pos)
        # Judge whether the original movement direction of the greedy snake and the movement direction entered by the player's keyboard violate the normal movement
        if run == "up" and not run_direction == "down":  # If the movement direction is upward and the player inputs the movement direction downward, it will violate the normal movement of greedy snake
            run = run_direction
        elif run == "down" and not run_direction == "up":
            run = run_direction
        elif run == "left" and not run_direction == "right":
            run = run_direction
        elif run == "right" and not run_direction == "left":
            run = run_direction
        # Insert snake head position into snake body list
        snake_body.insert(0, Position(head.x, head.y))
        # Update the snake head xy according to the direction entered by the player
        if run == "up":
            head.y -= 20
        elif run == "down":
            head.y += 20
        elif run == "left":
            head.x -= 20
        elif run == "right":
            head.x += 20
        # Through wall implementation
        through_snake(head, snake_body)
        # Judge whether to add points and randomly generate new food
        if head.x == food.x and head.y == food.y:
            score += 1
            food = new_food(head)
            color = (randint(10, 255), randint(10, 255), randint(10, 255))
        else:
            snake_body.pop()
        font = pygame.font.SysFont("simHei", 25)
        mode_title = font.render('Through wall mode', False, grey)
        socre_title = font.render('score: %s' % score, False, grey)
        window.blit(mode_title, (50, 30))
        window.blit(socre_title, (50, 65))
        # Draw update
        pygame.display.update()
        # Set snake speed through frame rate
        clock.tick(8)
# Monitor function, monitor keyboard input
# msg: button information, X: the x-axis of the button, y: the y-axis of the button, w: the width of the button, h: the height of the button, ic: the initial color of the button, ac: the color of the button, action: the action of the button
def button(msg, x, y, w, h, ic, ac, action=None):
    # Get mouse position
    mouse = pygame.mouse.get_pos()
    # Get keyboard input
    click = pygame.mouse.get_pressed()
    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(window, ac, (x, y, w, h))
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(window, ic, (x, y, w, h))
    # Set the text style and center alignment in the button
    font = pygame.font.SysFont('simHei', 20)
    smallfont = font.render(msg, True, white)
    smallrect = smallfont.get_rect()
    smallrect.center = ((x + (w / 2)), (y + (h / 2)))
    window.blit(smallfont, smallrect)
# Game initial interface, select mode
def into_game():
    into = True
    while into:
        window.blit(init_background, (0, 0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit_end()
        # Set font
        font = pygame.font.SysFont("simHei", 50)
        # Initial interface display text
        fontsurf = font.render('Welcome to snake adventure!', True, black)  # written words
        fontrect = fontsurf.get_rect()
        fontrect.center = ((width / 2), 200)
        window.blit(fontsurf, fontrect)
        button("Normal mode", 370, 370, 200, 40, blue, brightred, start_game)
        button("Through wall mode", 370, 420, 200, 40, violte, brightred, start_kgame)
        button("sign out", 370, 470, 200, 40, red,brightred, exit_end)
        pygame.display.update()
        clock.tick(15)
if __name__ == '__main__':
    # Define canvas color
    white = (255, 255, 255)
    red = (200, 0, 0)
    green = (0, 128, 0)
    blue = (0, 202, 254)
    violte = (194, 8, 234)
    brightred = (255, 0, 0)
    brightgreen = (0, 255, 0)
    black = (0, 0, 0)
    grey = (129, 131, 129)
    score = 0
    # Design window
    # Define window size
    width = 960
    height = 600
    window = pygame.display.set_mode((width, height))
    # Define title
    pygame.display.set_caption("Snake Adventure")
    # Define background picture
    init_background = pygame.image.load("image/init_bgimg.jpg")
    background = pygame.image.load("image/bgimg.jpg")
    # background music
    pygame.mixer.init()
    pygame.mixer.music.load("background.mp3")
    pygame.mixer.music.play(-1)
    # Create clock
    clock = pygame.time.Clock()
    # initialization
    pygame.init()
    # Initial interface
    into_game()

8, Summary

This is a simple Python game, the specific code to post on the blog. Then I compressed and uploaded the relevant technical documents, background music, fonts and codes to the csdn download area.

Keywords: Python Game Development

Added by harley1387 on Fri, 04 Mar 2022 09:19:53 +0200