chrome小恐龙游戏【Python】

一、游戏效果图

(1)运行时

(2)结束后

二、具体代码

import pygame
from pygame.locals import *  # 导入pygame的常量
import sys
import time
import random


# 各个图片的位置
bg_site = [(0, 0), (640, 0)]  # 背景1和2的位置
dino_site = [45, 125]  # 恐龙的位置
ca_site = [(-52, 117), (-52, 130)]  # 仙人掌1和2的位置
# 分数
best_score = 0  # 历史最佳分数
score = 0  # 本次分数
# 设置恐龙是否跳跃
jump_up = False  # 控制向上跳跃的if
jump_down = False  # 控制向下跳跃的if
# 生成下一个仙人掌下标的相关参数(相同下标的参数对应同一种情况)
ca_con1_reset = [False, False]  # 判断是否可以生成下一个仙人掌的下标
ca_con1_use = [False, False]  # 判断是否使用了ca_con1_reset
ca_random_index = [0, 0]  # 存储随机生成的仙人掌下标


# 绘制图像
def draw(screen, background_1, background_2, dinosaur, cactus_1, cactus_2, font, font1, print_text):
    screen.blit(background_1, tuple(bg_site[0]))  # 绘制背景
    screen.blit(background_2, tuple(bg_site[1]))
    screen.blit(cactus_1, ca_site[0])  # 绘制仙人掌
    screen.blit(cactus_2, ca_site[1])
    screen.blit(dinosaur, tuple(dino_site))  # 绘制恐龙
    text1 = font.render(f"now:{int(score)}", True, (0, 0, 0))  # 绘制当前分数
    screen.blit(text1, (480, 10))
    text2 = font.render(f"history:{int(best_score)}", True, (0, 0, 0))  # 绘制历史分数
    screen.blit(text2, (300, 10))
    if print_text:  # 游戏结束时绘制
        text = font1.render("按下空格键继续游戏", True, (0, 0, 0))
        screen.blit(text, (160, 60))
    pygame.display.update()  # 更新画布


# 移动背景(设置背景坐标)
def background_move(index, speed):  # index:背景的下标 speed:移动速度
    global bg_site
    if bg_site[index][0] > -640:
        bg_site[index] = (bg_site[index][0] - speed, 0)
    else:
        bg_site[index] = (640, 0)


# 恐龙跳跃(设置跳跃时的恐龙坐标)
def dinosaur_jump():
    global dino_site, jump_up, jump_down
    if jump_up:
        if dino_site[1] >= 25: dino_site[1] -= 15
        else: jump_up = False; jump_down = True
    if jump_down:
        if dino_site[1] < 125: dino_site[1] += 15
        else: jump_down = False


# 移动仙人掌
def cactus_move(index, speed):  # index:仙人掌的下标 speed:移动速度
    global ca_site
    if -51 <= ca_site[index][0] <= 589:  # x坐标在这个范围里才移动
        ca_site[index] = (ca_site[index][0] - speed, ca_site[index][1])


# 判断是否可以设置出现坐标
def judge_cactus(index):  # index:仙人掌的下标
    global ca_con1_reset, ca_con1_use
    if 150 <= ca_site[index][0] <= 250:  # 如果该仙人掌的x坐标移动到[150,250],就可以确定它的下一个仙人掌是什么
        if not ca_con1_use[index]:  # 这段代码的作用是让x在[150,250]时,只生成一次下个仙人掌的值
            ca_con1_reset[index] = True
            ca_con1_use[index] = True
    else: ca_con1_use[index] = False


# 随机生成仙人掌最初的坐标
def cactus_site(index):  # index:仙人掌的下标
    global ca_site
    if ca_site[index][0] > -52:  # 如果该仙人掌还在移动范围内就不改变坐标
        return
    x = random.randint(500, 589)  # 随机生成x在[500,589]的整数
    ca_site[index] = (x, ca_site[index][1])


# 检测恐龙和仙人掌是否碰撞
def collision(dinosaur_mask, cactus1_mask, cactus2_mask):
    offset_1 = [ca_site[0][0] - dino_site[0], ca_site[0][1] - dino_site[1]]  # 恐龙和仙人掌1的偏移量
    offset_2 = [ca_site[1][0] - dino_site[0], ca_site[1][1] - dino_site[1]]  # 恐龙和仙人掌2的偏移量
    # mask1.overlap(mask2, (offset_x, offset_y)) 检查有无重叠
    if dinosaur_mask.overlap(cactus1_mask, tuple(offset_1)) or dinosaur_mask.overlap(cactus2_mask, tuple(offset_2)):
        return True
    else:
        return False


def start():
    global best_score, jump_up, jump_down, ca_con1_reset, ca_random_index, score, bg_site, dino_site, ca_site

    # 初始化页面
    pygame.init()
    screen = pygame.display.set_mode((640, 203))  # 屏幕大小
    pygame.display.set_caption("Chrome小恐龙游戏")  # 屏幕标题
    background_1 = pygame.image.load("background.jpg").convert()  # 加载背景1  convert()可以让image与screen的像素格式一致
    background_2 = pygame.image.load("background.jpg").convert()  # 加载背景2
    dinosaur = pygame.image.load("dinosaur.png").convert_alpha()  # 加载恐龙 convert_alpha()可以将图片变成透明
    dinosaur_mask = pygame.mask.from_surface(dinosaur)  # 生成蒙版
    cactus_1 = pygame.image.load("cactus_1.png").convert_alpha()  # 加载仙人掌1
    cactus1_mask = pygame.mask.from_surface(cactus_1)
    cactus_2 = pygame.image.load("cactus_2.png").convert_alpha()  # 加载仙人掌2
    cactus2_mask = pygame.mask.from_surface(cactus_2)

    # 要显示的字体
    font = pygame.font.Font("FZShuiYJW_Zhong.TTF", 20)
    font1 = pygame.font.Font("FZShuiYJW_Zhong.TTF", 35)

    # 控制游戏帧率
    clock = pygame.time.Clock()

    # 运行游戏
    while True:  # 让游戏能够重新开始
        # 初始化变量的值
        bg_site = [(0, 0), (640, 0)]  # 背景1和2的位置
        dino_site = [45, 125]  # 恐龙的位置
        ca_site = [(-52, 117), (-52, 130)]  # 仙人掌1和2的位置
        index = random.randint(0, 1)  # 随机生成第一次出现的仙人掌
        ca_random_index = [index, index]
        cactus_site(index)  # 设置第一次出现的仙人掌的位置
        draw(screen, background_1, background_2, dinosaur, cactus_1, cactus_2, font, font1, False)  # 绘制图像
        pre_time = time.time()  # 记录游戏开始的时刻
        speed = 10  # 背景和仙人掌的移动速度
        while True:  # 不断改变变量的值和画面+监听用户操作
            for event in pygame.event.get():  # 获取用户操作的事件
                # 按下退出键
                if event.type == QUIT:
                    pygame.quit()  # 释放pygame资源
                    sys.exit()  # 退出Python程序
                # 按下键盘
                elif not jump_up and not jump_down and event.type == KEYDOWN:  # 【前两个条件用来防止用户在恐龙跳跃时按下键盘】
                    jump_up = True

            # 时刻更新各个图像的坐标
            background_move(0, speed)  # 移动背景
            background_move(1, speed)
            dinosaur_jump()  # 恐龙跳跃事件
            cactus_move(0, speed)  # 移动仙人掌1
            judge_cactus(0)  # 判断是否可以生成仙人掌1的下一个仙人掌(的值)
            cactus_move(1, speed)  # 移动仙人掌2
            judge_cactus(1)  # 判断是否可以生成仙人掌1的下一个仙人掌(的值)
            if ca_con1_reset[0]:  # 生成下一个仙人掌(的值)
                ca_random_index[0] = random.randint(0, 1)
                ca_con1_reset[0] = False
            if ca_con1_reset[1]:
                ca_random_index[1] = random.randint(0, 1)
                ca_con1_reset[1] = False
            cactus_site(ca_random_index[0])  # 随机生成下一个仙人掌出现的位置
            cactus_site(ca_random_index[1])

            # 时刻绘制图像
            draw(screen, background_1, background_2, dinosaur, cactus_1, cactus_2, font, font1, False)

            # 时刻更新分数
            end_time = time.time()  # 目前的时刻
            run_time = end_time - pre_time  # 游戏运行的时间
            score = run_time * 20

            # 是否碰撞
            res = collision(dinosaur_mask, cactus1_mask, cactus2_mask)
            if res:
                break

            # 更新速度,speed ∈ [10,15]
            if int(score / 500) > 5:
                speed = 15
            else:
                speed = 10 + int(score / 500)

            # 设置游戏运行帧率
            clock.tick(30)  # 30帧/秒

        # 游戏失败后
        draw(screen, background_1, background_2, dinosaur, cactus_1, cactus_2, font, font1, True)
        best_score = max(best_score, score)  # 更新历史最佳分数
        go_on = True
        while go_on:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == KEYDOWN:  # 按下鼠标键,游戏继续
                    go_on = False


if __name__ == "__main__":
    start()

作者:时光-小巷

物联沃分享整理
物联沃-IOTWORD物联网 » chrome小恐龙游戏【Python】

发表回复