Use Python to develop a dinosaur running game to play

I believe many people have played the dinosaur run game provided by Chrome browser. When we disconnect the Internet or directly enter the address in the browser“ chrome://dino/ ”Can enter the game

Today we use Python to make a similar game

Material preparation

First, we prepare the materials needed for the game, such as dinosaur pictures, cactus pictures, sky, ground, etc. we put them in the dino folder

Game logic

We use Pygame to make games. First initialize the game page

import pygame

# initialization
pygame.init()
pygame.mixer.init()
# Set window size
screen = pygame.display.set_mode((900, 200))
# Set title
pygame.display.set_caption("Dinosaur jump")
# Use the system's own font
my_font = pygame.font.SysFont("arial", 20)
score = 0
# Background color
bg_color = (218,220,225)

Next, we load various materials into memory

# Load normal dinosaur
dino_list = []
temp = ""
for i in range(1, 7):
    temp = pygame.image.load(f"dino/dino_run{i}.png")
    dino_list.append(temp)
dino_rect = temp.get_rect()
index = 0

# Initial value of x
dino_rect.x = 100
# Initial value of y
dino_rect.y = 150
# print(dino_rect)

# Set the initial velocity on the y-axis to 0
y_speed = 0
# Initial take-off speed
jumpSpeed = -20
# Simulated gravity
gravity = 2

 Loading ground
ground = pygame.image.load("dino/ground.png")

# Load cactus
cactus = pygame.image.load("dino/cactus1.png")
cactus_rect = cactus.get_rect()
cactus_rect.x,cactus_rect.y = 900,140

# Load again
restart = pygame.image.load("dino/restart.png")
restart_rect = restart.get_rect()
restart_rect.x,restart_rect.y = (900-restart.get_rect().width)/2,(200-restart.get_rect().height)/2+50
# Load gameover
gameover = pygame.image.load("dino/gameover.png")
gameover_rect = gameover.get_rect()
gameover_rect.x, gameover_rect.y = (
    900-gameover.get_rect().width)/2, (200-gameover.get_rect().height)/2
# Ground movement speed and distance
ground_speed = 10
ground_move_distance = 0

# Clock
clock = pygame.time.Clock()

# Do it again
is_restart = False
text_color = (0,0,0)

Next, we maintain the game process through a while loop

while True:
    # 30 times per second
    clock.tick(30)
    ...

In the above loop, we need two detection mechanisms, event detection and collision detection

event detection

# event detection 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            if result_flag:
                with open("result.ini", "w+") as f:
                    f.write(str(best))
            sys.exit()
        # Spacebar detection
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and dino_rect.y==150:
                y_speed = jumpSpeed

It mainly detects exit events and spacebar events

collision detection

# collision detection 
    if dino_rect.colliderect(cactus_rect):
        while not is_restart:
            # event detection 
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    if result_flag:
                        with open("result.ini", "w+") as f:
                            f.write(str(best))
                    sys.exit()
                # Spacebar detection
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        is_restart = True
                        bg_color = (218,220,225)
                        ground_speed = 10
            # Set the picture again
            screen.blit(restart, restart_rect)
            screen.blit(gameover, gameover_rect)
            pygame.display.update()

For the collision, as long as the dinosaur collides with the cactus, the game ends and the picture is displayed again

Because we want the game to record our best results, we use the local file to store the game records. When the game is over, we judge whether to write the new results into the file according to the current game results

Here is the code to calculate the running distance and the best result

 # Statistical distance
    score += ground_speed
    score_surface = my_font.render("Distance: "+str(score), True, text_color)

    # Calculate the best score
    result_flag = False
    if score >= best:
        best = score
        result_flag = True
    best_result = my_font.render("Best Result: " + str(best), True, text_color)

We also need to add different game difficulties to different distances. After all, the farther we run, the more difficult it is

# Change the background color, and the score is greater than 4000
    if score > 4000:
        bg_color = (55,55,55)
        ground_speed = 15
        text_color = (255,255, 255)
# Change the background color, and the score is greater than 8000
    if score > 8000:
        bg_color = (220,20,60)
        ground_speed = 20
        text_color = (255, 255, 255)

    # Change the background color, and the score is greater than 12000
    if score > 12000:
        bg_color = (25,25,112)
        ground_speed = 25
        text_color = (255, 255, 255)

    # Set background color
    screen.fill(bg_color)

Finally, we render all the elements loaded into memory on the screen

# Set ground picture 1
    screen.blit(ground, (0-ground_move_distance, 180))
    # Set ground picture 2, outside the right boundary
    screen.blit(ground, (900-ground_move_distance, 180))
    # Set dinosaur pictures
    screen.blit(dino_list[index % 6], dino_rect)
    # Set cactus picture
    screen.blit(cactus, cactus_rect)
    # Set score
    screen.blit(score_surface,(780,20))
    # Set best score
    screen.blit(best_result, (20, 20))

    pygame.display.update()

In order to increase the game, we add background music and jumping sound

pygame.mixer.music.load("background.mp3")
pygame.mixer.music.play(-1, 0)
sound = pygame.mixer.Sound('preview.mp3')

In this way, a simple and easy-to-use dinosaur running game is completed. Let's see the effect

end of document

Your favorite collection is my greatest encouragement!
Welcome to follow me, share Python dry goods and exchange Python technology.
If you have any opinions on the article or any technical problems, please leave a message in the comment area for discussion!

Keywords: Python

Added by love_php on Tue, 14 Dec 2021 04:54:40 +0200