当前位置:   article > 正文

2021烟花-新年快乐-Python_用python 新年快乐代码

用python 新年快乐代码

目录

前言

一.知识介绍

二.完整代码

三 参考文献


前言

昨天微信更新了版本,增加了烟花的表情,有XM同学提出建议,运用python编程实现烟花的效果。正值2021春节到来之际,祝大家2021春节愉快,祝我们的祖国繁荣昌盛!

Gif制作:https://en.softonic.com/best/free-to-play-games/?utm_source=wakeup

 

一.知识介绍

1.tkinter:这个小项目的主角,是一个python图形模块。且Python3已经自带了该模块,不用另外安装。它有点像java中的swing图形模块(由众多组件集成,组件通过创建实例添加,组件通过坐标定位在窗口上)。

2.PIL:Python Imaging Library,是Python平台的图像处理标准模块。在Python3也是自带的,在这个项目中用于背景图片的导入。

3.time:相信这个模块大家都不会陌生,导入它用来控制烟花的绽放,坠落及消失时间。

4.random:随机数模块,用于生成烟花随机坐标点,随机绽放速度,随机消失时间。

5.math:这个模块大家应该也很熟悉了,导入它的目的是使烟花绽放的粒子以一定角度散开。

二.完整代码

  1. # -*- coding: utf-8 -*-
  2. """
  3. Spyder Editor
  4. This is a temporary script file.
  5. """
  6. '''
  7. FIREWORKS SIMULATION WITH TKINTER
  8. *self-containing code
  9. *to run: simply type python simple.py in your console
  10. *compatible with both Python 2 and Python 3
  11. *Dependencies: tkinter, Pillow (only for background image)
  12. *The design is based on high school physics, with some small twists only for aesthetics purpose
  13. '''
  14. import tkinter as tk
  15. # from tkinter import messagebox
  16. # from tkinter import PhotoImage
  17. from PIL import Image, ImageTk ,ImageDraw
  18. from time import time, sleep
  19. from random import choice, uniform, randint
  20. from math import sin, cos, radians
  21. from PIL import ImageFont
  22. # gravity, act as our constant g, you can experiment by changing it
  23. GRAVITY = 0.05
  24. # list of color, can choose randomly or use as a queue (FIFO)
  25. colors = ['red', 'blue', 'yellow', 'white', 'green', 'orange', 'purple',
  26. 'red', 'blue', 'yellow', 'white', 'green', 'orange', 'purple','seagreen', 'indigo', 'cornflowerblue']
  27. '''
  28. Generic class for particles
  29. particles are emitted almost randomly on the sky, forming a round of circle (a star) before falling and getting removed
  30. from canvas
  31. Attributes:
  32. - id: identifier of a particular particle in a star
  33. - x, y: x,y-coordinate of a star (point of explosion)
  34. - vx, vy: speed of particle in x, y coordinate
  35. - total: total number of particle in a star
  36. - age: how long has the particle last on canvas
  37. - color: self-explantory
  38. - cv: canvas
  39. - lifespan: how long a particle will last on canvas
  40. '''
  41. class part:
  42. def __init__(self, cv, idx, total, explosion_speed, x=0., y=0., vx=0., vy=0., size=2., color='red', lifespan=2,
  43. **kwargs):
  44. self.id = idx
  45. self.x = x
  46. self.y = y
  47. self.initial_speed = explosion_speed
  48. self.vx = vx
  49. self.vy = vy
  50. self.total = total
  51. self.age = 0
  52. self.color = color
  53. self.cv = cv
  54. self.cid = self.cv.create_oval(
  55. x - size, y - size, x + size,
  56. y + size, fill=self.color)
  57. self.lifespan = lifespan
  58. def update(self, dt):
  59. self.age += dt
  60. # particle expansions
  61. if self.alive() and self.expand():
  62. move_x = cos(radians(self.id * 360 / self.total)) * self.initial_speed
  63. move_y = sin(radians(self.id * 360 / self.total)) * self.initial_speed
  64. self.cv.move(self.cid, move_x, move_y)
  65. self.vx = move_x / (float(dt) * 1000)
  66. # falling down in projectile motion
  67. elif self.alive():
  68. move_x = cos(radians(self.id * 360 / self.total))
  69. # we technically don't need to update x, y because move will do the job
  70. self.cv.move(self.cid, self.vx + move_x, self.vy + GRAVITY * dt)
  71. self.vy += GRAVITY * dt
  72. # remove article if it is over the lifespan
  73. elif self.cid is not None:
  74. cv.delete(self.cid)
  75. self.cid = None
  76. # define time frame for expansion
  77. def expand(self):
  78. return self.age <= 1.2
  79. # check if particle is still alive in lifespan
  80. def alive(self):
  81. return self.age <= self.lifespan
  82. '''
  83. Firework simulation loop:
  84. Recursively call to repeatedly emit new fireworks on canvas
  85. a list of list (list of stars, each of which is a list of particles)
  86. is created and drawn on canvas at every call,
  87. via update protocol inside each 'part' object
  88. '''
  89. def simulate(cv):
  90. t = time()
  91. explode_points = []
  92. wait_time = randint(10, 100)
  93. numb_explode = randint(6, 10)
  94. # create list of list of all particles in all simultaneous explosion
  95. # 创建一个所有粒子同时扩大的二维列表
  96. for point in range(numb_explode):
  97. objects = []
  98. x_cordi = randint(50, 1250)
  99. y_cordi = randint(50, 500)
  100. # 烟花降落的速度
  101. speed = uniform(1, 4)
  102. size = uniform(0.5, 3)
  103. color = choice(colors)
  104. explosion_speed = uniform(1.5, 6)
  105. total_particles = randint(20, 100)
  106. for i in range(1, total_particles):
  107. r = part(cv, idx=i, total=total_particles, explosion_speed=explosion_speed, x=x_cordi, y=y_cordi,
  108. vx=speed, vy=speed, color=color, size=size, lifespan=uniform(0.6, 1.75))
  109. objects.append(r)
  110. explode_points.append(objects)
  111. total_time = .0
  112. # keeps undate within a timeframe of 1.8 second
  113. while total_time < 1.8:
  114. sleep(0.01)
  115. tnew = time()
  116. t, dt = tnew, tnew - t
  117. for point in explode_points:
  118. for item in point:
  119. item.update(dt)
  120. cv.update()
  121. total_time += dt
  122. # recursive call to continue adding new explosion on canvas
  123. root.after(wait_time, simulate, cv)
  124. def close(*ignore):
  125. """Stops simulation loop and closes the window."""
  126. global root
  127. root.quit()
  128. if __name__ == '__main__':
  129. root = tk.Toplevel()
  130. root.title("2021新年快乐呀^_^")
  131. cv = tk.Canvas(root, height=854, width=1280)
  132. # use a nice background image
  133. # image = Image.open("image1.jpg")
  134. # photo = ImageTk.PhotoImage(image)
  135. #
  136. #设置字体,如果没有,也可以不设置
  137. font = ImageFont.truetype("C:\\Windows\\Fonts\\simsun.ttc",60) #现在是宋体
  138. #打开底版图片
  139. image=Image.open("image1.jpg")
  140. # 在图片上添加文字 1
  141. draw = ImageDraw.Draw(image)
  142. draw.text((400, 50),"2021要加油哦",fill = "yellow",font=font)
  143. # draw = ImageDraw.Draw(image)
  144. photo = ImageTk.PhotoImage(image)
  145. cv.create_image(0, 0, image=photo, anchor='nw')
  146. cv.pack()
  147. root.protocol("WM_DELETE_WINDOW", close)
  148. root.after(100, simulate, cv)
  149. root.mainloop()

三 参考文献

 

  1. 代码参考链接:https://github.com/tuangauss/DataScienceProjects/blob/master/Python/fireworks.py
  2. python 图片上添加文字:https://blog.csdn.net/dyyay521/article/details/102546637
  3. 【解决问题】Python-Error:image "pyimage1" doesn't exist:https://blog.csdn.net/weixin_44436677/article/details/105498762
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/42707
推荐阅读
相关标签
  

闽ICP备14008679号