python小游戏——像素鸟代码开源

简介: python小游戏——像素鸟代码开源

一.呈现效果

二.主代码

'''
Function:
    坠落的小鸟小游戏
'''
import cfg
import sys
import random
import pygame
from modules import *
'''游戏初始化'''
def initGame():
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode((cfg.SCREENWIDTH, cfg.SCREENHEIGHT))
    pygame.display.set_caption('坠落的小鸟 ——源码基地:959755565 ')
    return screen
'''显示当前分数'''
def showScore(screen, score, number_images):
    digits = list(str(int(score)))
    width = 0
    for d in digits:
        width += number_images.get(d).get_width()
    offset = (cfg.SCREENWIDTH - width) / 2
    for d in digits:
        screen.blit(number_images.get(d), (offset, cfg.SCREENHEIGHT*0.1))
        offset += number_images.get(d).get_width()
'''主函数'''
def main():
    screen = initGame()
    # 加载必要的游戏资源
    # --导入音频
    sounds = dict()
    for key, value in cfg.AUDIO_PATHS.items():
        sounds[key] = pygame.mixer.Sound(value)
    # --导入数字图片
    number_images = dict()
    for key, value in cfg.NUMBER_IMAGE_PATHS.items():
        number_images[key] = pygame.image.load(value).convert_alpha()
    # --管道
    pipe_images = dict()
    pipe_images['bottom'] = pygame.image.load(random.choice(list(cfg.PIPE_IMAGE_PATHS.values()))).convert_alpha()
    pipe_images['top'] = pygame.transform.rotate(pipe_images['bottom'], 180)
    # --小鸟图片
    bird_images = dict()
    for key, value in cfg.BIRD_IMAGE_PATHS[random.choice(list(cfg.BIRD_IMAGE_PATHS.keys()))].items():
        bird_images[key] = pygame.image.load(value).convert_alpha()
    # --背景图片
    backgroud_image = pygame.image.load(random.choice(list(cfg.BACKGROUND_IMAGE_PATHS.values()))).convert_alpha()
    # --其他图片
    other_images = dict()
    for key, value in cfg.OTHER_IMAGE_PATHS.items():
        other_images[key] = pygame.image.load(value).convert_alpha()
    # 游戏开始界面
    game_start_info = startGame(screen, sounds, bird_images, other_images, backgroud_image, cfg)
    # 进入主游戏
    score = 0
    bird_pos, base_pos, bird_idx = list(game_start_info.values())
    base_diff_bg = other_images['base'].get_width() - backgroud_image.get_width()
    clock = pygame.time.Clock()
    # --管道类
    pipe_sprites = pygame.sprite.Group()
    for i in range(2):
        pipe_pos = Pipe.randomPipe(cfg, pipe_images.get('top'))
        pipe_sprites.add(Pipe(image=pipe_images.get('top'), position=(cfg.SCREENWIDTH+200+i*cfg.SCREENWIDTH/2, pipe_pos.get('top')[-1])))
        pipe_sprites.add(Pipe(image=pipe_images.get('bottom'), position=(cfg.SCREENWIDTH+200+i*cfg.SCREENWIDTH/2, pipe_pos.get('bottom')[-1])))
    # --bird类
    bird = Bird(images=bird_images, idx=bird_idx, position=bird_pos)
    # --是否增加pipe
    is_add_pipe = True
    # --游戏是否进行中
    is_game_running = True
    while is_game_running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
                    bird.setFlapped()
                    sounds['wing'].play()
        # --碰撞检测
        for pipe in pipe_sprites:
            if pygame.sprite.collide_mask(bird, pipe):
                sounds['hit'].play()
                is_game_running = False
        # --更新小鸟
        boundary_values = [0, base_pos[-1]]
        is_dead = bird.update(boundary_values, float(clock.tick(cfg.FPS))/1000.)
        if is_dead:
            sounds['hit'].play()
            is_game_running = False
        # --移动base实现小鸟往前飞的效果
        base_pos[0] = -((-base_pos[0] + 4) % base_diff_bg)
        # --移动pipe实现小鸟往前飞的效果
        flag = False
        for pipe in pipe_sprites:
            pipe.rect.left -= 4
            if pipe.rect.centerx < bird.rect.centerx and not pipe.used_for_score:
                pipe.used_for_score = True
                score += 0.5
                if '.5' in str(score):
                    sounds['point'].play()
            if pipe.rect.left < 5 and pipe.rect.left > 0 and is_add_pipe:
                pipe_pos = Pipe.randomPipe(cfg, pipe_images.get('top'))
                pipe_sprites.add(Pipe(image=pipe_images.get('top'), position=pipe_pos.get('top')))
                pipe_sprites.add(Pipe(image=pipe_images.get('bottom'), position=pipe_pos.get('bottom')))
                is_add_pipe = False
            elif pipe.rect.right < 0:
                pipe_sprites.remove(pipe)
                flag = True
        if flag: is_add_pipe = True
        # --绑定必要的元素在屏幕上
        screen.blit(backgroud_image, (0, 0))
        pipe_sprites.draw(screen)
        screen.blit(other_images['base'], base_pos)
        showScore(screen, score, number_images)
        bird.draw(screen)
        pygame.display.update()
        clock.tick(cfg.FPS)
    endGame(screen, sounds, showScore, score, number_images, bird, pipe_sprites, backgroud_image, other_images, base_pos, cfg)
'''run'''
if __name__ == '__main__':
    while True:
        main()

三.cfg

'''配置文件'''

import os



# FPS

FPS = 60

# 屏幕

SCREENWIDTH = 288

SCREENHEIGHT = 512

# 管道之间的空隙

PIPE_GAP_SIZE = 100

# 图片

NUMBER_IMAGE_PATHS = {

   '0': os.path.join(os.getcwd(), 'resources/images/0.png'),

   '1': os.path.join(os.getcwd(), 'resources/images/1.png'),

   '2': os.path.join(os.getcwd(), 'resources/images/2.png'),

   '3': os.path.join(os.getcwd(), 'resources/images/3.png'),

   '4': os.path.join(os.getcwd(), 'resources/images/4.png'),

   '5': os.path.join(os.getcwd(), 'resources/images/5.png'),

   '6': os.path.join(os.getcwd(), 'resources/images/6.png'),

   '7': os.path.join(os.getcwd(), 'resources/images/7.png'),

   '8': os.path.join(os.getcwd(), 'resources/images/8.png'),

   '9': os.path.join(os.getcwd(), 'resources/images/9.png')

}

BIRD_IMAGE_PATHS = {

   'red': {

       'up': os.path.join(os.getcwd(), 'resources/images/redbird-upflap.png'),

       'mid': os.path.join(os.getcwd(), 'resources/images/redbird-midflap.png'),

       'down': os.path.join(os.getcwd(), 'resources/images/redbird-downflap.png')

   },

   'blue': {

       'up': os.path.join(os.getcwd(), 'resources/images/bluebird-upflap.png'),

       'mid': os.path.join(os.getcwd(), 'resources/images/bluebird-midflap.png'),

       'down': os.path.join(os.getcwd(), 'resources/images/bluebird-downflap.png')

   },

   'yellow': {

       'up': os.path.join(os.getcwd(), 'resources/images/yellowbird-upflap.png'),

       'mid': os.path.join(os.getcwd(), 'resources/images/yellowbird-midflap.png'),

       'down': os.path.join(os.getcwd(), 'resources/images/yellowbird-downflap.png')

   }

}

BACKGROUND_IMAGE_PATHS = {

   'day': os.path.join(os.getcwd(), 'resources/images/background-day.png'),

   'night': os.path.join(os.getcwd(), 'resources/images/background-night.png')

}

PIPE_IMAGE_PATHS = {

   'green': os.path.join(os.getcwd(), 'resources/images/pipe-green.png'),

   'red': os.path.join(os.getcwd(), 'resources/images/pipe-red.png')

}

OTHER_IMAGE_PATHS = {

   'gameover': os.path.join(os.getcwd(), 'resources/images/gameover.png'),

   'message': os.path.join(os.getcwd(), 'resources/images/message.png'),

   'base': os.path.join(os.getcwd(), 'resources/images/base.png')

}

# 音频路径

AUDIO_PATHS = {

   'die': os.path.join(os.getcwd(), 'resources/audios/die.wav'),

   'hit': os.path.join(os.getcwd(), 'resources/audios/hit.wav'),

   'point': os.path.join(os.getcwd(), 'resources/audios/point.wav'),

   'swoosh': os.path.join(os.getcwd(), 'resources/audios/swoosh.wav'),

   'wing': os.path.join(os.getcwd(), 'resources/audios/wing.wav')

}

四.README


# Introduction

https://mp.weixin.qq.com/s/44CZjwvjnH0kkkKIn5U9Uw


# Environment

```

OS: Windows10

Python: Python3.5+(have installed necessary dependencies)

```


# Usage

```

Step1:

pip install -r requirements.txt

Step2:

run "python Game6.py"

```


# Game Display

![giphy](demonstration/running.gif)


相关文章
|
2天前
|
C++ 开发者 Python
实现Python日志点击跳转到代码位置的方法
本文介绍了如何在Python日志中实现点击跳转到代码位置的功能,以提升调试效率。通过结合`logging`模块的`findCaller()`方法记录代码位置信息,并使用支持点击跳转的日志查看工具(如VS Code、PyCharm),开发者可以从日志直接点击链接定位到出错代码,加快问题排查。
12 2
|
2天前
|
算法 Java 编译器
优化Python代码性能的实用技巧
提高Python代码性能是每个开发者的关注焦点之一。本文将介绍一些实用的技巧和方法,帮助开发者优化他们的Python代码,提升程序的执行效率和性能。
|
2天前
|
Python
Python代码扫描目录下的文件并获取路径
【5月更文挑战第12天】Python代码扫描目录下的文件并获取路径
17 1
|
2天前
|
数据处理 Python
Python 代码中使用。
Python 代码中使用。 z
11 3
|
2天前
|
测试技术 Python
解密Python中的装饰器:提升代码可读性与灵活性
Python中的装饰器是一种强大的工具,能够在不改变原有函数结构的情况下,为函数添加额外功能。本文将深入探讨装饰器的原理及应用,介绍装饰器的基本语法和常见用法,并结合实例演示如何利用装饰器提升代码的可读性和灵活性,使代码更加简洁、模块化和易于维护。
|
2天前
|
监控 Python
Python中的装饰器:提升代码灵活性和可维护性
在Python编程中,装饰器是一种强大的工具,可以提高代码的灵活性和可维护性。本文将深入探讨装饰器的概念、用法和实际应用,帮助读者更好地理解并运用装饰器来优化自己的Python代码。
|
2天前
|
Python
Python中的装饰器:提升代码可读性与复用性
Python中的装饰器是一种强大的工具,能够提升代码的可读性和复用性。本文将深入探讨装饰器的原理、用法以及在实际项目中的应用,帮助读者更好地理解和利用这一特性,提升代码质量和开发效率。
|
编解码 计算机视觉 Python
Python 获取图片某像素BGR值并生成纯色图 | Python工具
Python 获取图片某像素BGR值并生成纯色图 | Python工具
Python 获取图片某像素BGR值并生成纯色图 | Python工具
|
1天前
|
网络协议 Unix Python
Python编程-----网络通信
Python编程-----网络通信
8 1
|
2天前
|
JSON 数据格式 开发者
pip和requests在Python编程中各自扮演着不同的角色
【5月更文挑战第9天】`pip`是Python的包管理器,用于安装、升级和管理PyPI上的包;`requests`是一个HTTP库,简化了HTTP通信,支持各种HTTP请求类型及数据交互。两者在Python环境中分别负责包管理和网络请求。
31 5