Flappy Bird游戏python完整源码

通过pygame实现当年风靡一时的flappy bird小游戏。

当前只设定了同样长度的管道,图片和声音文件自行导入。

效果如下:

Flappy Bird游戏python完整源码_第1张图片Flappy Bird游戏python完整源码_第2张图片

# -*- coding:utf-8 -*-
"""
通过pygame实现曾风靡一时的flappybird游戏。
小鸟x坐标不变,画布左移实现飞行效果。
通过判断小鸟和管道矩形是否重叠认定碰撞。
清楚矩形4个参数的含义以及所使用图片素材的像素。
声音播放如果位于while循环内且只需要播放一次的,需要在循环外设定状态。
"""
import pygame
import sys


class Bird(object):
    """定义小鸟类"""
    def __init__(self):
        """定义初始化方法"""
        self.birdRect = pygame.Rect(65, 50, 54, 70)  # 小鸟的矩形
        # 定义小鸟的3种状态
        self.birdStatus = [pygame.image.load("assets/start.png"),
                           pygame.image.load("assets/fly.png"),
                           pygame.image.load("assets/dead.png")]
        self.status = 0  # 默认飞行状态
        self.birdX = 100  # 小鸟所在X轴坐标
        self.birdY = 300  # 小鸟所在Y轴坐标,即上下飞行的高度
        self.jump = False  # 默认情况下小鸟自动降落
        self.jumpSpeed = 8  # 跳跃高度
        self.gravity = 3  # 重力
        self.dead = False  # 默认小鸟生命状态为活着

    def birdUpdate(self):
        if self.jump:
            self.jumpSpeed -= 1  # 速度递减,上升越来越慢
            self.birdY -= self.jumpSpeed  # Y坐标轴减小,小鸟上升
        else:
            # 小鸟下坠
            self.gravity += 1
            self.birdY += self.gravity

        self.birdRect[1] = self.birdY  # 更新Y轴位置


class Pipeline(object):
    """管道类"""
    def __init__(self):
        self.wall_x = 300  # 上下管道X坐标
        self.pineUp = pygame.image.load("assets/top.png")
        self.pineDown = pygame.image.load("assets/bottom.png")

    def updatePipeline(self):
        self.wall_x -= 3  # 每一帧x坐标-3,即向左移动3像素
        # 当管道x坐标移动到-10位置时分数+1,并将其重置为500
        if self.wall_x < -10:
            global score
            score += 1
            self.wall_x = 500


def createMap():
    screen.fill((255, 255, 255))
    screen.blit(background, (0, 0))
    # 显示管道
    screen.blit(Pipeline.pineUp, (Pipeline.wall_x, 0))
    screen.blit(Pipeline.pineDown, (Pipeline.wall_x, 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)), (150, 100))
    # 更新显示
    pygame.display.update()


def checkDead():
    # 上方管道的矩形位置,Rect的4个参数分别为x坐标、y坐标,管道宽度、管道高度
    upRect = pygame.Rect(Pipeline.wall_x, 0, Pipeline.pineUp.get_width(), Pipeline.pineUp.get_height())
    # 下方管道的矩形位置
    downRect = pygame.Rect(Pipeline.wall_x, 700-(Pipeline.pineDown.get_height()),
                           Pipeline.pineDown.get_width(), 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


def getResult():  # 设置游戏结束时显示内容
    gameover_text = 'GAME OVER'
    score_text = 'Your final score is:' + str(score)
    ft1_surf = font.render(gameover_text, 1, (250, 5, 35))
    ft2_surf = font.render(score_text, 1, (250, 180, 6))
    screen.blit(ft1_surf, [screen.get_width()/2 - ft1_surf.get_width()/2, 150])
    screen.blit(ft2_surf, [screen.get_width()/2 - ft2_surf.get_width()/2, 200])
    pygame.display.flip()


if __name__ == '__main__':
    pygame.init()
    pygame.font.init()
    pygame.mixer.init()
    pygame.mixer.music.load('sound/fly.ogg')  # 载入音效
    pygame.mixer.music.load('sound/crashed.ogg')
    fly_sound = pygame.mixer.Sound('sound/fly.ogg')
    crashed_sound = pygame.mixer.Sound('sound/crashed.ogg')
    font = pygame.font.SysFont("None", 50)
    size = width, height = 450, 700
    screen = pygame.display.set_mode(size)
    clock = pygame.time.Clock()
    Pipeline = Pipeline()
    Bird = Bird()
    score = 0
    crashed_sound_play = True
    while True:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                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
                fly_sound.play()

        background = pygame.image.load('assets/background.png')

        if checkDead():
            getResult()
            fly_sound.stop()
            if crashed_sound_play:  # 通过此方法使得坠落音效播放一次,否则会一直播放
                crashed_sound.play()
                crashed_sound_play = False
        else:
            createMap()

你可能感兴趣的:(Python,游戏,pygame,python)