当前位置: 首页 > article >正文

Python项目之Pygame制作新年烟花!

实现源码涉及到两个Python库:random 和 pygame。

1.random库:randint(a, b):返回一个在[a, b]范围内的随机整数。uniform(a, b):返回一个在[a, b]范围内的随机浮点数。choice(sequence):从给定的序列中随机选择一个元素。

2.Pygame是一个用于制作游戏的Python模块,它包含了许多用于游戏开发和图形渲染的功能。以下是Pygame的一些主要功能:

图形绘制:Pygame提供了许多函数来绘制形状、线条和图像,可以用来创建游戏中的场景、角色和道具等。

事件处理:Pygame可以检测和处理用户的输入事件,例如键盘按键、鼠标移动和点击等,使得游戏能够响应用户的操作。

音频和音乐:Pygame支持播放和生成音频和音乐,可以用来添加游戏音效、背景音乐等。

碰撞检测:Pygame提供了一些工具和函数来检测游戏对象之间的碰撞,可以用来实现游戏的物理效果和交互。

精灵和纹理:Pygame使用精灵和纹理来管理游戏中的图像和角色,可以用来创建复杂的游戏对象和场景。

屏幕管理:Pygame可以控制屏幕的分辨率、颜色深度和刷新率等,可以用来优化游戏的显示效果和性能。

游戏逻辑:Pygame提供了一些函数和类来管理游戏的状态和流程,可以用来实现游戏的逻辑和规则。

总的来说,Pygame是一个功能强大的游戏开发模块,它可以用于创建各种类型的游戏,包括动作、冒险、策略和益智等。

↓源码如下↓ 


import math
from random import randint, uniform, choice
import pygame

vector = pygame.math.Vector2
gravity = vector(0, 0.3)
DISPLAY_WIDTH = 1100
DISPLAY_HEIGHT = 700

trail_colours = [(45, 45, 45), (60, 60, 60), (75, 75, 75),
                 (125, 125, 125), (150, 150, 150)]
dynamic_offset = 1
static_offset = 5


class Firework:

    def __init__(self):
        self.colour = (randint(0, 255), randint(0, 255), randint(0, 255))
        self.colours = (
            (randint(0, 255), randint(0, 255), randint(0, 255)
             ), (randint(0, 255), randint(0, 255), randint(0, 255)),
            (randint(0, 255), randint(0, 255), randint(0, 255)))
        self.firework = Particle(randint(0, DISPLAY_WIDTH), DISPLAY_HEIGHT, True,
                                 self.colour)  # Creates the firework particle
        self.exploded = False
        self.particles = []
        self.min_max_particles = vector(100, 225)

    def update(self, win):  # called every frame
        if not self.exploded:
            self.firework.apply_force(gravity)
            self.firework.move()
            for tf in self.firework.trails:
                tf.show(win)

            self.show(win)

            if self.firework.vel.y >= 0:
                self.exploded = True
                self.explode()
        else:
            for particle in self.particles:
                particle.apply_force(
                    vector(gravity.x + uniform(-1, 1) / 20, gravity.y / 2 + (randint(1, 8) / 100)))
                particle.move()
                for t in particle.trails:
                    t.show(win)
                particle.show(win)

    def explode(self):
        amount = randint(self.min_max_particles.x, self.min_max_particles.y)
        for i in range(amount):
            self.particles.append(
                Particle(self.firework.pos.x, self.firework.pos.y, False, self.colours))

    def show(self, win):
        pygame.draw.circle(win, self.colour, (int(self.firework.pos.x), int(
            self.firework.pos.y)), self.firework.size)

    def remove(self):
        if self.exploded:
            for p in self.particles:
                if p.remove is True:
                    self.particles.remove(p)

            if len(self.particles) == 0:
                return True
            else:
                return False


class Particle:

    def __init__(self, x, y, firework, colour):
        self.firework = firework
        self.pos = vector(x, y)
        self.origin = vector(x, y)
        self.radius = 20
        self.remove = False
        self.explosion_radius = randint(5, 18)
        self.life = 0
        self.acc = vector(0, 0)
        # trail variables
        self.trails = []  # stores the particles trail objects
        self.prev_posx = [-10] * 10  # stores the 10 last positions
        self.prev_posy = [-10] * 10  # stores the 10 last positions

        if self.firework:
            self.vel = vector(0, -randint(17, 20))
            self.size = 5
            self.colour = colour
            for i in range(5):
                self.trails.append(Trail(i, self.size, True))
        else:
            self.vel = vector(uniform(-1, 1), uniform(-1, 1))
            self.vel.x *= randint(7, self.explosion_radius + 2)
            self.vel.y *= randint(7, self.explosion_radius + 2)
            self.size = randint(2, 4)
            self.colour = choice(colour)
            for i in range(5):
                self.trails.append(Trail(i, self.size, False))

    def apply_force(self, force):
        self.acc += force

    def move(self):
        if not self.firework:
            self.vel.x *= 0.8
            self.vel.y *= 0.8

        self.vel += self.acc
        self.pos += self.vel
        self.acc *= 0

        if self.life == 0 and not self.firework:  # check if particle is outside explosion radius
            distance = math.sqrt((self.pos.x - self.origin.x)
                                 ** 2 + (self.pos.y - self.origin.y) ** 2)
            if distance > self.explosion_radius:
                self.remove = True

        self.decay()

        self.trail_update()

        self.life += 1

    def show(self, win):
        pygame.draw.circle(win, (self.colour[0], self.colour[1], self.colour[2], 0), (int(self.pos.x), int(self.pos.y)),
                           self.size)

    def decay(self):  # random decay of the particles
        if 50 > self.life > 10:  # early stage their is a small chance of decay
            ran = randint(0, 30)
            if ran == 0:
                self.remove = True
        elif self.life > 50:
            ran = randint(0, 5)
            if ran == 0:
                self.remove = True

    def trail_update(self):
        self.prev_posx.pop()
        self.prev_posx.insert(0, int(self.pos.x))
        self.prev_posy.pop()
        self.prev_posy.insert(0, int(self.pos.y))

        for n, t in enumerate(self.trails):
            if t.dynamic:
                t.get_pos(self.prev_posx[n + dynamic_offset],
                          self.prev_posy[n + dynamic_offset])
            else:
                t.get_pos(self.prev_posx[n + static_offset],
                          self.prev_posy[n + static_offset])


class Trail:

    def __init__(self, n, size, dynamic):
        self.pos_in_line = n
        self.pos = vector(-10, -10)
        self.dynamic = dynamic

        if self.dynamic:
            self.colour = trail_colours[n]
            self.size = int(size - n / 2)
        else:
            self.colour = (255, 255, 200)
            self.size = size - 2
            if self.size < 0:
                self.size = 0

    def get_pos(self, x, y):
        self.pos = vector(x, y)

    def show(self, win):
        pygame.draw.circle(win, self.colour, (int(
            self.pos.x), int(self.pos.y)), self.size)


def update(win, fireworks):
    for fw in fireworks:
        fw.update(win)
        if fw.remove():
            fireworks.remove(fw)

    pygame.display.update()

# 主函数
def main():
    pygame.init()
    pygame.display.set_caption('2024新年快乐')
    win = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
    myfont = pygame.font.Font('C:\Windows\Fonts\simkai.ttf', 80)
    text = myfont.render('2024新年快乐', False, (255, 0, 0))
    # 将文字绘制到屏幕上
    win.blit(text, (100, 100))
    pygame.display.flip()
    clock = pygame.time.Clock()
    fireworks = [Firework() for i in range(3)]  # create the first fireworks
    running = True

    while running:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == pygame.KEYDOWN:
            # Change game speed with number keys
                if event.key == pygame.K_1:
                    fireworks.append(Firework())
                if event.key == pygame.K_2:
                    for i in range(10):
                        fireworks.append(Firework())
        win.fill((20, 20, 30))  # draw background

        if randint(0, 20) == 1:  # create new firework
            fireworks.append(Firework())

        update(win, fireworks)

        # stats for fun
        # total_particles = 0
        # for f in fireworks:
        #    total_particles += len(f.particles)

        # print(f"Fireworks: {len(fireworks)}\nParticles: {total_particles}\n\n")

    pygame.quit()
    quit()


main()


http://www.kler.cn/a/450640.html

相关文章:

  • Spring AOP 中记录日志
  • windows下安装配置anaconda及常用的conda命令
  • C/C++基础错题归纳
  • java web springboot
  • 【杂谈】-为什么Python是AI的首选语言
  • 前端开发 之 12个鼠标交互特效上【附完整源码】
  • 【从零开始入门unity游戏开发之——unity篇02】unity6基础入门——软件下载安装、Unity Hub配置、安装unity编辑器、许可证管理
  • Vue 3 和 Vue Router 使用 createWebHistory 配置
  • WebGL 项目外包开发流程
  • 告别卡顿:CasaOS轻NAS设备安装Gopeed打造高效下载环境
  • 四种电子杂志制作软件
  • MySQL -函数和约束
  • VS2022 中的 /MT /MTd /MD /MDd 选项
  • 分布式事务的解决方案(欢迎讨论~)
  • springboot启动不了 因一个spring-boot-starter-web底下的tomcat-embed-core依赖丢失
  • 机器学习-KMeans聚类
  • clickhouse分布式表插入数据不用带ON CLUSTER
  • SpringBoot状态机
  • Xilinx 平台 drp 动态调节 mmcm
  • python基础知识(六)
  • 【day15】String常用API
  • 【论文阅读笔记】Learning to sample
  • 数据结构经典算法总复习(上卷)
  • redis延迟队列
  • 云边端一体化架构
  • pyinstaller打包资源文件和ini配置文件怎么放