基于Python记录一场2023的烟花
作者:Leleprogrammer 发布时间:2022-01-08 19:57:07
弹指间,2023已经到来,新的一年,祝大家新年快乐,阖家幸福呀~~~
好吧,进入正题,2023的到来,肯定少不了烟花吧(外面不让放炮,那咱们就用python放炮【DOGE】)
首先,需要的外置库:pygame,pymunk
导入
import pygame
from pygame.locals import *
import pymunk
from pymunk import pygame_util
import sys
import random as rd
import time
import math
然后写一个主程序类,对pygame进行初始化,设置屏幕宽高,设置标题,创建pymunk空间,然后设置空间的重力为(0,300),然后设置collision_persistence参数为0,表示没有碰撞,毕竟俩烟花也不会撞一起......然后设置烟花半径(可以自行修改),创建两个列表,用于存放烟花 * 形成的火球和发射到天空中还没 * 的烟花,创建一个colors列表,存放烟花的颜色
class Firework:
def __init__(self):
pygame.init()
self.W,self.H=800,1000
self.screen=pygame.display.set_mode((self.W,self.H))
self.draw_options=pygame_util.DrawOptions(self.screen)
pygame.display.set_caption("2023元旦烟花")
self.space=pymunk.Space()
self.space.gravity=(0,300)
self.space.collision_persistence=0
self.fireball_radius=2
self.fire_radius=2
self.fireballs=[]
self.colors=[
(255,0,0),(255,127,80),(255,140,0),(255,160,122),(240,128,128),(255,99,71),(255,69,0),
(255,105,180),(255,20,147),(208,32,144),(176,48,96),(153,50,204),(255,48,48),
(238,44,44),(205,38,38),(255,255,0),(255,215,0),(255,185,15),(238,201,0),
(34,139,34),(46,139,87),(60,179,113),(0,255,127)
]
self.fires=[]
接下来,进行事件监听,按下鼠标就可以创建火球
def listen(self):
for event in pygame.event.get():
if event.type==QUIT:
sys.exit()
if event.type==MOUSEBUTTONDOWN:
self.create_firework(x=pygame.mouse.get_pos()[0])
然后写个创建烟花的方法,首先要有个body,设置body_type为DYNAMIC,因为烟花是动态的。然后设置body的位置,x坐标为传参的x坐标,y坐标为屏幕最底部,接下来创建一个shape,形状为circle,body对应的fireball_body传进去就好了,然后设置radius(半径),设置shape的弹性(这个不设置也可以,没多大影响),将body和shape添加到空间中,用add添加,然后将烟花对应的shape对象、颜色、创建时间、 * 前持续时间这四个参数归在一个列表,将这个列表添加到fireballs中,最后就是要赋予body冲击力了,使用apply_impulse_at_local_point方法
def create_firework(self,x):
fireball_body=pymunk.Body(mass=1,moment=100,body_type=pymunk.Body.DYNAMIC)
fireball_body.position=x,self.H
fireball_shape=pymunk.Circle(fireball_body,self.fireball_radius)
fireball_shape.elasticity=0.5
self.space.add(fireball_body,fireball_shape)
self.fireballs.append([fireball_shape,rd.choice(self.colors),time.time(),rd.uniform(1,2.2)]) # shape,color,startTime,lastTime
fireball_body.apply_impulse_at_local_point((0,rd.randint(-730,-500)),(0,0))
然后是draw的代码(比较多),先是填充背景为黑色,然后使用while循环遍历fireballs,将烟花绘制出来,检查是否到达了 * 时间,如果已经到达 * 时间,那么将这个火球从烟花的列表中删掉。接下来就要创建炸开来的火花,火花是向不同方向散开的,所以用for循环遍历一圈的度数,每隔10°就有一个,length是斜边长度,然后定义bias偏移量,因为火花散发力量和距离并不是固定的,所以每一次length都会浮动一点,但始终控制在25~100之间(maximum和minimum),因为apply_impulse_at_local_point发射出去时传参是x轴的力量和y轴的力量,所以要使用三角函数计算临边和对边的长度从而得到apply_impulse_at_local_point传参的数值,又因为我们遍历的是度数(degree),sin和cos计算的是弧度(radians),所以要先把度数通过math.radians转化为弧度,再传参到sin和cos中。计算出来之后,还是创建body和shape并设置一些基本的参数,添加到空间中,并添加到fires列表中,最后删除已 * 的烟花,别忘了变量i需要减1。
上面是对未 * 的烟花进行遍历,下面我们还需要对 * 后形成的火花进行遍历,如果超出范围或已到达删除时间就进行删除的操作,逻辑差不多
draw的代码如下
def draw(self):
self.screen.fill((0,0,0))
i=0
while i<len(self.fireballs):
fireball,color,startTime,lastTime=self.fireballs[i]
pygame.draw.circle(self.screen,color,fireball.body.position,self.fireball_radius)
nowTime=time.time()
boomTime=startTime+lastTime
if nowTime>boomTime:
popball=self.fireballs.pop(i)
length=50
for degree in range(90,450,10):
bias=1
length+=rd.randint(-bias,bias)
maximum,minimum=100,25
if length>maximum:
length=maximum
elif length<minimum:
length=minimum
radians=math.radians(degree)
x_force=math.sin(radians)*length
y_force=math.cos(radians)*length
body=pymunk.Body(mass=1,moment=100,body_type=pymunk.Body.DYNAMIC)
body.position=popball[0].body.position
shape=pymunk.Circle(body,self.fire_radius)
self.space.add(body,shape)
self.fires.append([shape,popball[1],time.time(),rd.uniform(0.5,1.5)]) # shape,color,startTime,lastTime
body.apply_impulse_at_local_point((x_force,y_force),(0,0))
self.space.remove(popball[0])
i-=1
i+=1
i=0
while i<len(self.fires):
fire,color,startTime,lastTime=self.fires[i]
pos=fire.body.position
pygame.draw.circle(self.screen,color,pos,self.fire_radius)
nowTime=time.time()
deleteTime=startTime+lastTime
if nowTime>deleteTime:
self.fires.pop(i)
self.space.remove(fire)
i-=1
elif pos[0]<0 or pos[0]>self.W or pos[1]>self.H:
self.fires.pop(i)
self.space.remove(fire)
i-=1
i+=1
写到这儿,我们的烟花就差不多完成了,最后写个run
def run(self):
clock=pygame.time.Clock()
FPS=60
while True:
clock.tick(FPS)
self.listen()
self.draw()
self.space.step(1/FPS)
pygame.display.update()
运行
if __name__=="__main__":
firework=Firework()
firework.run()
这样就好啦!
最终代码
import pygame
from pygame.locals import *
import pymunk
from pymunk import pygame_util
import sys
import random as rd
import time
import math
class Firework:
def __init__(self):
pygame.init()
self.W,self.H=800,1000
self.screen=pygame.display.set_mode((self.W,self.H))
self.draw_options=pygame_util.DrawOptions(self.screen)
pygame.display.set_caption("2023元旦烟花")
self.space=pymunk.Space()
self.space.gravity=(0,300)
self.space.collision_persistence=0
self.fireball_radius=2
self.fire_radius=2
self.fireballs=[]
self.colors=[
(255,0,0),(255,127,80),(255,140,0),(255,160,122),(240,128,128),(255,99,71),(255,69,0),
(255,105,180),(255,20,147),(208,32,144),(176,48,96),(153,50,204),(255,48,48),
(238,44,44),(205,38,38),(255,255,0),(255,215,0),(255,185,15),(238,201,0),
(34,139,34),(46,139,87),(60,179,113),(0,255,127)
]
self.fires=[]
def listen(self):
for event in pygame.event.get():
if event.type==QUIT:
sys.exit()
if event.type==MOUSEBUTTONDOWN:
self.create_firework(x=pygame.mouse.get_pos()[0])
def create_firework(self,x):
fireball_body=pymunk.Body(mass=1,moment=100,body_type=pymunk.Body.DYNAMIC)
fireball_body.position=x,self.H
fireball_shape=pymunk.Circle(fireball_body,self.fireball_radius)
fireball_shape.elasticity=0.5
self.space.add(fireball_body,fireball_shape)
self.fireballs.append([fireball_shape,rd.choice(self.colors),time.time(),rd.uniform(1,2.2)]) # shape,color,startTime,lastTime
fireball_body.apply_impulse_at_local_point((0,rd.randint(-730,-500)),(0,0))
def draw(self):
self.screen.fill((0,0,0))
i=0
while i<len(self.fireballs):
fireball,color,startTime,lastTime=self.fireballs[i]
pygame.draw.circle(self.screen,color,fireball.body.position,self.fireball_radius)
nowTime=time.time()
boomTime=startTime+lastTime
if nowTime>boomTime:
popball=self.fireballs.pop(i)
length=50
for degree in range(90,450,10):
bias=1
length+=rd.randint(-bias,bias)
maximum,minimum=100,25
if length>maximum:
length=maximum
elif length<minimum:
length=minimum
radians=math.radians(degree)
x_force=math.sin(radians)*length
y_force=math.cos(radians)*length
body=pymunk.Body(mass=1,moment=100,body_type=pymunk.Body.DYNAMIC)
body.position=popball[0].body.position
shape=pymunk.Circle(body,self.fire_radius)
self.space.add(body,shape)
self.fires.append([shape,popball[1],time.time(),rd.uniform(0.5,1.5)]) # shape,color,startTime,lastTime
body.apply_impulse_at_local_point((x_force,y_force),(0,0))
self.space.remove(popball[0])
i-=1
i+=1
i=0
while i<len(self.fires):
fire,color,startTime,lastTime=self.fires[i]
pos=fire.body.position
pygame.draw.circle(self.screen,color,pos,self.fire_radius)
nowTime=time.time()
deleteTime=startTime+lastTime
if nowTime>deleteTime:
self.fires.pop(i)
self.space.remove(fire)
i-=1
elif pos[0]<0 or pos[0]>self.W or pos[1]>self.H:
self.fires.pop(i)
self.space.remove(fire)
i-=1
i+=1
def run(self):
clock=pygame.time.Clock()
FPS=60
while True:
clock.tick(FPS)
self.listen()
self.draw()
self.space.step(1/FPS)
pygame.display.update()
if __name__=="__main__":
firework=Firework()
firework.run()
此时我仿佛听见你说:一直按鼠标手好酸啊!
那没事,我们改成自动就好啦!
只需要修改一部分内容就好
首先需要一个自定义事件(全局变量)
CREATE_FIREBALL=USEREVENT+1
run中while循环前添加这一行,用来启动事件循环,第二个参数是间隔时间,单位是毫秒,可以自己修改
pygame.time.set_timer(CREATE_FIREBALL,120)
将listen改成这样
def listen(self):
for event in pygame.event.get():
if event.type==QUIT:
sys.exit()
if event.type==CREATE_FIREBALL:
self.create_firework(x=rd.randint(0,self.W))
这样就大功告成啦!
来源:https://blog.csdn.net/leleprogrammer/article/details/128510460
猜你喜欢
- 随机从列表中取出元素:import randomdataSet = [[0], [1], [2], [3], [4], [5], [6],
- 我生平不爱学习,所以说不出什么洋洋洒洒的大道理,貌似也写不出妙语连珠的学术文章,有感于现在宅到极致的生活状态,故一篇图文并茂的文章诞生了(大
- 本文实例讲述了python网络编程之读取网站根目录的方法,分享给大家供大家参考。具体实现方法如下:import socket, sys po
- 本文教大家调用电脑摄像头进行实时人脸+眼睛识别+微笑识别,供大家参考,具体内容如下一、调用电脑摄像头进行实时人脸+眼睛识别# 调用电脑摄像头
- 序列的逆序方式1. range 函数一般 for 循环中总会用到 range 函数来进行顺序遍历,同样的,range 也能表示序列的逆序。在
- 1.能调用方法的一定是对象,比如数值、字符串、列表、元组、字典,甚至文件也是对象,Python中一切皆为对象。 str1 = 'he
- 1、使用基础Python代码来读写和处理CSV文件import sys#使用基础Python代码来读写和处理CSV文件input_file
- 利用pymongo包进行数据库的连接,使用xlrd包读取excel数据,由于二者数据结构的不同,要将excel格式数据转换为json格式数据
- 前几天安装了dedecms系统,当在后台安全退出的时候,后台出现空白,先前只分析其他功能去了,也没太注意安全,看了一下安全退出的代码,是这样
- 上一次,我们谈到在ASP中如何利用“正则表达式”对象来实现各种数据的校验,文中描述了正则表达式对象的强大功能,接下来,我们来看看有关“正则表
- 工作时需要取得MySQL中一个表的字段是否存在于是就使用Describe命令来判断mysql_connect(localhost, root
- 利用zipfile模块和pandas获取数据,代码比较简单,做个记录吧:# -*- coding: utf-8 -*-""
- 1. Numpy(Numberical Python)Anaconda中已经集成了NumPy,可以直接使用。如果想要自行安装的话,可以使用流
- 1. 概述JSON (JavaScript Object Notation)是一种使用广泛的轻量数据格式. Python标准库中的json模
- 这几天一直困惑我的问题,我觉得pycharm应该也是有的啊,偶然间找到了这个。把那个框里的选中,就可以了。ps:我的是 PyCharm 20
- 一、基本概述目前电脑上已经下载了MongoDB数据库、navicat for mongodb作为mongoDB的可视化工具,形如navica
- 4. 生成器(generator)4.1. 生成器简介首先请确信,生成器就是一种迭代器。生成器拥有next方法并且行为与迭代器完全相同,这意
- python3 在服务器上打印资产信息pip3 install prettytableurl 为 资产信息接口地址,返回为json信息。#
- <!doctype><html><head><title>新闻图片轮换类</title
- 字符串是不可变类型,可以重新赋值,但不可以索引改变其中一个值,只能拼接字符串建立新变量索引和切片索引:越界会报错切片:越界会自动修改不包含右