python烟花绘制,春节祝福

春节将至,写一个烟花程序给亲近的人
在这里插入图片描述

核心逻辑

烟花类:
定义烟花的颜色,更新烟花的轨迹,爆炸,消失等功能,在烟花爆炸的同时也涉及到粒子的创建

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 particleself.exploded = Falseself.particles = []self.min_max_particles = vector(100, 225)def update(self, win):  # called every frameif 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 = Trueself.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 数量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 Trueelse:return False

粒子类:
定义了粒子的方向,轨迹,颜色,以及粒子的减少过程等

class Particle:def __init__(self, x, y, firework, colour):self.firework = fireworkself.pos = vector(x, y)self.origin = vector(x, y)self.radius = 20self.remove = Falseself.explosion_radius = randint(5, 18)self.life = 0self.acc = vector(0, 0)# trail variablesself.trails = []  # stores the particles trail objectsself.prev_posx = [-10] * 10  # stores the 10 last positionsself.prev_posy = [-10] * 10  # stores the 10 last positionsif self.firework:self.vel = vector(0, -randint(17, 20))self.size = 5self.colour = colourfor 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)# 5 个 tails总计for i in range(5):self.trails.append(Trail(i, self.size, False))def apply_force(self, force):self.acc += forcedef move(self):if not self.firework:self.vel.x *= 0.8self.vel.y *= 0.8self.vel += self.accself.pos += self.velself.acc *= 0if self.life == 0 and not self.firework:  # check if particle is outside explosion radiusdistance = math.sqrt((self.pos.x - self.origin.x) ** 2 + (self.pos.y - self.origin.y) ** 2)if distance > self.explosion_radius:self.remove = Trueself.decay()self.trail_update()self.life += 1def 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 particlesif 50 > self.life > 10:  # early stage their is a small chance of decayran = randint(0, 30)if ran == 0:self.remove = Trueelif self.life > 50:ran = randint(0, 5)if ran == 0:self.remove = Truedef 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 = nself.pos = vector(-10, -10)self.dynamic = dynamicif self.dynamic:self.colour = trail_colours[n]self.size = int(size - n / 2)else:self.colour = (255, 255, 200)self.size = size - 2if self.size < 0:self.size = 0def 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 main():pygame.init()pygame.font.init()pygame.display.set_caption("Fireworks in Pygame")  # 标题background = pygame.image.load("src/1.jpg")  # 背景myfont = pygame.font.Font("src/simkai.ttf", 80)myfont1 = pygame.font.Font("src/simkai.ttf", 30)testsurface = myfont.render("新年快乐", False, (251, 59, 85))testsurface1 = myfont1.render("by:yourname", False, (251, 59, 85))# pygame.image.load("")win = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))# win.blit(background)clock = pygame.time.Clock()fireworks = [Firework() for i in range(2)]  # create the first fireworksrunning = Truewhile running:clock.tick(60)for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseif event.type == pygame.KEYDOWN:  # Change game speed with number keysif event.key == pygame.K_1:  # 按下 1fireworks.append(Firework())if event.key == pygame.K_2:  # 按下 2 加入10个烟花for i in range(10):fireworks.append(Firework())scaled_background = pygame.transform.scale(background, (DISPLAY_WIDTH, DISPLAY_HEIGHT))win.fill((20, 20, 30))  # draw backgroundwin.blit(scaled_background, (0, 0))win.blit(testsurface, (200, 30))win.blit(testsurface1, (520, 80))if randint(0, 20) == 1:  # create new fireworkfireworks.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()

完整代码

import pygame
from random import randint, uniform, choice
import mathvector = pygame.math.Vector2
gravity = vector(0, 0.3)
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600trail_colours = [(45, 45, 45), (60, 60, 60), (75, 75, 75), (125, 125, 125), (150, 150, 150)]
dynamic_offset = 1
static_offset = 3class 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 particleself.exploded = Falseself.particles = []self.min_max_particles = vector(100, 225)def update(self, win):  # called every frameif 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 = Trueself.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 数量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 Trueelse:return Falseclass Particle:def __init__(self, x, y, firework, colour):self.firework = fireworkself.pos = vector(x, y)self.origin = vector(x, y)self.radius = 20self.remove = Falseself.explosion_radius = randint(5, 18)self.life = 0self.acc = vector(0, 0)# trail variablesself.trails = []  # stores the particles trail objectsself.prev_posx = [-10] * 10  # stores the 10 last positionsself.prev_posy = [-10] * 10  # stores the 10 last positionsif self.firework:self.vel = vector(0, -randint(17, 20))self.size = 5self.colour = colourfor 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)# 5 个 tails总计for i in range(5):self.trails.append(Trail(i, self.size, False))def apply_force(self, force):self.acc += forcedef move(self):if not self.firework:self.vel.x *= 0.8self.vel.y *= 0.8self.vel += self.accself.pos += self.velself.acc *= 0if self.life == 0 and not self.firework:  # check if particle is outside explosion radiusdistance = math.sqrt((self.pos.x - self.origin.x) ** 2 + (self.pos.y - self.origin.y) ** 2)if distance > self.explosion_radius:self.remove = Trueself.decay()self.trail_update()self.life += 1def 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 particlesif 50 > self.life > 10:  # early stage their is a small chance of decayran = randint(0, 30)if ran == 0:self.remove = Trueelif self.life > 50:ran = randint(0, 5)if ran == 0:self.remove = Truedef 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 = nself.pos = vector(-10, -10)self.dynamic = dynamicif self.dynamic:self.colour = trail_colours[n]self.size = int(size - n / 2)else:self.colour = (255, 255, 200)self.size = size - 2if self.size < 0:self.size = 0def 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.font.init()pygame.display.set_caption("Fireworks in Pygame")  # 标题background = pygame.image.load("src/1.jpg")  # 背景myfont = pygame.font.Font("src/simkai.ttf", 80)myfont1 = pygame.font.Font("src/simkai.ttf", 30)testsurface = myfont.render("新年快乐", False, (251, 59, 85))testsurface1 = myfont1.render("By:shangyi", False, (251, 59, 85))# pygame.image.load("")win = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))# win.blit(background)clock = pygame.time.Clock()fireworks = [Firework() for i in range(2)]  # create the first fireworksrunning = Truewhile running:clock.tick(60)for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseif event.type == pygame.KEYDOWN:  # Change game speed with number keysif event.key == pygame.K_1:  # 按下 1fireworks.append(Firework())if event.key == pygame.K_2:  # 按下 2 加入10个烟花for i in range(10):fireworks.append(Firework())scaled_background = pygame.transform.scale(background, (DISPLAY_WIDTH, DISPLAY_HEIGHT))win.fill((20, 20, 30))  # draw backgroundwin.blit(scaled_background, (0, 0))win.blit(testsurface, (200, 30))win.blit(testsurface1, (520, 80))if randint(0, 20) == 1:  # create new fireworkfireworks.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.mzph.cn/news/675803.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

数据结构——单向链表和双向链表的实现(C语言版)

目录 前言 1. 链表 1.1 链表的概念及结构 1.2 链表的分类 2. 单链表接口实现 2.1 数据结构设计与接口函数声明 2.2 创建结点&#xff0c;打印&#xff0c;查找 2.3 尾插&#xff0c;头插&#xff0c;尾删&#xff0c;头删 2.4 插入或删除 2.4.1在指定位置后 2.4.2在…

制作二维码扫描器

目录 前言原料主要的库资源其它 制作准备工作界面功能封装扫描二维码扫描复制扫描结果 成果 打包结尾下载链接 本文由Jzwalliser原创&#xff0c;发布在CSDN平台上&#xff0c;遵循CC 4.0 BY-SA协议。 因此&#xff0c;若需转载/引用本文&#xff0c;请注明作者并附原文链接&am…

云卷云舒:论超级数据库、算网数据库、智算数据库

笔者大胆提出一种“超级数据库”的概念设想。 一、超级能力 就像当初提出“超级计算机”一样&#xff0c;我们是否同样可以提出“超级数据库”的概念呢&#xff1f;当然不是不可以。 二、超级计算机 我们回忆一下“超级计算机”的发展之路&#xff0c;大致经过了如下几个环…

C语言之喝汽水问题

个人主页&#xff08;找往期文章包括但不限于本期文章中不懂的知识点&#xff09;&#xff1a; 我要学编程(ಥ_ಥ)-CSDN博客 题目&#xff1a; 喝汽水&#xff0c;1瓶汽水1元&#xff0c;2个空瓶可以换一瓶汽水&#xff0c;给20元&#xff0c;可以喝多少汽水&#xff08;编程实…

ChatGPT 变懒最新解释!或和系统Prompt太长有关

大家好我是二狗。 ChatGPT变懒这件事又有了最新解释了。 这两天&#xff0c;推特用户Dylan Patel发文表示&#xff1a; 你想知道为什么 ChatGPT 和 6 个月前相比会如此糟糕吗&#xff1f; 那是因为ChatGPT系统Prompt是竟然包含1700 tokens&#xff0c;看看这个prompt里面有多…

RabbitMQ-2.SpringAMQP

SpringAMQP 2.SpringAMQP2.1.创建Demo工程2.2.快速入门2.1.1.消息发送2.1.2.消息接收2.1.3.测试 2.3.WorkQueues模型2.2.1.消息发送2.2.2.消息接收2.2.3.测试2.2.4.能者多劳2.2.5.总结 2.4.交换机类型2.5.Fanout交换机2.5.1.声明队列和交换机2.5.2.消息发送2.5.3.消息接收2.5.4…

【Java IO】同步异步和阻塞非阻塞真正的区别!!!

先上结论&#xff1a; 同步异步和阻塞非阻塞真正的区别&#xff01;&#xff01;&#xff01; 假设某个进程正在运行下面这段代码&#xff1a; ...... operatorA......; read(); operatorB......; operatorC......;当进程执行完operatorA后开始进行read系统调用&#xff0c;…

代码随想录 Leetcode376. 摆动序列

题目&#xff1a; 代码&#xff08;首刷看解析 2024年2月9日&#xff09;&#xff1a; class Solution { public:int wiggleMaxLength(vector<int>& nums) {if (nums.size() < 1) return nums.size();int direction 0;//1上升&#xff0c;0下降int res 0;//res…

【Linux】Shell编程

Shell编程 目录 Shell编程1.shell基础1.输入重定向 & 输出重定向2.管道3.特殊字符(3.1)通配符(3.2)引号(3.3)注释符(#) 4.别名5.命令历史history 2.Shell脚本Shell脚本的执行方式(1)为脚本文件加上可执行权限,然后在命令行直接输入shell脚本文件名执行。(2)sh shell脚本名(…

QT基础教程(全系列教程目录)

文章目录 前言一、QT基础教程二、QT进阶教程三、QT高级教程四、QT项目教程 前言 有了C语言全套教学文章和C全套教学文章后&#xff0c;我打算开始完成全套的QT教程文章了&#xff0c;为了方便大家更进一步的提高自己的水平和知识&#xff0c;将学习到的语言运用起来。 "…

接口测试:自动化脚本

接口测试:自动化脚本 接口自动化脚本 为什么要设计自动化脚本&#xff1f; 后台程序更新/发布新版之前需要验证下之前的功能是否能用 自动化脚本设计原则 每个测试用例都是独立的测试用例都是可重复运行的测试数据与业务相分离&#xff08;测试数据包括参数接口数据/ 测试…

STM32控制JQ8400语音播报模块

时间记录&#xff1a;2024/2/7 一、JQ8400引脚介绍 标示说明ONE LINE一线操作引脚BUSY忙信号引脚&#xff0c;正在播放语音时输出高电平RX串口两线操作接收引脚TX串口两线操作发送引脚GND电源地引脚DC-5V电源引脚&#xff0c;3.3-5VDAC-RDAC输出右声道引脚DAC-LDAC输出左声道…

机器学习:分类决策树(Python)

一、各种熵的计算 entropy_utils.py import numpy as np # 数值计算 import math # 标量数据的计算class EntropyUtils:"""决策树中各种熵的计算&#xff0c;包括信息熵、信息增益、信息增益率、基尼指数。统一要求&#xff1a;按照信息增益最大、信息增益率…

mysql8.0 正值表达式Regular expressions (sample database classicmodels _No.5)

mysql8.0 正值表达式Regular expressions 准备工作&#xff0c;可以去下载 classicmodels 数据库资源如下 [ 点击&#xff1a;classicmodels] (https://download.csdn.net/download/tomxjc/88685970) 也可以去我的博客资源下载 https://download.csdn.net/download/tomxjc/8…

第二十六回 母夜叉孟州道卖人肉 武都头十字坡遇张青-Ubuntu 防火墙ufw配置

武松到县里投案&#xff0c;县官看武松是个汉子&#xff0c;就把诉状改成&#xff1a;武松与嫂一时斗殴杀死&#xff0c;后西门庆前来&#xff0c;两人互殴&#xff0c;打死西门庆。上报东平府。东平府尹也可怜武松&#xff0c;从轻发落&#xff0c;最后判了个&#xff1a;脊杖…

一条 SQL 更新语句是如何执行的?

之前你可能经常听 DBA 同事说&#xff0c;MySQL 可以恢复到半个月内任意一秒的状态&#xff0c;惊叹的同时&#xff0c;你是不是心中也会不免会好奇&#xff0c;这是怎样做到的呢&#xff1f; 我们先从一条更新语句讲起&#xff0c;首先创建一个表&#xff0c;这个表有一个主键…

设计模式(创建型模式)原型模式

目录 一、简介二、原型模式2.1、不使用原型模式2.2、使用原型模式&#xff08;浅拷贝&#xff09;2.3、使用原型模式&#xff08;深拷贝&#xff09; 三、原型模式 一、简介 原型模式&#xff08;Prototype Pattern&#xff09; 是一种创建型设计模式&#xff0c;它允许通过复制…

百卓Smart管理平台 uploadfile.php 文件上传漏洞(CVE-2024-0939)

免责声明&#xff1a;文章来源互联网收集整理&#xff0c;请勿利用文章内的相关技术从事非法测试&#xff0c;由于传播、利用此文所提供的信息或者工具而造成的任何直接或者间接的后果及损失&#xff0c;均由使用者本人负责&#xff0c;所产生的一切不良后果与文章作者无关。该…

零基础学Python(9)— 流程控制语句(下)

前言&#xff1a;Hello大家好&#xff0c;我是小哥谈。流程控制语句是编程语言中用于控制程序执行流程的语句&#xff0c;本节课就带大家认识下Python语言中常见的流程控制语句&#xff01;~&#x1f308; 目录 &#x1f680;1.while循环 &#x1f680;2.for循环 &#x1…

re:从0开始的CSS学习之路 8. 浏览器默认样式

1. 默认样式 浏览器会有一个默认样式&#xff0c;body标签会有自带一个8px的margin属性。在布局的时候通常不想要浏览器的默认样式&#xff0c;因此可以先清除一下浏览器提供的默认样式 示例如下&#xff1a; <!DOCTYPE html> <html lang"en"><head…