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;大致经过了如下几个环…

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脚本名(…

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;这个表有一个主键…

百卓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…

RCE(命令执行)知识点总结最详细

description: 这里是CTF做题时常见的会遇见的RCE的漏洞知识点总结。 如果你觉得写得好并且想看更多web知识的话可以去gitbook.22kaka.fun去看&#xff0c;上面是我写的一本关于web学习的一个gitbook&#xff0c;当然如果你能去我的github为我的这个项目点亮星星我会感激不尽htt…

STM32之定时器

一、简介 STM32F4xx系列共有14个定时器&#xff0c;其中2个高级定时器、10个通用定时器、2个基本定时器。下图 为各定时器及其功能。 图1.各定时器及其功能 二、定时器的计数模式 向上计数模式&#xff1a;计数器从0计数到自动加载值(TIMx_ARR)&#xff0c;然后重新从0开始…

17:定时器编程实战

1、实验目的 (1)使用定时器来完成LED闪烁 (2)原来实现闪烁时中间的延迟是用delay函数实现的&#xff0c;在delay的过程中CPU要一直耗在这里不能去做别的事情。这是之前的缺点 (3)本节用定时器来定一个时间&#xff08;譬如0.3s&#xff09;&#xff0c;在这个定时器定时时间内…

抽象springBoot报错

Failed to configure a DataSource: url attribute is not specified and no embedded datasource could be configured. 中文翻译&#xff1a;无法配置DataSource&#xff1a;未指定“url”属性&#xff0c;并且无法配置嵌入数据源。 DataSource 翻译&#xff1a;数据源 得…

The Back-And-Forth Method (BFM) for Wasserstein Gradient Flows windows安装

本文记录了BFM算法代码在windows上的安装过程。 算法原网站&#xff1a;https://wasserstein-gradient-flows.netlify.app/ github&#xff1a;https://github.com/wonjunee/wgfBFMcodes 文章目录 FFTWwgfBFMcodesMATLABpython注 FFTW 官网/下载路径&#xff1a;https://ww…