当前位置: 首页 > news >正文

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? 二、虚拟目录是什么&#xff1f; 三、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 &#xff0c;有两种模式server和client 四、Docker-cons…...

CentOS 8 执行yum命令报错:Failed to set locale, defaulting to C.UTF-8

今天Docker新搞了一个CentOS镜像&#xff0c;在运行基于该镜像的容器&#xff0c;执行yum命令时&#xff0c;遇到了如下报错&#xff1a; [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数学公式如下图所示&#xff0c;例子如下下图所示。 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中的注解&#xff08;Annotation&#xff09;&#xff0c;它用于告诉编译器该方法是覆盖&#xff08;重写&#xff09;父类中的方法。当我们使用Override注解时&#xff0c;编译器会检查当前方法是否正确地覆盖了父类中的方法&#xff0c;如果没有覆盖成功&…...

雅思写作 三小时浓缩学习顾家北 笔记总结(二)

目录 饥饿网一百句翻译 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&…...

中国五百强企业用泛微为合同加速,提升数字化办公水平

华谊集团借力泛微&#xff0c;融合企业微信、SAP、WPS、电子签章等多种系统&#xff0c;构建了业务集成、场景驱动的全程数字化合同管理平台。 上海华谊&#xff08;集团&#xff09;公司是由上海市政府国有资产监督管理委员会授权&#xff0c;通过资产重组建立的大型化工企业…...

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天。 读《发布&#xff01;设计与部署稳定的分布式系统》终于更新完成 选读《SQL经典实例》也更新完成 读《高性能MySQL&#xff08;第4版&#xff09;》开更&#xff0c;但目前暂缓 读《SQL学习指南&#xff08;第3版&#xff09;》开更并持续更新…...

正中优配:红筹股是啥意思?

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

《Linux从练气到飞升》No.19 进程等待

&#x1f57a;作者&#xff1a; 主页 我的专栏C语言从0到1探秘C数据结构从0到1探秘Linux菜鸟刷题集 &#x1f618;欢迎关注&#xff1a;&#x1f44d;点赞&#x1f64c;收藏✍️留言 &#x1f3c7;码字不易&#xff0c;你的&#x1f44d;点赞&#x1f64c;收藏❤️关注对我真的…...

OpenCV

文章目录 OpenCV学习报告读取图片和网络摄像头1.1 图片读取1.2 视频读取1.1.1 读取视频文件1.1.2读取网络摄像头 OpenCV基础功能调整、裁剪图像3.1 调整图像大小3.2 裁剪图像 图像上绘制形状和文本4.1 图像上绘制形状4.2图像上写文字 透视变换图像拼接颜色检测轮廓检测人脸检测…...

hadoop解决数据倾斜的方法

分析&回答 1&#xff0c;如果预聚合不影响最终结果&#xff0c;可以使用conbine&#xff0c;提前对数据聚合&#xff0c;减少数据量。使用combinner合并,combinner是在map阶段,reduce之前的一个中间阶段,在这个阶段可以选择性的把大量的相同key数据先进行一个合并,可以看做…...

打造坚不可摧的代码堡垒 - 搭建GitLab私有仓库完全指南

在现代软件开发中&#xff0c;版本控制是一个不可或缺的环节。GitLab是一个流行的版本控制平台&#xff0c;允许开发团队协同工作并管理他们的代码。在某些情况下&#xff0c;您可能希望将您的代码托管在一个私有仓库中&#xff0c;以确保代码的安全性和机密性。在本文中&#…...

linux把文件压缩/解压成.tar.gz/tar/tgz等格式的命令大全

linux把文件压缩/解压成.tar.gz/tar/tgz等格式的命令大全 linux压缩命令常用的有&#xff1a;tar&#xff0c;tgz&#xff0c;gzip&#xff0c;zip&#xff0c;rar 一&#xff0c;tar&#xff08;一&#xff09; tar压缩命令#说明&#xff1a;#举例&#xff1a; &#xff08;二…...

用户角色权限demo后续出现问题和解决

将demo账号给到理解和蒋老师&#xff0c;测试的时候将登录人账号改了&#xff0c;结果登录不了了&#xff0c;后续还需要分配权限无法更改他人的账号和密码 将用户和权限重新分配&#xff08;数据库更改&#xff0c;不要学我&#xff09; 试着登录还是报一样的错&#xff0c;但…...

SpringBoot在IDEA里实现热部署

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

浅谈 React Hooks

React Hooks 是 React 16.8 引入的一组 API&#xff0c;用于在函数组件中使用 state 和其他 React 特性&#xff08;例如生命周期方法、context 等&#xff09;。Hooks 通过简洁的函数接口&#xff0c;解决了状态与 UI 的高度解耦&#xff0c;通过函数式编程范式实现更灵活 Rea…...

Java 语言特性(面试系列2)

一、SQL 基础 1. 复杂查询 &#xff08;1&#xff09;连接查询&#xff08;JOIN&#xff09; 内连接&#xff08;INNER JOIN&#xff09;&#xff1a;返回两表匹配的记录。 SELECT e.name, d.dept_name FROM employees e INNER JOIN departments d ON e.dept_id d.dept_id; 左…...

基于大模型的 UI 自动化系统

基于大模型的 UI 自动化系统 下面是一个完整的 Python 系统,利用大模型实现智能 UI 自动化,结合计算机视觉和自然语言处理技术,实现"看屏操作"的能力。 系统架构设计 #mermaid-svg-2gn2GRvh5WCP2ktF {font-family:"trebuchet ms",verdana,arial,sans-…...

Java 语言特性(面试系列1)

一、面向对象编程 1. 封装&#xff08;Encapsulation&#xff09; 定义&#xff1a;将数据&#xff08;属性&#xff09;和操作数据的方法绑定在一起&#xff0c;通过访问控制符&#xff08;private、protected、public&#xff09;隐藏内部实现细节。示例&#xff1a; public …...

DeepSeek 赋能智慧能源:微电网优化调度的智能革新路径

目录 一、智慧能源微电网优化调度概述1.1 智慧能源微电网概念1.2 优化调度的重要性1.3 目前面临的挑战 二、DeepSeek 技术探秘2.1 DeepSeek 技术原理2.2 DeepSeek 独特优势2.3 DeepSeek 在 AI 领域地位 三、DeepSeek 在微电网优化调度中的应用剖析3.1 数据处理与分析3.2 预测与…...

盘古信息PCB行业解决方案:以全域场景重构,激活智造新未来

一、破局&#xff1a;PCB行业的时代之问 在数字经济蓬勃发展的浪潮中&#xff0c;PCB&#xff08;印制电路板&#xff09;作为 “电子产品之母”&#xff0c;其重要性愈发凸显。随着 5G、人工智能等新兴技术的加速渗透&#xff0c;PCB行业面临着前所未有的挑战与机遇。产品迭代…...

centos 7 部署awstats 网站访问检测

一、基础环境准备&#xff08;两种安装方式都要做&#xff09; bash # 安装必要依赖 yum install -y httpd perl mod_perl perl-Time-HiRes perl-DateTime systemctl enable httpd # 设置 Apache 开机自启 systemctl start httpd # 启动 Apache二、安装 AWStats&#xff0…...

Go 语言接口详解

Go 语言接口详解 核心概念 接口定义 在 Go 语言中&#xff0c;接口是一种抽象类型&#xff0c;它定义了一组方法的集合&#xff1a; // 定义接口 type Shape interface {Area() float64Perimeter() float64 } 接口实现 Go 接口的实现是隐式的&#xff1a; // 矩形结构体…...

DIY|Mac 搭建 ESP-IDF 开发环境及编译小智 AI

前一阵子在百度 AI 开发者大会上&#xff0c;看到基于小智 AI DIY 玩具的演示&#xff0c;感觉有点意思&#xff0c;想着自己也来试试。 如果只是想烧录现成的固件&#xff0c;乐鑫官方除了提供了 Windows 版本的 Flash 下载工具 之外&#xff0c;还提供了基于网页版的 ESP LA…...

数据链路层的主要功能是什么

数据链路层&#xff08;OSI模型第2层&#xff09;的核心功能是在相邻网络节点&#xff08;如交换机、主机&#xff09;间提供可靠的数据帧传输服务&#xff0c;主要职责包括&#xff1a; &#x1f511; 核心功能详解&#xff1a; 帧封装与解封装 封装&#xff1a; 将网络层下发…...