Use Python to develop a small dinosaur jumping game and play it

I believe that many people have played the dinosaur running game provided on the chrome browser. You can enter the game when we disconnect from the Internet or directly enter the address "chrome://dino/" in the browser.

Today we are using Python to make a similar little game

material preparation

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

game logic

We use Pygame to make the game, first initialize the game page

import pygame

# initialization
pygame.init()
pygame.mixer.init()
# set window size
screen = pygame.display.set_mode((900200))
# set title
pygame.display.set_caption("Dinosaur jump")
# Use system fonts
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(17):
    temp = pygame.image.load(f"dino/dino_run{i}.png")
    dino_list.append(temp)
dino_rect = temp.get_rect()
index = 0

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

# set up y The initial velocity on the axis is 0
y_speed = 0
# initial jump speed
jumpSpeed = -20
# Simulate gravity
gravity = 2

 load 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 all over again
is_restart = False
text_color = (0,0,0)

Next, we keep the game progress 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()
        # space bar detection
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and dino_rect.y==150:
                y_speed = jumpSpeed

Mainly detect exit events and space bar events

Impact checking

# Impact checking
    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()
                # space bar 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 collision, as long as the dinosaur collided with the cactus, the game is over, and the picture is displayed again.

Since we want the game to record our best scores, we use a local file to store game records. When the game ends, we will judge whether to write new scores into the file according to the current game scores.

Below is the code to calculate distance run and best time

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

    # Calculate best grade
    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 increase the difficulty of the game for different distances. After all, the farther the distance is, the greater the difficulty.

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

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

    #set background color
    screen.fill(bg_color)

Finally we render all elements loaded into memory on the screen

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

    pygame.display.update()

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

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

In this way, an easy-to-use dinosaur running game is completed. Let's take a look at the effect.

Well, today's sharing is here, if you like it, give it a like

For those who need the complete code, click "Watching" below, and wechat private chat to get it!

This article is by mdnice Multi-platform release

Tags: Python

Posted by p_h_p on Sun, 25 Sep 2022 02:07:51 +0930