Chrome小恐龙快跑小游戏——Python实现
目录
视频演示
代码实现
视频演示
Chrome小恐龙快跑小游戏——Python实现
代码实现
import pygame
import os
import random
pygame.init()# Global Constants
SCREEN_HEIGHT = 600
SCREEN_WIDTH = 1100
game_over = False
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))RUNNING = [pygame.image.load(os.path.join("Dino", "DinoRun1.png")),pygame.image.load(os.path.join("Dino", "DinoRun2.png"))]
JUMPING = pygame.image.load(os.path.join("Dino", "DinoJump.png"))
DUCKING = [pygame.image.load(os.path.join("Dino", "DinoDuck1.png")),pygame.image.load(os.path.join("Dino", "DinoDuck2.png"))]SMALL_CACTUS = [pygame.image.load(os.path.join("Cactus", "SmallCactus1.png")),pygame.image.load(os.path.join("Cactus", "SmallCactus2.png")),pygame.image.load(os.path.join("Cactus", "SmallCactus3.png"))]
LARGE_CACTUS = [pygame.image.load(os.path.join("Cactus", "LargeCactus1.png")),pygame.image.load(os.path.join("Cactus", "LargeCactus2.png")),pygame.image.load(os.path.join("Cactus", "LargeCactus3.png"))]BIRD = [pygame.image.load(os.path.join("Bird", "Bird1.png")),pygame.image.load(os.path.join("Bird", "Bird2.png"))]CLOUD = pygame.image.load(os.path.join("Other", "Cloud.png"))BG = pygame.image.load(os.path.join("Other", "Track.png"))class Dinosaur:X_POS = 80Y_POS = 310Y_POS_DUCK = 340JUMP_VEL = 8.5def __init__(self):self.duck_img = DUCKINGself.run_img = RUNNINGself.jump_img = JUMPINGself.dino_duck = Falseself.dino_run = Trueself.dino_jump = Falseself.step_index = 0self.jump_vel = self.JUMP_VELself.image = self.run_img[0]self.dino_rect = self.image.get_rect()self.dino_rect.x = self.X_POSself.dino_rect.y = self.Y_POSdef update(self, userInput):if self.dino_duck:self.duck()if self.dino_run:self.run()if self.dino_jump:self.jump()if self.step_index >= 10:self.step_index = 0if userInput[pygame.K_UP] and not self.dino_jump:self.dino_duck = Falseself.dino_run = Falseself.dino_jump = Trueelif userInput[pygame.K_DOWN] and not self.dino_jump:self.dino_duck = Trueself.dino_run = Falseself.dino_jump = Falseelif not (self.dino_jump or userInput[pygame.K_DOWN]):self.dino_duck = Falseself.dino_run = Trueself.dino_jump = Falsedef duck(self):self.image = self.duck_img[self.step_index // 5]self.dino_rect = self.image.get_rect()self.dino_rect.x = self.X_POSself.dino_rect.y = self.Y_POS_DUCKself.step_index += 1def run(self):self.image = self.run_img[self.step_index // 5]self.dino_rect = self.image.get_rect()self.dino_rect.x = self.X_POSself.dino_rect.y = self.Y_POSself.step_index += 1def jump(self):self.image = self.jump_imgif self.dino_jump:self.dino_rect.y -= self.jump_vel * 4self.jump_vel -= 0.8if self.jump_vel < - self.JUMP_VEL:self.dino_jump = Falseself.jump_vel = self.JUMP_VELdef draw(self, SCREEN):SCREEN.blit(self.image, (self.dino_rect.x, self.dino_rect.y))class Cloud:def __init__(self):self.x = SCREEN_WIDTH + random.randint(800, 1000)self.y = random.randint(50, 100)self.image = CLOUDself.width = self.image.get_width()def update(self):self.x -= game_speedif self.x < -self.width:self.x = SCREEN_WIDTH + random.randint(2500, 3000)self.y = random.randint(50, 100)def draw(self, SCREEN):SCREEN.blit(self.image, (self.x, self.y))class Obstacle:def __init__(self, image, type):self.image = imageself.type = typeself.rect = self.image[self.type].get_rect()self.rect.x = SCREEN_WIDTHdef update(self):self.rect.x -= game_speedif self.rect.x < -self.rect.width:obstacles.pop()def draw(self, SCREEN):SCREEN.blit(self.image[self.type], self.rect)class SmallCactus(Obstacle):def __init__(self, image):self.type = random.randint(0, 2)super().__init__(image, self.type)self.rect.y = 325class LargeCactus(Obstacle):def __init__(self, image):self.type = random.randint(0, 2)super().__init__(image, self.type)self.rect.y = 300class Bird(Obstacle):def __init__(self, image):self.type = 0super().__init__(image, self.type)self.rect.y = 250self.index = 0def draw(self, SCREEN):if self.index >= 9:self.index = 0SCREEN.blit(self.image[self.index//5], self.rect)self.index += 1def main():global game_speed, x_pos_bg, y_pos_bg, points, obstaclesrun = Trueclock = pygame.time.Clock()player = Dinosaur()cloud = Cloud()game_speed = 20x_pos_bg = 0y_pos_bg = 380points = 0font = pygame.font.Font('freesansbold.ttf', 20)obstacles = []death_count = 0def score():global points, game_speedpoints += 1if points % 100 == 0:game_speed += 1text = font.render("Points: " + str(points), True, (0, 0, 0))textRect = text.get_rect()textRect.center = (1000, 40)SCREEN.blit(text, textRect)def update_high_score(score):high_score = read_high_score()if score > high_score:with open("high_score.txt", "w") as file:file.write(str(score))def background():global x_pos_bg, y_pos_bgimage_width = BG.get_width()SCREEN.blit(BG, (x_pos_bg, y_pos_bg))SCREEN.blit(BG, (image_width + x_pos_bg, y_pos_bg))if x_pos_bg <= -image_width:SCREEN.blit(BG, (image_width + x_pos_bg, y_pos_bg))x_pos_bg = 0x_pos_bg -= game_speedwhile run:for event in pygame.event.get():if event.type == pygame.QUIT:run = FalseSCREEN.fill((255, 255, 255))userInput = pygame.key.get_pressed()player.draw(SCREEN)player.update(userInput)if len(obstacles) == 0:if random.randint(0, 2) == 0:obstacles.append(SmallCactus(SMALL_CACTUS))elif random.randint(0, 2) == 1:obstacles.append(LargeCactus(LARGE_CACTUS))elif random.randint(0, 2) == 2:obstacles.append(Bird(BIRD))for obstacle in obstacles:obstacle.draw(SCREEN)obstacle.update()if player.dino_rect.colliderect(obstacle.rect) and player.dino_rect.right >= obstacle.rect.left:pygame.time.delay(2000)death_count += 1update_high_score(points)menu(death_count)background()cloud.draw(SCREEN)cloud.update()score()clock.tick(30)pygame.display.update()def read_high_score():try:with open("high_score.txt", "r") as file:high_score = int(file.read())except FileNotFoundError:high_score = 0return high_scoredef menu(death_count):high_score = read_high_score()global pointsrun = Truewhile run:SCREEN.fill((255, 255, 255))font = pygame.font.Font('freesansbold.ttf', 30)if death_count == 0:text = font.render("Press any Key to Start", True, (0, 0, 0))elif death_count > 0:text = font.render("Press any Key to Restart", True, (0, 0, 0))score = font.render("Your Score: " + str(points), True, (0, 0, 0))scoreRect = score.get_rect()scoreRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 50)SCREEN.blit(score, scoreRect)textRect = text.get_rect()textRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)high_score_text = font.render("High Score: " + str(high_score), True, (0, 0, 0))high_score_rect = high_score_text.get_rect()high_score_rect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 80)SCREEN.blit(high_score_text, high_score_rect)SCREEN.blit(text, textRect)SCREEN.blit(RUNNING[0], (SCREEN_WIDTH // 2 - 20, SCREEN_HEIGHT // 2 - 140))pygame.display.update()for event in pygame.event.get():if event.type == pygame.QUIT:run = Falseif event.type == pygame.KEYDOWN:main()menu(death_count=0)
相关文章:

Chrome小恐龙快跑小游戏——Python实现
目录 视频演示 代码实现 视频演示 Chrome小恐龙快跑小游戏——Python实现 代码实现 import pygame import os import random pygame.init()# Global Constants SCREEN_HEIGHT 600 SCREEN_WIDTH 1100 game_over False SCREEN pygame.display.set_mode((SCREEN_WIDTH, SCR…...

Web网站服务器
目录 一、什么是Apache? 二、虚拟目录是什么? 三、Apcahe相关配置文件 四、httpd.conf主配置文件的常用配置参数 五、Web网站配置案例 5.1搭建基于用户的个人主页网站 5.2、配置虚拟目录 5.3、配置虚拟主机 5.3.1搭建两个基于IP地址的虚拟主机 5.3.2搭建两个基于域…...

Docker consul 容器服务自动发现和更新
目录 一、什么是服务注册与发现 二、Docker-consul集群 1.Docker-consul consul提供的一些关键特性 2.registrator 3.Consul-template 三、Docker-consul实现过程 以配置nginx负载均衡为例 先配置consul-agent ,有两种模式server和client 四、Docker-cons…...
CentOS 8 执行yum命令报错:Failed to set locale, defaulting to C.UTF-8
今天Docker新搞了一个CentOS镜像,在运行基于该镜像的容器,执行yum命令时,遇到了如下报错: [rootGC Administrator]# yum install -y yum-utils Failed to set locale, defaulting to C.UTF-8 CentOS Linux 8 - AppStream …...

8. 损失函数与反向传播
8.1 损失函数 ① Loss损失函数一方面计算实际输出和目标之间的差距。 ② Loss损失函数另一方面为我们更新输出提供一定的依据。 8.2 L1loss损失函数 ① L1loss数学公式如下图所示,例子如下下图所示。 import torch from torch.nn import L1Loss inputs torch.tens…...

Angular安全专辑之四 —— 避免服务端可能的资源耗尽(NodeJS)
express-rate-limit是一个简单实用的npm包,用于在Express应用程序中实现速率限制。它可以帮助防止DDoS攻击和暴力破解,同时还允许对API端点进行流控。 express-rate-limit及其主要功能 express-rate-limit是Express框架的一个流行中间件,它允许根据IP地址或其他标准轻松地对请求…...

Servlet学习总结(Request请求与转发,Response响应,Servlet生命周期、体系结构、执行流程等...)
Override 是Java中的注解(Annotation),它用于告诉编译器该方法是覆盖(重写)父类中的方法。当我们使用Override注解时,编译器会检查当前方法是否正确地覆盖了父类中的方法,如果没有覆盖成功&…...

雅思写作 三小时浓缩学习顾家北 笔记总结(二)
目录 饥饿网一百句翻译 Using government funds for pollution cleanup work can create a comfortable environment. "Allocating government funds to pollution cleanup work can contribute to the creation of a comfortable environment." Some advertise…...

Element Plus 日期选择器的使用和属性
element plus 日期选择器如果如果没有进行处理 他会返回原有的属性值data格式 如果想要获取选中的日期时间就需要通过以下的代码来实现选中的值 format"YYYY/MM/DD" value-format"YYYY-MM-DD" <el-date-pickerv-model"formInline.date" type&…...

中国五百强企业用泛微为合同加速,提升数字化办公水平
华谊集团借力泛微,融合企业微信、SAP、WPS、电子签章等多种系统,构建了业务集成、场景驱动的全程数字化合同管理平台。 上海华谊(集团)公司是由上海市政府国有资产监督管理委员会授权,通过资产重组建立的大型化工企业…...
Vue3 QRCode生成
一. 依赖安装 npm install vue-qr --save 二. 引用与使用 引用 <script> // import vueqr from vue-qr vue2的引入 import vueqr from vue-qr/src/packages/vue-qr.vue // vue3的引入 export default {components: {vueqr} } </script> 使用 <template>&…...

2023年8月随笔之有顾忌了
1. 回头看 日更坚持了243天。 读《发布!设计与部署稳定的分布式系统》终于更新完成 选读《SQL经典实例》也更新完成 读《高性能MySQL(第4版)》开更,但目前暂缓 读《SQL学习指南(第3版)》开更并持续更新…...

正中优配:红筹股是啥意思?
随着我国经济的高速开展,越来越多的人开始参加到股票出资中。其中,红筹股作为一种特别类型的股票,备受一些出资者的关注,但对于一般出资者来说,红筹股详细含义还不是特别清楚。本文将从多个角度探讨红筹股的含义、特征…...

《Linux从练气到飞升》No.19 进程等待
🕺作者: 主页 我的专栏C语言从0到1探秘C数据结构从0到1探秘Linux菜鸟刷题集 😘欢迎关注:👍点赞🙌收藏✍️留言 🏇码字不易,你的👍点赞🙌收藏❤️关注对我真的…...

OpenCV
文章目录 OpenCV学习报告读取图片和网络摄像头1.1 图片读取1.2 视频读取1.1.1 读取视频文件1.1.2读取网络摄像头 OpenCV基础功能调整、裁剪图像3.1 调整图像大小3.2 裁剪图像 图像上绘制形状和文本4.1 图像上绘制形状4.2图像上写文字 透视变换图像拼接颜色检测轮廓检测人脸检测…...
hadoop解决数据倾斜的方法
分析&回答 1,如果预聚合不影响最终结果,可以使用conbine,提前对数据聚合,减少数据量。使用combinner合并,combinner是在map阶段,reduce之前的一个中间阶段,在这个阶段可以选择性的把大量的相同key数据先进行一个合并,可以看做…...
打造坚不可摧的代码堡垒 - 搭建GitLab私有仓库完全指南
在现代软件开发中,版本控制是一个不可或缺的环节。GitLab是一个流行的版本控制平台,允许开发团队协同工作并管理他们的代码。在某些情况下,您可能希望将您的代码托管在一个私有仓库中,以确保代码的安全性和机密性。在本文中&#…...
linux把文件压缩/解压成.tar.gz/tar/tgz等格式的命令大全
linux把文件压缩/解压成.tar.gz/tar/tgz等格式的命令大全 linux压缩命令常用的有:tar,tgz,gzip,zip,rar 一,tar(一) tar压缩命令#说明:#举例: (二…...

用户角色权限demo后续出现问题和解决
将demo账号给到理解和蒋老师,测试的时候将登录人账号改了,结果登录不了了,后续还需要分配权限无法更改他人的账号和密码 将用户和权限重新分配(数据库更改,不要学我) 试着登录还是报一样的错,但…...

SpringBoot在IDEA里实现热部署
使用步骤 1.引入依赖 <!--devtools热部署--> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional><scope>true</scope><versi…...

SpringBoot-17-MyBatis动态SQL标签之常用标签
文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…...

深入理解JavaScript设计模式之单例模式
目录 什么是单例模式为什么需要单例模式常见应用场景包括 单例模式实现透明单例模式实现不透明单例模式用代理实现单例模式javaScript中的单例模式使用命名空间使用闭包封装私有变量 惰性单例通用的惰性单例 结语 什么是单例模式 单例模式(Singleton Pattern&#…...
django filter 统计数量 按属性去重
在Django中,如果你想要根据某个属性对查询集进行去重并统计数量,你可以使用values()方法配合annotate()方法来实现。这里有两种常见的方法来完成这个需求: 方法1:使用annotate()和Count 假设你有一个模型Item,并且你想…...

全球首个30米分辨率湿地数据集(2000—2022)
数据简介 今天我们分享的数据是全球30米分辨率湿地数据集,包含8种湿地亚类,该数据以0.5X0.5的瓦片存储,我们整理了所有属于中国的瓦片名称与其对应省份,方便大家研究使用。 该数据集作为全球首个30米分辨率、覆盖2000–2022年时间…...
工程地质软件市场:发展现状、趋势与策略建议
一、引言 在工程建设领域,准确把握地质条件是确保项目顺利推进和安全运营的关键。工程地质软件作为处理、分析、模拟和展示工程地质数据的重要工具,正发挥着日益重要的作用。它凭借强大的数据处理能力、三维建模功能、空间分析工具和可视化展示手段&…...
使用van-uploader 的UI组件,结合vue2如何实现图片上传组件的封装
以下是基于 vant-ui(适配 Vue2 版本 )实现截图中照片上传预览、删除功能,并封装成可复用组件的完整代码,包含样式和逻辑实现,可直接在 Vue2 项目中使用: 1. 封装的图片上传组件 ImageUploader.vue <te…...
在Ubuntu中设置开机自动运行(sudo)指令的指南
在Ubuntu系统中,有时需要在系统启动时自动执行某些命令,特别是需要 sudo权限的指令。为了实现这一功能,可以使用多种方法,包括编写Systemd服务、配置 rc.local文件或使用 cron任务计划。本文将详细介绍这些方法,并提供…...

Python基于历史模拟方法实现投资组合风险管理的VaR与ES模型项目实战
说明:这是一个机器学习实战项目(附带数据代码文档),如需数据代码文档可以直接到文章最后关注获取。 1.项目背景 在金融市场日益复杂和波动加剧的背景下,风险管理成为金融机构和个人投资者关注的核心议题之一。VaR&…...
Go语言多线程问题
打印零与奇偶数(leetcode 1116) 方法1:使用互斥锁和条件变量 package mainimport ("fmt""sync" )type ZeroEvenOdd struct {n intzeroMutex sync.MutexevenMutex sync.MutexoddMutex sync.Mutexcurrent int…...
【学习笔记】erase 删除顺序迭代器后迭代器失效的解决方案
目录 使用 erase 返回值继续迭代使用索引进行遍历 我们知道类似 vector 的顺序迭代器被删除后,迭代器会失效,因为顺序迭代器在内存中是连续存储的,元素删除后,后续元素会前移。 但一些场景中,我们又需要在执行删除操作…...