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)

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/61845.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mysql通过.frm和.ibd 文件恢复数据库

问题背景&#xff1a;由于强制在服务关闭mysql导致部分数据表以及数据丢失 如下图只有.frm .ibd的文件为我的问题文件 查找不到表结构和表数据目录D:XXXX\mysql-5.7.24-winx64\data\mydata 从frm文件中恢复表结构 先把原来的数据备份一次 避免过程中出错 先备份之前数据的.fr…

聊聊Jasypt的StandardPBEByteEncryptor

序 本文主要研究一下Jasypt的StandardPBEByteEncryptor Jasypt Jasypt即Java Simplified Encryption&#xff0c;它主要是简化项目加解密的工作&#xff0c;内置提供了很多组件的集成&#xff0c;比如hibernate、spring、spring-security等 示例 示例1 StrongPasswordEnc…

【高危】Apache Airflow Spark Provider 反序列化漏洞 (CVE-2023-40195)

zhi.oscs1024.com​​​​​ 漏洞类型反序列化发现时间2023-08-29漏洞等级高危MPS编号MPS-qkdx-17bcCVE编号CVE-2023-40195漏洞影响广度广 漏洞危害 OSCS 描述Apache Airflow Spark Provider是Apache Airflow项目的一个插件&#xff0c;用于在Airflow中管理和调度Apache Spar…

QT使用QXlsx实现数据验证与Excel公式操作 QT基础入门【Excel的操作】

准备环境:QT中使用QtXlsx库的三种方法 1、公式操作写单行公式 //右值初始化Format rAlign;rAlign.setHorizontalAlignment(Format::AlignRight);//左值初始化Format lAlign;lAlign.setHorizontalAlignment(Format::AlignLeft);xlsx.write("B3", 40, lAlign);xlsx.wr…

Spark及其生态简介

一、Spark简介 Spark 是一个用来实现快速而通用的集群计算的平台&#xff0c;官网上的解释是&#xff1a;Apache Spark™是用于大规模数据处理的统一分析引擎。 Spark 适用于各种各样原先需要多种不同的分布式平台的场景&#xff0c;包括批处理、迭代算法、交互式查询、流处理…

Generated Knowledge Prompting for Commonsense Reasoning

本文是知识图谱系列相关的文章&#xff0c;针对《Generated Knowledge Prompting for Commonsense Reasoning》的翻译。 常识推理的生成知识提示 摘要1 引言2 生成知识提示3 实验设置4 实验结果5 相关工作6 结论 摘要 结合外部知识是否有利于常识推理&#xff0c;同时保持预训…

如何理解attention中的Q、K、V?

y直接用torch实现一个SelfAttention来说一说&#xff1a; 1、首先定义三哥线性变换&#xff0c;query&#xff0c;key以及value&#xff1a; class BertSelfAttention(nn.Module):self.query nn.Linear(config.hidden_size, self.all_head_size)#输入768&#xff0c;输出768…

Oracle Scheduler中日期表达式和PLSQL表达式的区别

参考文档&#xff1a; Database Administrator’s Guide 29.4.5.4 Differences Between PL/SQL Expression and Calendaring Syntax Behavior There are important differences in behavior between a calendaring expression and PL/SQL repeat interval. These differenc…

螺旋矩阵、旋转矩阵、矩阵Z字打印

螺旋矩阵 #include <iostream> #include <vector> void display(std::vector<std::vector<int>>&nums){for(int i 0; i < nums.size(); i){for(int j 0; j < nums[0].size(); j){std::cout<<nums[i][j]<< ;}std::cout<<…

从钉钉到金蝶云星空通过接口配置打通数据

从钉钉到金蝶云星空通过接口配置打通数据 对接系统钉钉 钉钉&#xff08;DingTalk&#xff09;是阿里巴巴集团打造的企业级智能移动办公平台&#xff0c;是数字经济时代的企业组织协同办公和应用开发平台。钉钉将IM即时沟通、钉钉文档、钉闪会、钉盘、Teambition、OA审批、智能…

v-on 和 v-bind

v-on 和 v-bind 都可以与回调函数一起使用&#xff0c;但它们的作用不同。 v-on&#xff1a; 这是Vue中用于绑定事件监听器的指令。你可以使用 v-on 来监听元素的各种事件&#xff08;如点击、输入、鼠标移动等&#xff09;&#xff0c;并在事件触发时执行指定的回调函数。所以…

算法通过村第五关-队列和Hash青铜笔记|队列和Hash

文章目录 前言1. Hash基础1.1 Hash的概念和基本特征1.2 碰撞处理方法1.2.1 开放地址法1.1.2 链地址法 2. 队列的基础2.1 队列的概念和基本特征2.2 队列的实现 总结 前言 提示&#xff1a;幸福的秘密是尽量扩大自己的兴趣范围对感兴趣的人和物尽可能的友善 --波特兰罗素 谈完栈&…

说说Omega架构

分析&回答 Omega架构我们暂且称之为混合数仓。 什么是ECS设计模式 在谈我们的解法的时候&#xff0c;必须要先提ECS的设计模式。 简单的说&#xff0c;Entity、Component、System分别代表了三类模型。 实体(Entity)&#xff1a;实体是一个普通的对象。通常&#xff0c…

在window上安装hadoop3.3.4

暑假不知道啥原因电脑死机啦。环境需要重新配一下 首先需要配置Hadoop集群&#xff0c;但是为了代码调试方便需要先在Windows上配置Hadoop环境。 1.前期准备 首先在搭建Hadoop环境之前需要先安装JDK&#xff0c;并且配置好Java环境变量。 这里有个bug就是Java环境变量中不允许…

视频动态壁纸 Dynamic Wallpaper for Mac中文

Dynamic Wallpaper是一款Mac平台上的动态壁纸应用程序&#xff0c;它可以根据时间等因素动态切换壁纸&#xff0c;提供更加生动和多样化的桌面体验。 Dynamic Wallpaper包含了多个动态壁纸&#xff0c;用户可以根据自己的喜好选择和切换。这些动态壁纸可以根据时间等因素进行自…

【Android Framework系列】第13章 SVG矢量图形自定义组件(绘制中国地图)

1 前言 本章节我们来了解下什么是SVG矢量图形&#xff0c;怎么通过SVG实现图形的绘制&#xff0c;通过SVG实现不规则的自定义控件&#xff0c;项目实现一个中国地图&#xff0c;实现每个省都能够点击&#xff0c;项目地址在文末请自取。 2 SVG概念 2.1 SVG矢量图形 SVG 指可…

二叉树的构建及遍历

目录 题目题目要求示例 解答方法一、实现思路时间复杂度和空间复杂度代码 方法二、实现思路时间复杂度和空间复杂度代码 题目 二叉树的构建及遍历 题目要求 题目链接 示例 解答 方法一、 先构建二叉树&#xff0c;再中序遍历。 实现思路 按照给出的字符串创建二叉树&am…

分布式定时任务框架选型,讲的太好了

1. 前言 我们先思考下面几个业务场景的解决方案: 支付系统每天凌晨1点跑批&#xff0c;进行一天清算&#xff0c;每月1号进行上个月清算电商整点抢购&#xff0c;商品价格8点整开始优惠12306购票系统&#xff0c;超过30分钟没有成功支付订单的&#xff0c;进行回收处理商品成…

Elasticsearch集群内的原理

一个运行中的 Elasticsearch 实例称为一个 节点&#xff0c;而集群是由一个或者多个拥有相同 cluster.name 配置的节点组成&#xff0c; 它们共同承担数据和负载的压力。当有节点加入集群中或者从集群中移除节点时&#xff0c;集群将会重新平均分布所有的数据。 当一个节点被选…

Leetcode 最后一个单词的长度

给你一个字符串 s&#xff0c;由若干单词组成&#xff0c;单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。 单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。 示例 1&#xff1a; 输入&#xff1a;s “Hello World” 输出&#xff1a;5 解释&a…