当前位置:   article > 正文

Python-烟花代码_python火花代码

python火花代码
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. import pygame
  4. import random
  5. import time # 导入time模块
  6. # 设置窗口尺寸
  7. WIDTH, HEIGHT = 800, 600
  8. # 颜色定义
  9. BLACK = (0, 0, 0)
  10. WHITE = (255, 255, 255)
  11. RED = (255, 0, 0)
  12. GREEN = (0, 255, 0)
  13. BLUE = (0, 0, 255)
  14. YELLOW = (255, 255, 0)
  15. # 初始化pygame
  16. pygame.init()
  17. screen = pygame.display.set_mode((WIDTH, HEIGHT))
  18. pygame.display.set_caption("Fireworks")
  19. # 定义Firework(烟花)类
  20. class Firework:
  21. def __init__(self):
  22. self.x = random.randint(50, WIDTH - 50)
  23. self.y = HEIGHT
  24. self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
  25. self.speed = random.randint(5, 12)
  26. def move(self):
  27. self.y -= self.speed
  28. def explode(self, sparks):
  29. for _ in range(50):
  30. spark = Spark(self.x, self.y, self.color)
  31. sparks.append(spark)
  32. def draw(self, screen):
  33. pygame.draw.circle(screen, self.color, (self.x, self.y), 3)
  34. # 定义Spark(火花)类
  35. class Spark:
  36. def __init__(self, x, y, color):
  37. self.x = x
  38. self.y = y
  39. self.color = color
  40. self.speedx = random.uniform(-1, 1) * 8
  41. self.speedy = random.uniform(-1, 1) * 8
  42. self.age = 0
  43. def move(self):
  44. self.x += self.speedx
  45. self.y += self.speedy
  46. self.speedy += 0.2
  47. self.age += 1
  48. def draw(self, screen):
  49. pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), 2)
  50. # 主循环
  51. clock = pygame.time.Clock()
  52. fireworks = []
  53. sparks = []
  54. running = True
  55. start_time = pygame.time.get_ticks() # 获取程序开始的时间
  56. total_run_time = 60 * 3 # 设置程序总运行时间为3分钟
  57. current_run_time = 0 # 当前程序运行时间
  58. while current_run_time < total_run_time: # 循环条件改为判断当前运行时间是否小于总运行时间
  59. for event in pygame.event.get():
  60. if event.type == pygame.QUIT:
  61. running = False
  62. screen.fill(BLACK)
  63. # 创建新烟花
  64. if random.random() < 0.02:
  65. fireworks.append(Firework())
  66. # 更新和绘制烟花
  67. for firework in fireworks:
  68. firework.move()
  69. firework.draw(screen)
  70. if firework.y < random.randint(50, HEIGHT // 2):
  71. firework.explode(sparks)
  72. fireworks.remove(firework)
  73. # 移动和绘制火花
  74. for spark in sparks:
  75. spark.move()
  76. spark.draw(screen)
  77. if spark.age > 100:
  78. sparks.remove(spark)
  79. pygame.display.flip()
  80. clock.tick(60)
  81. # 更新程序当前运行时间
  82. current_run_time = (pygame.time.get_ticks() - start_time) / 1000 # 转换为秒
  83. time.sleep(0.1) # 添加时间延迟,让程序暂停0.1秒
  84. pygame.quit()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/515391
推荐阅读
相关标签
  

闽ICP备14008679号