Python跳跳兔小游戏源代码,兔年必玩小游戏,兔年大吉,小兔子跳跳,按空格键向上跳跃,按键盘方向键进行左右移动,以避开飞弹,以防被炸,还可以捡到火箭道具哦。

完整程序下载地址:Python跳跳兔小游戏源代码

main.py

import pygame as pg
import random
import os
from settings import *
from sprites import *class Game:def __init__(self):pg.init()pg.mixer.init()self.screen = pg.display.set_mode((WIDTH, HEIGHT))pg.display.set_caption(TITLE)self.clock = pg.time.Clock()self.running = True# 设置绘制时使用的字体self.font_name = pg.font.match_font(FONT_NAME)self.load_data()def load_data(self): # 加载数据self.dir = os.path.dirname(__file__)filepath = os.path.join(self.dir, HS_FILE)with open(filepath, 'r') as f:try:self.highscore = int(f.read())except:self.highscore = 0img_dir = os.path.join(self.dir, 'img')# 加载精灵图片self.spritesheet = Spritesheet(os.path.join(img_dir, SPRITESHEET))# 加载云彩图片self.cloud_images = []for i in range(1, 4):self.cloud_images.append(pg.image.load(os.path.join(img_dir, 'cloud{}.png'.format(i))).convert())# 加载音乐self.snd_dir = os.path.join(self.dir, 'snd')# 跳跃时音效self.jump_sound = pg.mixer.Sound(os.path.join(self.snd_dir, 'Jump33.wav'))# 使用道具时音效self.boost_sound = pg.mixer.Sound(os.path.join(self.snd_dir, 'Boost16.wav'))def new(self):self.score = 0# self.all_sprites = pg.sprite.Group()# 层次添加,避免元素重叠显示(如背景云遮挡住平台与玩家)self.all_sprites = pg.sprite.LayeredUpdates()self.platforms = pg.sprite.Group()self.powerups = pg.sprite.Group() # 急速飞跃道具self.mobs = pg.sprite.Group() # 敌人对象self.clouds = pg.sprite.Group() # 云彩对象self.player = Player(self)self.all_sprites.add(self.player)for plat in PLATFORM_LIST:p = Platform(self, *plat)# self.all_sprites.add(p)# self.platforms.add(p)self.mob_timer = 0# 游戏的背景音乐pg.mixer.music.load(os.path.join(self.snd_dir, 'Happy Tune.ogg'))# 创建云彩for i in range(8):c = Cloud(self)c.rect.y += 500self.run()def run(self):# loops表示循环次数,-1表示音乐将无限播放下去pg.mixer.music.play(loops=-1)self.playing = Truewhile self.playing:self.clock.tick(FPS)self.events()self.update()self.draw()# 退出后停止音乐,fadeout(time)设置音乐淡出的时间,该方法会阻塞到音乐消失pg.mixer.music.fadeout(500)def update(self):self.all_sprites.update()# 产生敌人now = pg.time.get_ticks()# 通过时间间隔来判断是否要产生敌人if now - self.mob_timer > 5000 + random.choice([-1000, -500, 0, 500, 1000]):self.mob_timer = nowMob(self)# 碰撞检测 - 如果碰撞到了敌人,游戏结束mob_hits = pg.sprite.spritecollide(self.player, self.mobs, False, pg.sprite.collide_mask)if mob_hits:self.playing = False# 玩家在界面中时(y>0),进行碰撞检测,检测玩家是否碰撞到平台if self.player.vel.y > 0:hits = pg.sprite.spritecollide(self.player, self.platforms, False)if hits:lowest = hits[0]for hit in hits:if hit.rect.bottom > lowest.rect.bottom:lowest = hit # 保存最小的值# 避免平移效果 - 兔子最底部没有小于碰撞检测中的最小值,则不算跳跃到平台上if self.player.pos.y < lowest.rect.centery:self.player.pos.y = lowest.rect.topself.player.vel.y = 0self.player.jumping = False# 会产生平移效果# if hits:#     self.player.pos.y = hits[0].rect.top#     self.player.vel.y = 0# 玩家到达游戏框 1/4 处时(注意,游戏框,头部为0,底部为游戏框长度,到到游戏框的1/4处,表示已经到达了顶部一部分了)if self.player.rect.top <= HEIGHT / 4:# 玩家位置移动(往下移动)# self.player.pos.y += abs(self.player.vel.y)self.player.pos.y += max(abs(self.player.vel.y), 2)# 随机生成新云朵if random.randrange(100) < 10:Cloud(self)# 云彩同步移动for cloud in self.clouds:cloud.rect.y += max(abs(self.player.vel.y / 2), 2)# 敌人位置同步往下移动for mob in self.mobs:mob.rect.y += max(abs(self.player.vel.y), 2)# 平台在游戏框外时,将其注销,避免资源浪费for plat in self.platforms:# 平台移动位置(往下移动,移动的距离与玩家相同,这样玩家才能依旧站立在原本的平台上)# plat.rect.y += abs(self.player.vel.y)plat.rect.y += max(abs(self.player.vel.y), 2)if plat.rect.top >= HEIGHT: plat.kill()# 分数增加 - 平台销毁,分数相加self.score += 10# 碰撞检测 - 玩家碰撞到急速飞跃道具pow_hits = pg.sprite.spritecollide(self.player, self.powerups, True)for pow in pow_hits:# 道具类型 - 不同道具可以实现不同的效果if pow.type == 'boost':self.boost_sound.play() # 播放相应的音效self.player.vel.y = -BOOST_POWER # 快递移动的距离self.player.jumping = False # 此时不为跳跃状态# 死亡 - 玩家底部大于游戏框高度if self.player.rect.bottom > HEIGHT:for sprite in self.all_sprites:sprite.rect.y -= max(self.player.vel.y, 10)# 元素底部小于0 - 说明在游戏框外面,将其删除if sprite.rect.bottom < 0:sprite.kill()# 平台个数为0,游戏结束if len(self.platforms) == 0:self.playing = False# 判断平台数,产生新的平台while len(self.platforms) < 6:width = random.randrange(50, 100)# 平台虽然是随机生成的,但会生成在某一个范围内p = Platform(self, random.randrange(0, WIDTH - width),random.randrange(-75, -30))self.platforms.add(p)self.all_sprites.add(p)# 事件处理def events(self):for event in pg.event.get():# 关闭if event.type == pg.QUIT:if self.playing:self.playing = Falseself.running = False# 跳跃if event.type == pg.KEYDOWN:if event.key == pg.K_SPACE:self.player.jump()# 按钮抬起,减小跳跃速度,从而实现,快速点击,短跳,长按,长跳的效果if event.type == pg.KEYUP:if event.key == pg.K_SPACE:self.player.jump_cut()def draw(self):# 绘制self.screen.fill(BGCOLOR)self.all_sprites.draw(self.screen)# 绘制文字 - 具体的分数self.draw_text(str(self.score), 22, WHITE, WIDTH / 2, 15)# 翻转pg.display.flip()# 开始游戏的钩子函数def show_start_screen(self):pg.mixer.music.load(os.path.join(self.snd_dir, 'Yippee.ogg'))pg.mixer.music.play(loops=-1)self.screen.fill(BGCOLOR) # 填充颜色# 绘制文字self.draw_text(TITLE, 48, WHITE, WIDTH / 2, HEIGHT / 4)self.draw_text("Left and right button move, space bar jump", 22, WHITE, WIDTH / 2, HEIGHT / 2)self.draw_text("Press any key to start the game", 22, WHITE, WIDTH / 2, HEIGHT * 3 / 4)# 画布翻转pg.display.flip()self.wait_for_key() # 等待用户敲击键盘中的仍以位置pg.mixer.music.fadeout(500)def wait_for_key(self):waiting = Truewhile waiting:self.clock.tick(FPS)for event in pg.event.get():if event.type == pg.QUIT: # 点击退出,结束等待循环waiting = Falseself.running = Falseif event.type == pg.KEYUP: # 按下键盘,结束等待循环waiting = Falsedef show_go_screen(self):# game over/continueif not self.running: # 是否在运行returnpg.mixer.music.load(os.path.join(self.snd_dir, 'Yippee.ogg'))pg.mixer.music.play(loops=-1)self.screen.fill(BGCOLOR) # 游戏框背景颜色填充# 绘制文字self.draw_text("GAME OVER", 48, WHITE, WIDTH / 2, HEIGHT / 4)self.draw_text("Score: " + str(self.score), 22, WHITE, WIDTH / 2, HEIGHT / 2)self.draw_text("Press a key to play again", 22, WHITE, WIDTH / 2, HEIGHT * 3 / 4)# 判断分数if self.score > self.highscore:self.highscore = self.scoreself.draw_text("NEW HIGH SCORE!", 22, WHITE, WIDTH / 2, HEIGHT / 2 + 40)# 记录新的最高分到文件中 - 持久化with open(os.path.join(self.dir, HS_FILE), 'w') as f:f.write(str(self.score))else:self.draw_text("High Score: " + str(self.highscore), 22, WHITE, WIDTH / 2, HEIGHT / 2 + 40)# 翻转pg.display.flip()# 等待敲击任意键,self.wait_for_key()pg.mixer.music.fadeout(500)# 绘制文字def draw_text(self, text, size, color, x, y):font = pg.font.Font(self.font_name, size) # 设置字体与大小text_surface = font.render(text, True, color) # 设置颜色text_rect = text_surface.get_rect() # 获得字体对象text_rect.midtop = (x, y) # 定义位置self.screen.blit(text_surface, text_rect) # 在屏幕中绘制字体g = Game()
g.show_start_screen()
while g.running:g.new()g.show_go_screen()pg.quit()

完整程序下载地址:Python跳跳兔小游戏源代码

Python跳跳兔小游戏源代码,兔年必玩小游戏,兔年大吉相关推荐

  1. 机房计算机没游戏,一款童年必玩的游戏,小学机房肯定安装,如今都不一定能过关!...

    作为90后的我们,在小时候很多人家里并没有电脑,可能有些小部分小伙伴家里没电脑,但是家里的亲戚有电脑,于是我们去亲戚家的时候就看着那些舅舅姑妈哥哥姐姐大姨他们玩游戏,当时自己玩不了,只能看着他们玩我就 ...

  2. Python版基于pygame的玛丽快跑小游戏源代码,玛丽冒险小游戏代码,支持双人模式

    基于pygame的玛丽快跑小游戏源代码,玛丽冒险小游戏代码,支持双人模式 按空格进入单人模式,按't'进入双人模式,双人模式下玛丽1采用空格键上跳,玛丽2采用方向上键上跳. 完整代码下载地址:Pyth ...

  3. HTML趣味钢琴小游戏源代码,钢琴琴谱练习小游戏源代码

    HTML趣味钢琴小游戏源代码,钢琴琴谱练习小游戏源代码 完整代码下载地址:HTML趣味钢琴小游戏源代码,钢琴琴谱练习小游戏源代码 index.html <!DOCTYPE html> &l ...

  4. 能玩游戏的计算机名字,适合玩大型游戏的笔记本电脑排行榜前十名

    喜欢玩游戏的小伙伴们近期准备入手一台游戏笔记本,临近国庆中秋普天同庆的盛大节日,各大商家相继推出了促销活动,大家此时买笔记本电脑是优惠力度非常大的,小编为大家带来适合玩大型游戏的笔记本电脑推荐,欢迎查 ...

  5. Java黑皮书课后题第6章:**6.30(游戏:双骰子)掷双骰子游戏是某场景中非常流行的骰子游戏。编写程序,玩这个游戏的变种

    6.30(游戏:双骰子)掷双骰子游戏是某场景中非常流行的骰子游戏.编写程序,玩这个游戏的变种 题目 题目描述 破题 代码 题目 题目描述 6.30(游戏:双骰子)掷双骰子游戏是某场境中非常流行的骰子游 ...

  6. python3小游戏源代码_Python3制作仿“FlappyBird”小游戏|python3教程|python入门|python教程...

    https://www.xin3721.com/eschool/pythonxin3721/ 本文转载至知乎ID:Charles(白露未晞)知乎个人专栏 下载W3Cschool手机App,0基础随时随 ...

  7. 车险计算器微信小程序源代码下载【工具型小程序】

    简单的计算让你知道车险的价值 前两天,一个小伙伴私信我,说想找一个车险计算器的小程序源代码. 然后小二特别注意它,发现这个 还用了一个简单的源代码,所以边肖把它发给了大家. 知道如何具体介绍它,所以让 ...

  8. 校园服务小程序源代码分享园服务微信小程序全开源版源码-包含服务端

    2021年4月17日更新 严正声明: [请一定勿将程序用户商业用途且 包括 用此程序去参加各类学校的竞赛或者其他以获取名利而参与的竞赛等,一旦被原作者发现将会面临严重的侵权责任后果,特别是被获奖后会遭 ...

  9. 打游戏计算机内存不足,电脑玩cf游戏内存不足的两种解决方法

    电脑出现内存不足是一种较为常见的电脑故障,常见于运行大型游戏的时候发生此类故障.最近,一些小伙伴说电脑玩cf游戏内存不足,怎么办?cf穿越火线是一款第一人称射击游戏的网络游戏,如果想要运行cf游戏,不 ...

最新文章

  1. 继承和多态 1.0 -- 继承概念(is-a、has-a,赋值兼容规则,隐藏重定义)
  2. guava-collections
  3. 员工培训与开发实训心得体会_公司新员工培训心得体会800字范文
  4. dfs.datanode.max.xcievers参数导致hbase集群报错
  5. androidstudio自带git用法_Android Studio使用Git版本控制github
  6. 【java】java 理解JDK中UUID的底层实现
  7. Windows编程的Notification和Message
  8. 解决类似 /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found 的问题
  9. linux 4433端口,linux – 使用相同的openssl端口443绑定不同端口的apache ssl端口
  10. R-Sys.time计算程序运行时间
  11. java为table添加一行_Js实现Table动态添加一行的小例子
  12. hibernate中session 与JDBC中 connection分析
  13. java传文件到kafka_Java将CSV的数据发送到kafka的示例
  14. SnagIt怎么使用 SnagIt使用教程
  15. 软件工程 - chapter02 - 敏捷开发
  16. 怎么用Hypermesh划分球体网格
  17. require(): open_basedir restriction in effect. File(/www/wwwroot/wei/files/vendor/autoload.php)
  18. android媲美微信扫码库
  19. 计算机课吐槽,让上课更有趣!这位老师的课学生可发弹幕提问吐槽
  20. 简易磁盘写入速度测试工具(GO)

热门文章

  1. ARM架构二 ARMv5T架构简介
  2. 敏捷认证(Professional Scrum Master)PSM——❶认证介绍
  3. 苹果热在华退烧:新品不再受追捧
  4. linux的关机与重启
  5. Dagger的使用一
  6. BandLab Cakewalk 28.06 For Windows 老牌音乐制作宿主软件
  7. 一生情缘繫交大——卢善栋老学长
  8. hibernate的sessionfactory
  9. 利用JAVA实现显卡、声卡、网卡通过PCI插槽工作。
  10. 视频监控系统中的流媒体服务器,视频监控系统中的流媒体服务器、直写和全切换三种取流架构方案...