使用Python开发一个恐龙跑跑小游戏,玩起来

简介: 使用Python开发一个恐龙跑跑小游戏,玩起来

相信很多人都玩过 chrome 浏览器上提供的恐龙跑跑游戏,在我们断网或者直接在浏览器输入地址“chrome://dino/”都可以进入游戏


今天我们就是用 Python 来制作一个类似的小游戏

素材准备

首先我们准备下游戏所需的素材,比如恐龙图片,仙人掌图片,天空,地面等等,我们统一放到 dino 文件夹下


游戏逻辑

我们使用 Pygame 来制作游戏,先进行游戏页面的初始化

import pygame
# 初始化
pygame.init()
pygame.mixer.init()
# 设置窗口大小
screen = pygame.display.set_mode((900, 200))
# 设置标题
pygame.display.set_caption("恐龙跳跳")
# 使用系统自带的字体
my_font = pygame.font.SysFont("arial", 20)
score = 0
# 背景色
bg_color = (218,220,225)

接下来我们将各种素材加载进内存

# 加载正常恐龙
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 初始值
dino_rect.x = 100
# y 初始值
dino_rect.y = 150
# print(dino_rect)
# 设置y轴上的初速度为0
y_speed = 0
# 起跳初速度
jumpSpeed = -20
# 模拟重力
gravity = 2
 加载地面
ground = pygame.image.load("dino/ground.png")
# 加载仙人掌
cactus = pygame.image.load("dino/cactus1.png")
cactus_rect = cactus.get_rect()
cactus_rect.x,cactus_rect.y = 900,140
# 加载重新再来
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
# 加载 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_speed = 10
ground_move_distance = 0
# 时钟
clock = pygame.time.Clock()
# 重新再来一次
is_restart = False
text_color = (0,0,0)

再接下来,我们通过一个 while 死循环来保持游戏进程

while True:
    # 每秒30次
    clock.tick(30)
    ...

在上面的循环当中,我们需要两个检测机制,事件检测和碰撞检测

事件检测

# 事件侦测
    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()
        # 空格键侦测
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and dino_rect.y==150:
                y_speed = jumpSpeed

主要检测退出事件和空格键事件

碰撞检测

# 碰撞检测
    if dino_rect.colliderect(cactus_rect):
        while not is_restart:
            # 事件侦测
            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()
                # 空格键侦测
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        is_restart = True
                        bg_color = (218,220,225)
                        ground_speed = 10
            # 设置重新再来图片
            screen.blit(restart, restart_rect)
            screen.blit(gameover, gameover_rect)
            pygame.display.update()

对于碰撞,只要恐龙碰撞到了仙人掌,那么游戏结束,展示重新再来图片

由于我们希望游戏可以记录我们的最好成绩,所以这里使用了本地文件存储游戏记录的方式,当游戏结束的时候,根据当前游戏成绩来判断是否将新的成绩写入文件当中

下面是计算跑动距离和最好成绩的代码

# 统计距离
    score += ground_speed
    score_surface = my_font.render("Distance: "+str(score), True, text_color)
    # 计算最好成绩
    result_flag = False
    if score >= best:
        best = score
        result_flag = True
    best_result = my_font.render("Best Result: " + str(best), True, text_color)

我们还需要给不同距离增加不同的游戏难度,毕竟跑起来,肯定距离越远,难度越大嘛

# 更换背景色,成绩大于4000
    if score > 4000:
        bg_color = (55,55,55)
        ground_speed = 15
        text_color = (255,255, 255)
# 更换背景色,成绩大于8000
    if score > 8000:
        bg_color = (220,20,60)
        ground_speed = 20
        text_color = (255, 255, 255)
    # 更换背景色,成绩大于12000
    if score > 12000:
        bg_color = (25,25,112)
        ground_speed = 25
        text_color = (255, 255, 255)
    # 设置背景色
    screen.fill(bg_color)

最后我们将所有加载到内存当中的元素都呈现在 screen 上

# 设置地面图片1
    screen.blit(ground, (0-ground_move_distance, 180))
    # 设置地面图片2,在右边边界外
    screen.blit(ground, (900-ground_move_distance, 180))
    # 设置恐龙图片
    screen.blit(dino_list[index % 6], dino_rect)
    # 设置仙人掌图片
    screen.blit(cactus, cactus_rect)
    # 设置分数
    screen.blit(score_surface,(780,20))
    # 设置最好成绩
    screen.blit(best_result, (20, 20))
    pygame.display.update()

为了增加游戏性,我们再增加背景音乐和跳跃音效

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

这样,一个简单易用的恐龙跑跑游戏就完成了,我们来看下效果吧


好了,今天的分享就到这里,喜欢就点个

相关文章
|
3月前
|
存储 监控 算法
淘宝买家秀 API开发实录Python(2025)
本文讲述了作者在电商开发领域,尤其是对接淘宝买家秀 API 接口过程中所经历的挑战与收获。从申请接入、签名验证、频率限制到数据处理和实时监控,作者分享了多个实战经验与代码示例,帮助开发者更高效地获取和处理买家秀数据,提升开发效率。
|
2月前
|
设计模式 人工智能 API
AI智能体开发实战:17种核心架构模式详解与Python代码实现
本文系统解析17种智能体架构设计模式,涵盖多智能体协作、思维树、反思优化与工具调用等核心范式,结合LangChain与LangGraph实现代码工作流,并通过真实案例验证效果,助力构建高效AI系统。
391 7
|
2月前
|
小程序 PHP 图形学
热门小游戏源码(Python+PHP)下载-微信小程序游戏源码Unity发实战指南​
本文详解如何结合Python、PHP与Unity开发并部署小游戏至微信小程序。涵盖技术选型、Pygame实战、PHP后端对接、Unity转换适配及性能优化,提供从原型到发布的完整指南,助力开发者快速上手并发布游戏。
|
3月前
|
算法 程序员 API
电商程序猿开发实录:淘宝商品python(2)
本文分享了开发者在对接淘宝商品详情API过程中的真实经历,涵盖权限申请、签名验证、限流控制、数据解析及消息订阅等关键环节,提供了实用的Python代码示例,帮助开发者高效调用API,提升系统稳定性与数据处理能力。
|
4月前
|
数据采集 存储 数据库
Python爬虫开发:Cookie池与定期清除的代码实现
Python爬虫开发:Cookie池与定期清除的代码实现
|
5月前
|
人工智能 搜索推荐 数据可视化
用 Python 制作简单小游戏教程:手把手教你开发猜数字游戏
本教程详细讲解了用Python实现经典猜数字游戏的完整流程,涵盖从基础规则到高级功能的全方位开发。内容包括游戏逻辑设计、输入验证与错误处理、猜测次数统计、难度选择、彩色输出等核心功能,并提供完整代码示例。同时,介绍了开发环境搭建及调试方法,帮助初学者快速上手。最后还提出了图形界面、网络对战、成就系统等扩展方向,鼓励读者自主创新,打造个性化游戏版本。适合Python入门者实践与进阶学习。
584 1
|
5月前
|
存储 算法 数据可视化
用Python开发猜数字游戏:从零开始的手把手教程
猜数字游戏是编程入门经典项目,涵盖变量、循环、条件判断等核心概念。玩家通过输入猜测电脑生成的随机数,程序给出提示直至猜中。项目从基础实现到功能扩展,逐步提升难度,适合各阶段Python学习者。
309 0
|
IDE 开发工具 Android开发
Python开发神器PyCharm,体验下吧
Python开发神器PyCharm,体验下吧
293 0
Python开发神器PyCharm,体验下吧
|
存储 监控 IDE
猪行天下之Python基础——1.3 Python开发IDE之PyCharm(下)
内容简述: 1、为什么要使用IDE? 2、PyCharm的下载安装 3、PyCharm的基本使用 4、PyCharm程序调试 5、共用全局的Python解释器
357 0
|
IDE 开发工具 开发者
猪行天下之Python基础——1.3 Python开发IDE之PyCharm(中)
内容简述: 1、为什么要使用IDE? 2、PyCharm的下载安装 3、PyCharm的基本使用 4、PyCharm程序调试 5、共用全局的Python解释器
279 0

推荐镜像

更多