current position:Home>Use Python to develop a dinosaur running game and play it

Use Python to develop a dinosaur running game and play it

2022-02-02 06:49:05 yz_ weixiao

 picture .png

I believe many people have played chrome Dinosaur running game provided on the browser , When we disconnect or enter the address directly in the browser “chrome://dino/” Can enter the game

 picture .png

Today we just use Python Make a similar game

Material preparation

First, we prepare the materials needed for the game , Like dinosaur pictures , Cactus pictures , sky , Ground, etc , We put it together dino Under the folder

 picture .png

The 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 Fonts 
my_font = pygame.font.SysFont("arial", 20)
score = 0
#  Background color 
bg_color = (218,220,225)
 Copy code 

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

# 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
#  Take off speed 
jumpSpeed = -20
#  Simulate gravity 
gravity = 2

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

#  Loading 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

#  The clock 
clock = pygame.time.Clock()

#  Again 
is_restart = False
text_color = (0,0,0)
 Copy code 

Next , We passed a while Loop to keep the game going

while True:
    #  Per second 30 Time 
    clock.tick(30)
    ...
 Copy code 

In the above cycle , 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
 Copy code 

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()
                #  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 up the picture again 
            screen.blit(restart, restart_rect)
            screen.blit(gameover, gameover_rect)
            pygame.display.update()
 Copy code 

For collisions , As long as the dinosaurs hit the cactus , So the game is over , Show the pictures again

Because we hope the game can record our best results , So here we use local files to store game records , When the game is over , Judge whether to write the new score into the file according to the current game score

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)
 Copy code 

We also need to add different game difficulty to different distances , After all, running , The farther away you must be , The more difficult it is

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

    #  Change the background color , Results are 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)
 Copy code 

All of our elements are loaded into memory screen On

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

    pygame.display.update()
 Copy code 

To increase gameplay , We'll add background music and jumping sound

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

such , A simple and easy-to-use dinosaur running game is completed , Let's see the effect

At the end of the article

Your favorite collection is my greatest encouragement ! Welcome to follow me , Share Python dried food , communication Python technology . What's your opinion on the article , Or any technical problems , Welcome to leave a message and discuss in the comment area !

copyright notice
author[yz_ weixiao],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020649042654.html

Random recommended