python实现烟花小程序


Posted in Python onJanuary 30, 2019

本文实例为大家分享了python实现烟花小程序的具体代码,供大家参考,具体内容如下

'''
FIREWORKS SIMULATION WITH TKINTER
*self-containing code
*to run: simply type python simple.py in your console
*compatible with both Python 2 and Python 3
*Dependencies: tkinter, Pillow (only for background image)
*The design is based on high school physics, with some small twists only for aesthetics purpose
 
import tkinter as tk
#from tkinter import messagebox
#from tkinter import PhotoImage
from PIL import Image, ImageTk
from time import time, sleep
from random import choice, uniform, randint
from math import sin, cos, radians
# gravity, act as our constant g, you can experiment by changing it
GRAVITY = 0.05
# list of color, can choose randomly or use as a queue (FIFO)
colors = ['red', 'blue', 'yellow', 'white', 'green', 'orange', 'purple', 'seagreen','indigo', 'cornflowerblue']
Generic class for particles
particles are emitted almost randomly on the sky, forming a round of circle (a star) before falling and getting removed
from canvas
Attributes:
 - id: identifier of a particular particle in a star
 - x, y: x,y-coordinate of a star (point of explosion)
 - vx, vy: speed of particle in x, y coordinate
 - total: total number of particle in a star
 - age: how long has the particle last on canvas
 - color: self-explantory
 - cv: canvas
 - lifespan: how long a particle will last on canvas
class part:
 def __init__(self, cv, idx, total, explosion_speed, x=0., y=0., vx = 0., vy = 0., size=2., color = 'red', lifespan = 2, **kwargs):
  self.id = idx
  self.x = x
  self.y = y
  self.initial_speed = explosion_speed
  self.vx = vx
  self.vy = vy
  self.total = total
  self.age = 0
  self.color = color
  self.cv = cv
  self.cid = self.cv.create_oval(
   x - size, y - size, x + size,
   y + size, fill=self.color)
  self.lifespan = lifespan
 def update(self, dt):
  self.age += dt
  # particle expansions
  if self.alive() and self.expand():
   move_x = cos(radians(self.id*360/self.total))*self.initial_speed
   move_y = sin(radians(self.id*360/self.total))*self.initial_speed
   self.cv.move(self.cid, move_x, move_y)
   self.vx = move_x/(float(dt)*1000)
  # falling down in projectile motion
  elif self.alive():
   move_x = cos(radians(self.id*360/self.total))
   # we technically don't need to update x, y because move will do the job
   self.cv.move(self.cid, self.vx + move_x, self.vy+GRAVITY*dt)
   self.vy += GRAVITY*dt
  # remove article if it is over the lifespan
  elif self.cid is not None:
   cv.delete(self.cid)
   self.cid = None
 # define time frame for expansion
 def expand (self):
  return self.age <= 1.2
 # check if particle is still alive in lifespan
 def alive(self):
  return self.age <= self.lifespan
Firework simulation loop:
Recursively call to repeatedly emit new fireworks on canvas
a list of list (list of stars, each of which is a list of particles)
is created and drawn on canvas at every call, 
via update protocol inside each 'part' object 
def simulate(cv):
 t = time()
 explode_points = []
 wait_time = randint(10,100)
 numb_explode = randint(6,10)
 # create list of list of all particles in all simultaneous explosion
 for point in range(numb_explode):
  objects = []
  x_cordi = randint(50,550)
  y_cordi = randint(50, 150)
  speed = uniform (0.5, 1.5)   
  size = uniform (0.5,3)
  color = choice(colors)
  explosion_speed = uniform(0.2, 1)
  total_particles = randint(10,50)
  for i in range(1,total_particles):
   r = part(cv, idx = i, total = total_particles, explosion_speed = explosion_speed, x = x_cordi, y = y_cordi, 
    vx = speed, vy = speed, color=color, size = size, lifespan = uniform(0.6,1.75))
   objects.append(r)
  explode_points.append(objects)
 total_time = .0
 # keeps undate within a timeframe of 1.8 second
 while total_time < 1.8:
  sleep(0.01)
  tnew = time()
  t, dt = tnew, tnew - t
  for point in explode_points:
   for item in point:
    item.update(dt)
  cv.update()
  total_time += dt
 # recursive call to continue adding new explosion on canvas
 root.after(wait_time, simulate, cv)
def close(*ignore):
 """Stops simulation loop and closes the window."""
 global root
 root.quit()
 
if __name__ == '__main__':
 root = tk.Tk()
 cv = tk.Canvas(root, height=600, width=600)
 # use a nice background image
 image = Image.open("./image1.jpg")#背景照片路径自行选择,可以选择酷炫一点的,看起来效果会#更好
 photo = ImageTk.PhotoImage(image)
 cv.create_image(0, 0, image=photo, anchor='nw')
 cv.pack()
 root.protocol("WM_DELETE_WINDOW", close)
 root.after(100, simulate, cv)
 root.mainloop()

注意:这里需要安装tkinter,安装过程:

step1:

>>> import _tkinter # with underscore, and lowercase 't'

step2:

>>> import Tkinter # no underscore, uppercase 'T' for versions prior to V3.0

>>> import tkinter # no underscore, lowercase 't' for V3.0 and later

step3:

>>> Tkinter._test() # note underscore in _test and uppercase 'T' for versions prior to V3.0 

>>> tkinter._test() # note underscore in _test and lowercase 'T' for V3.0 and later

然后就可以运行了,在代码中有一个背景照片部分,路径可自行选择!我这里就不修改了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python 元类使用说明
Dec 18 Python
python实现识别手写数字 python图像识别算法
Mar 23 Python
Python RabbitMQ消息队列实现rpc
May 30 Python
利用python库在局域网内传输文件的方法
Jun 04 Python
基于numpy中数组元素的切片复制方法
Nov 15 Python
python使用xlrd模块读取xlsx文件中的ip方法
Jan 11 Python
python判断字符串或者集合是否为空的实例
Jan 23 Python
Python基础之循环语句用法示例【for、while循环】
Mar 23 Python
在pytorch中为Module和Tensor指定GPU的例子
Aug 19 Python
Python 如何提高元组的可读性
Aug 26 Python
Python 爬取必应壁纸的实例讲解
Feb 24 Python
使用Python将语音转换为文本的方法
Aug 10 Python
Python面向对象程序设计示例小结
Jan 30 #Python
python实现浪漫的烟花秀
Jan 30 #Python
新年快乐! python实现绚烂的烟花绽放效果
Jan 30 #Python
python+selenium 定位到元素,无法点击的解决方法
Jan 30 #Python
解决Python selenium get页面很慢时的问题
Jan 30 #Python
对python实现模板生成脚本的方法详解
Jan 30 #Python
ActiveMQ:使用Python访问ActiveMQ的方法
Jan 30 #Python
You might like
从PHP $_SERVER相关参数判断是否支持Rewrite模块
2013/09/26 PHP
图文详解PHP环境搭建教程
2016/07/16 PHP
php封装的验证码工具类完整实例
2016/10/19 PHP
PHP仿微信发红包领红包效果
2016/10/30 PHP
PHP程序守护进程化实现方法详解
2020/07/16 PHP
PHPStorm2020.1永久激活及下载更新至2020(推荐)
2020/09/25 PHP
Date对象格式化函数代码
2010/07/17 Javascript
在Node.js中实现文件复制的方法和实例
2014/06/05 Javascript
JavaScript实现网页对象拖放功能的方法
2015/04/15 Javascript
jquery+css实现的红色线条横向二级菜单效果
2015/08/22 Javascript
javascript中的previousSibling和nextSibling的正确用法
2015/09/16 Javascript
javascript中活灵活现的Array对象详解
2016/11/30 Javascript
微信小程序 刷新上拉下拉不会断详细介绍
2017/05/11 Javascript
基于pako.js实现gzip的压缩和解压功能示例
2017/06/13 Javascript
vue router自动判断左右翻页转场动画效果
2017/10/10 Javascript
用JavaScript做简易的购物车的代码示例
2017/10/20 Javascript
vue+element实现批量删除功能的示例
2018/02/28 Javascript
Vue使用axios出现options请求方法
2019/05/30 Javascript
[02:11]完美世界DOTA2联赛10月28日赛事精彩集锦:来吧展示实力强劲
2020/10/29 DOTA
Python实现KNN邻近算法
2021/01/28 Python
python验证码识别教程之滑动验证码
2018/06/04 Python
Python minidom模块用法示例【DOM写入和解析XML】
2019/03/25 Python
tensorflow 环境变量设置方式
2020/02/06 Python
计算Python Numpy向量之间的欧氏距离实例
2020/05/22 Python
Python中内建模块collections如何使用
2020/05/27 Python
python实现mask矩阵示例(根据列表所给元素)
2020/07/30 Python
HTML5 video 上传预览图片视频如何设置、预览视频某秒的海报帧
2018/08/28 HTML / CSS
HTML5 通过Vedio标签实现视频循环播放的示例代码
2020/08/05 HTML / CSS
百丽国际旗下购物网站:优购
2017/02/28 全球购物
新学期校长寄语
2014/01/18 职场文书
教师节宣传方案
2014/05/23 职场文书
预备党员群众路线教育实践活动思想汇报2014
2014/10/25 职场文书
第28个世界无烟日活动总结
2015/02/10 职场文书
公司员工离职感言
2015/08/03 职场文书
解决golang 关于全局变量的坑
2021/05/06 Golang
一篇文章带你掌握SQLite3基本用法
2022/06/14 数据库