前言
又是一篇摸鱼小文章~相信这个游戏应该大多数人都玩过吧
话不多说,现在就来开整,赶紧做完,赶紧摸鱼
不得不说这个小游戏挑战性还蛮大的

开发工具
Python版本:3.6.4
相关模块:
pygame模块
以及一些Python自带的模块。
环境搭建
安装Python并添加到环境变量,pip安装需要的相关模块即可
原理介绍
FlappyBird游戏简介:
玩家通过空格键控制一只小鸟,使其跨越由各种不同长度水管所组成的障碍物,当小鸟碰撞到障碍物或跌至屏幕最底端时,游戏结束。
逐步实现:
Step1:定义精灵类
为了方便实现小鸟和水管之间碰撞的检测,
我们先定义一些精灵类,包括:
① 小鸟类
素材:
   
python学习交流Q群:770699889
def __init__(self):
"""定义初始化方法"""
self.birdRect = pygame.Rect(65, 50, 50, 50)
self.birdStatus = [pygame.image.load("assets/1.png"),
pygame.image.load("assets/2.png"),
pygame.image.load("assets/dead.png")]
self.status = 0
self.birdX = 120
self.birdY = 350
self.jump = False
self.jumpSpeed = 20
self.gravity = 3
self.dead = False
def birdUpdate(self):
if self.jump:
self.jumpSpeed -= 1
self.birdY -= self.jumpSpeed
else:
self.gravity += 0.2
self.birdY += self.gravity
self.birdRect[1] = self.birdY
② 管道类
管道分为管道体和管道头。
管道上部:

管道下部:

游戏背景

def __init__(self):
"""定义初始化方法"""
self.wallx = 400
self.pineUp = pygame.image.load("assets/top.png")
self.pineDown = pygame.image.load("assets/bottom.png")
def updatePipeline(self):
""""管道移动方法"""
self.wallx -= 5
if self.wallx < -80:
global score
score += 1
self.wallx = 400
创建地图然后设置管道、小鸟位置和状态,别忘记设置分数:
python学习交流Q群:770699889
def createMap():
"""定义创建地图的方法"""
screen.fill((255, 255, 255))
screen.blit(background, (0, 0))
screen.blit(Pipeline.pineUp, (Pipeline.wallx, -300))
screen.blit(Pipeline.pineDown, (Pipeline.wallx, 500))
Pipeline.updatePipeline()
if Bird.dead:
Bird.status = 2
elif Bird.jump:
Bird.status = 1
screen.blit(Bird.birdStatus[Bird.status], (Bird.birdX, Bird.birdY))
Bird.birdUpdate()
screen.blit(font.render('Score:' + str(score), -1, (255, 255, 255)), (100, 50))
pygame.display.update()

检测碰撞
def checkDead():
upRect = pygame.Rect(Pipeline.wallx, -300,
Pipeline.pineUp.get_width() - 10,
Pipeline.pineUp.get_height())
downRect = pygame.Rect(Pipeline.wallx, 500,
Pipeline.pineDown.get_width() - 10,
Pipeline.pineDown.get_height())
if upRect.colliderect(Bird.birdRect) or downRect.colliderect(Bird.birdRect):
Bird.dead = True
if not 0 < Bird.birdRect[1] < height:
Bird.dead = True
return True
else:
return False
Step2:实现游戏主循环
先初始化,载入图片、音乐、字体等文件,
并定义一些必要的常量:
if __name__ == '__main__':
"""主程序"""
pygame.init()
pygame.font.init()
font = pygame.font.SysFont("ziti.ttf", 50)
size = width, height = 400, 650
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
Pipeline = Pipeline()
Bird = Bird()
score = 0
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if (event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN) and not Bird.dead:
Bird.jump = True
Bird.gravity = 5
Bird.jumpSpeed = 10
background = pygame.image.load("assets/background.png")
if checkDead():
getResutl()
else:
createMap()
pygame.quit()
All Done!
完整代码
点击此处领取即可
 好了 今天的分享到这里就结束了
对文章有问题的,或者有其他关于python的问题,可以在评论区留言或者私信我哦 觉得我分享的文章不错的话,可以关注一下我,或者给文章点赞(/≧▽≦)/

|