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

2023-11-02

♥️作者:小刘在这里

♥️每天分享云计算网络运维课堂笔记,努力不一定有回报,但一定会有收获加油!一起努力,共赴美好人生!

♥️夕阳下,是最美的,绽放,愿所有的美好,再疫情结束后如约而至。

目录

一.呈现效果

 二.主代码

三.cfg

四.README


一.呈现效果

 二.主代码

'''
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)

♥️关注,就是我创作的动力

♥️点赞,就是对我最大的认可

♥️这里是小刘,励志用心做好每一篇文章,谢谢大家

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python小游戏——像素鸟代码开源 的相关文章

  • 避免由于相对 URL 导致的错误请求

    我正在尝试使用Scrapy抓取一个网站 并且我想要抓取的每个页面的url都是使用这种相对路径编写的 a href en item to scrap html Link a 现在 在我的浏览器中 这些链接可以工作 您可以访问类似的网址http
  • Tensorflow 可变图像输入大小(自动编码器、放大......)

    Edit WARNING不建议使用不同图像大小的图像 因为张量需要具有相同的大小才能实现并行化 我一直在寻找解决方案 了解如何使用不同大小的图像作为神经网络的输入 Numpy 第一个想法是使用numpy 然而 由于每个图像的大小不同 我无法
  • 优化 Keras 以使用所有可用的 CPU 资源

    好吧 我真的不知道我在说什么 所以请耐心听我说 我正在使用 Theano 后端运行 Keras 以在 MNIST 图像上运行基本的神经网络 目前只是一个教程 过去 我一直使用我的旧 HP 笔记本电脑 因为我有 Windows 和 Ubunt
  • Pandas重置索引未生效[重复]

    这个问题在这里已经有答案了 我不确定我在哪里误入歧途 但我似乎无法重置数据帧上的索引 当我跑步时test head 我得到以下输出 正如您所看到的 数据帧是一个切片 因此索引超出范围 我想做的是重置该数据帧的索引 所以我跑test rese
  • 错误:permission_manager_qt.cpp(82) 不支持的权限类型:13

    我正在开发具有内置浏览器功能的 python 代码 PyQt 5 13 import sys from PyQt5 QtCore import from PyQt5 QtGui import from PyQt5 QtWidgets imp
  • 如果字段值在外部列表中,Django 会注释布尔值

    想象一下我有这个 Django 模型 class Letter models Model name models CharField max length 1 unique True 还有这个列表 vowels a e i o u 我想查询
  • “char”/“character”类型的类型提示

    char 或 character 没有内置的原始类型 因此显然必须使用长度为 1 的字符串 但是为了暗示这一点并暗示它应该被视为一个字符 如何通过类型提示来实现这一点 grade chr A 一种方法可能是使用内置的 chr 函数来表示这一
  • 无法打开 Python。错误 0xc000007b

    我最近一直在学习 Python 3 我在我的上网本 32 位 Windows 7 上创建简单的小程序没有任何问题 当我将它安装在我的上网本上时 我没有遇到任何问题 但现在我已经开始使用它了 我想将它安装在我的台式机上 并且我有一个 我的桌面
  • 创建一个类似于 Tkinter 的表

    我希望创建类似于 Tkinter 中的表格的东西 但它不一定是这样的 例如 我想创建标题 Name1 Name2 Value 并在每个标题下面有几个空白行 然后 我希望稍后用我计算的值或名称的字符串值填充这些行 因此是标签 对于 Name2
  • matplotlib matshow 标签

    我一个月前开始使用 matplotlib 所以我仍在学习 我正在尝试用 matshow 制作热图 我的代码如下 data numpy array a reshape 4 4 cax ax matshow data interpolation
  • 获取列表中倒数第二个元素[重复]

    这个问题在这里已经有答案了 我可以通过以下方式获取列表的倒数第二个元素 gt gt gt lst a b c d e f gt gt gt print lst len lst 2 e 有没有比使用更好的方法print lst len lst
  • Python 中的 @staticmethod 与 @classmethod

    方法和方法有什么区别装饰的 https peps python org pep 0318 with staticmethod http docs python org library functions html staticmethod和
  • 为什么我用 beautifulSoup 刮的时候有桌子,但没有 pandas

    尝试抓取条目页面转换为制表符分隔格式 主要拉出序列和 UniProt 登录号 当我跑步时 url www signalpeptide de index php sess m listspdb bacteria s details id 10
  • select() 可以在 Windows 下使用 Python 中的文件吗?

    我正在尝试在 Windows 下运行以下 python 服务器 An echo server that uses select to handle multiple clients at a time Entering any line o
  • 如何有效地从 loadmat 函数生成的嵌套 numpy 数组中提取值?

    python中是否有更有效的方法从嵌套的python列表中提取数据 例如A array array 12000000 dtype object 我一直在使用A 0 0 0 0 当你有很多像 A 这样的数据时 这似乎不是一个有效的方法 我也用
  • 在 MacO 和 Linux 上安装 win32com [重复]

    这个问题在这里已经有答案了 我的问题很简单 我可以安装吗win32com蟒蛇API pywin32特别是 在非 Windows 操作系统上 我一直在Mac上尝试多个版本pip install pywin32 都失败了 下面是一个例子 如果你
  • Python组合目录中的所有csv文件并按日期时间排序

    我有 2 年的每日数据分成每月文件 我想将所有这些数据合并到一个按日期和时间排序的文件中 我正在使用的代码组合了所有文件 但不按顺序 我正在使用的代码 import pandas as pd import glob os import cs
  • 全局变量是 None 而不是实例 - Python

    我正在处理Python 中的全局变量 代码应该可以正常工作 但是有一个问题 我必须使用全局变量作为类的实例Back 当我运行应用程序时 它说 back is None 这应该不是真的 因为第二行setup 功能 back Back Back
  • TypeError:无法使用抽象方法实例化抽象类 <...>

    这是我的代码 from abc import ABC from abc import abstractmethod class Mamifiero ABC docstring for Mamifiero def init self self
  • 异步和协程与任务队列

    我一直在阅读有关 python 3 中的 asyncio 模块的内容 以及更广泛地了解 python 中的协程的内容 但我不明白是什么让 asyncio 成为如此出色的工具 我的感觉是 你可以用协程做的所有事情 通过使用基于多处理模块 例如

随机推荐