Python3 FlappyBird
发布日期:2021-08-16 20:25:35 浏览次数:2 分类:技术文章

本文共 7941 字,大约阅读时间需要 26 分钟。

 

 

1 from InitObject import * 2  3 def startGame(): 4     moveDistance = -20 5     isButtonPlay = False    #是否按下开始按钮 6     isAlive = "birdIsAlive"      #鸟是否死亡 7     initObject(screen, imageDict, bgListNight, bgListDay, pipeList, birdListAlive, birdListDeath)     #初始化对象 8     buttonPlay = BaseClass(screen, 90, 300, imageDict[11], 116, 70)     #实例一个开始按钮 9     gameOver = BaseClass(screen, 50, 240, imageDict[13], 204, 54)10     11     while True:      12         ret = checkEvent()     #停止事件检测13         movingBackground(bgListNight, bgListDay)        #交替移动的背景14         movingPipe(pipeList)    #移动的管道15         screen.blit(textScore, (140, 0))16         if not isButtonPlay:    #判断开始按钮是否按下17             buttonPlay.display()18             if ret and ret[0] == "buttonDownPos" and buttonPlay.rect.collidepoint(ret[1]):19                     isButtonPlay = True20             screen.blit(getScore, (260, 0))21         else:       #已经按下开始按钮22             moveDistance += 523             showScore(moveDistance)24             25             if isAlive == "birdIsAlive":    #鸟是活着的状态26                 isButtonDownK_SPACE = ret   #判断是否应该向上跳跃,如果不跳跃,则自由落体27                 isAlive = birdAnimationAlive(pipeList, birdListAlive, isButtonDownK_SPACE)28                 29             if isAlive == "birdHasDeath":   #鸟是死了的状态30                 birdAnimationDeath(birdListDeath)   #鸟的死亡动画 31                 gameOver.display()  #显示makeover按钮32                 #单击gameover按钮,退出游戏33                 if ret and ret[0] == "buttonDownPos" and gameOver.rect.collidepoint(ret[1]):34                     sys.exit()35                36         37         pygame.display.update()38         39 if __name__ == "__main__":40     startGame()41   42
Main.py
1 import pygame 2 import time 3 import sys 4 import random 5 from pygame.locals import * 6  7 pygame.init() 8  9 font = pygame.font.SysFont("arial", 40)10 goodFont = pygame.font.SysFont("arial", 80)11 textScore = font.render("Score: ", True, (255, 0, 0))12 getScore =  font.render("0", True, (0, 255, 0))13 good =  goodFont.render("Good!", True, (255, 0, 0))14 frameCountPerSeconds = 10       #设置帧率15 moveDistance = 016 17 imageDict = {1: "./images/bird1_0.png", 2: "./images/bird1_1.png", 3: "./images/bird1_2.png", 4: "./images/bird2_0.png", 5: "./images/bird2_1.png", 6: "./images/bird2_2.png", 7: "./images/bg_night.png", 8: "./images/bg_day.png", 9: "./images/pipe2_down.png", 10: "./images/pipe2_up.png", 11: "./images/button_play.png", 12: "./images/text_ready.png", 13: "./images/text_game_over.png"}18 19 screen = pygame.display.set_mode((288, 512))    #加载图片到缓冲区,还没有展示在屏幕上,返回Surface对象20 pygame.display.set_caption("Author:筵")      #设置标题21 22 23 bgListNight = []      #三张夜晚背景容器24 bgListDay = []        #三张白天背景容器25 pipeList = []26 birdListAlive = []27 birdListDeath = []
Headers.py
1 from Methods import * 2  3 def initObject(screen, imageDict, bgListNight, bgListDay, pipeList, birdListAlive, birdListDeath): 4     for i in range(3):  #实例化三张夜晚背景 5         bgListNight.append(Background(screen, 288*i, 0, imageDict[7])) 6     for i in range(3):  #实例化三张白天背景 7         bgListDay.append(Background(screen, 288*i + 864, 0, imageDict[8]))    8     for i in range(6):  #实例化水管 9         rand = random.randrange(-200, -50)10         pipeList.append([Pipe(screen, 304+220*i, rand, imageDict[9]), Pipe(screen, 304+220*i, 500+rand, imageDict[10])]) 11     for i in range(3):      #初始化活鸟12         birdListAlive.append(Bird(screen, 36, 200, imageDict[i+1])) 13     for i in range(3):      #初始化死鸟14         birdListDeath.append(Bird(screen, 36, 200, imageDict[i+4]))
InitObject.py
from Headers import *#定义基类class BaseClass:    def __init__(self, screen, x, y, imagePath, rectX, rectY):        self.screen = screen        self.x = x        self.y = y        self.rect = Rect(self.x, self.y, rectX, rectY)        self.image = pygame.image.load(imagePath).convert_alpha()    def display(self):      #渲染到屏幕上        self.screen.blit(self.image, self.rect)#定义背景类,继承基类class Background(BaseClass):    def __init__(self, screen, x, y, imagePath):        super().__init__(screen, x, y, imagePath, 288, 512)    def moveLeft(self):     #向左移动        if self.rect.x < -288:            self.rect.x = 1440        self.rect = self.rect.move([-5, 0])#定义水管类,继承基类class Pipe(BaseClass):    def __init__(self, screen, x, y, imagePath):        super().__init__(screen, x, y, imagePath, 52, 320)        def moveLeft(self):        self.rect = self.rect.move([-5, 0])                 #定义小鸟类,继承基类class Bird(BaseClass):    def __init__(self, screen, x, y, imagePath):        super().__init__(screen, x, y, imagePath, 48, 48)            def moveDown(self):            self.rect = self.rect.move([0, 10])                 def deathDown(self):        if self.rect.y <= 400:            self.rect = self.rect.move([0, 50])              def moveUp(self):        self.rect = self.rect.move([0, -20])
Class.py
1 from Class import *  2   3   4 #检查停止事件  5 def checkEvent():  6     time.sleep(0.1)  7     press = pygame.key.get_pressed()    #检测按下ESC键退出游戏  8     if(press[K_ESCAPE]):  9         sys.exit() 10 #     elif press[K_SPACE]: 11 #         return "buttonDownKSpace" 12      13     for event in pygame.event.get():     14         if event.type == pygame.QUIT:   #检测单击X,退出游戏 15             sys.exit() 16              17         elif event.type == MOUSEBUTTONDOWN:     #获取鼠标单击位置 18             buttonDownPos = event.pos 19             return ("buttonDownPos", buttonDownPos) 20          21         elif event.type == KEYDOWN and event.key == K_SPACE:     #检测是否按下SPACE键 22 #             if event.key == K_SPACE:  23                 return "buttonDownK_SPACE" 24                  25          26              27 #三张夜晚背景和三张白天背景交替出现,向左移动 28 def movingBackground(bgListNight, bgListDay): 29     for i in range(3): 30         bgListNight[i].display() 31         bgListNight[i].moveLeft() 32  33     for i in range(3): 34         bgListDay[i].display() 35         bgListDay[i].moveLeft() 36          37 def movingPipe(pipeList): 38     for i in pipeList: 39         i[0].display() 40         i[0].moveLeft() 41         i[1].display() 42         i[1].moveLeft() 43          44 def birdAnimationAlive(pipeList, birdList, isButtonDownK_SPACE):   #自由下落的鸟 45     deltaTime  = time.time()   46     frameIndex = (int)(deltaTime/(1.0/frameCountPerSeconds))    47      48      49     if isButtonDownK_SPACE == "buttonDownK_SPACE": 50         for i in range(3): 51             birdList[i].moveUp() 52     else: 53         for i in range(3): 54             birdList[i].moveDown() 55    56     if frameIndex % 3 == 0:  57         birdList[0].display()          58     if frameIndex % 3 == 1: 59         birdList[1].display()      60     if frameIndex % 3 == 2:  61         birdList[2].display()  62      63     for i in pipeList: 64         if birdList[0].rect.colliderect(i[0].rect) or birdList[0].rect.colliderect(i[1].rect): 65             return "birdHasDeath" 66     if birdList[0].rect.y >= 512: 67         return "birdHasDeath" 68     else: 69         return "birdIsAlive" 70      71  72 def birdAnimationDeath(birdList): 73     deltaTime  = time.time()   74     frameIndex = (int)(deltaTime/(1.0/frameCountPerSeconds))    75     if frameIndex % 3 == 0:  76         birdList[0].display()          77     if frameIndex % 3 == 1: 78         birdList[1].display()      79     if frameIndex % 3 == 2:  80         birdList[2].display()  81     for i in range(3): 82             birdList[i].deathDown() 83      84          85          86          87 def showScore(moveDistance): 88     score = moveDistance // 220 89     if score <= 0: 90         score = 0 91     if score >= 6: 92         score = 6 93         screen.blit(good, (30, 200))   94     getScoreStart =  font.render(str(score), True, (255, 0, 0)) 95     screen.blit(getScoreStart, (260, 0)) 96      97      98      99     100     101     102
Methods.py

 

转载于:https://www.cnblogs.com/yan1314/articles/8904935.html

转载地址:https://blog.csdn.net/weixin_30823001/article/details/95778357 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Python——Pycharm安装、激活、中文、
下一篇:《深入理解bootstrap》读书笔记:第二章 整体架构

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月17日 21时43分27秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

Windows10开启电脑卓越性能模式,运行速度提升10%,CUP利用率达到50% 2019-04-26
Java 的Swing 之JFrame快速入门 2019-04-26
Mybatis快速入门(3)resultType(输出类型)一对一关联映射,一对多关联映射 2019-04-26
Android Studio创建shapeDrawable的方法 2019-04-26
Mybatis快速入门(4)Mybatis与Spring整合(增删改查)以及逆向工程 2019-04-26
Java 之 一天快速入门--SpringMVC快速入门(1)SpringMVC介绍、SpringMVC入门创建工程,SpringMVC执行流程 2019-04-26
计算机二级C语言:大题程序修改题 2019-04-26
Android Studio 实现注册信息表单验证的源代码(实现账号,密码,邮箱,手机号验证) 2019-04-26
Android Studio 安卓手机上实现火柴人动画(Java源代码—Python) 2019-04-26
SpringMVC快速入门(2)商品列表的加载 2019-04-26
SpringMVC快速入门(3)默认组件加载 2019-04-26
SpringMVC快速入门(4)SpringMVC整合Mybatis,SpringMVC参数绑定 2019-04-26
Java 解决SpringMVC的post请求乱码的问题 2019-04-26
SpringMVC快速入门(5)高级参数的绑定,@RequestMapping注解的用法,Controller方法返回值,SpringMVC当中的异常处理 2019-04-26
Java SSM 项目实战 day02 功能介绍,SSM整合,数据库和IDEA的maven工程搭建,产品信息查询和添加 2019-04-26
Java SSM 项目实战 day03 功能介绍,订单的操作,订单的增删改查 2019-04-26
Java SSM 项目实战 day04 功能介绍,订单的操作,订单的增删改查,实现登录功能 2019-04-26
Android Studio 实现登录注册-源代码 (连接MySql数据库) 2019-04-26
C/C++语言数据结构快速入门(一)(代码解析+内容解析)数据结构基本内容和线性表 2019-04-26
Android Studio 实现登录注册-源代码 二(Servlet + 连接MySql数据库) 2019-04-26