下面是一個(gè)用Python編寫的簡(jiǎn)單煙花特效代碼,使用了Pygame庫(kù)來(lái)實(shí)現(xiàn)圖形顯示。請(qǐng)確保你已經(jīng)安裝了Pygame庫(kù),如果沒(méi)有安裝,可以使用pip install pygame
來(lái)安裝。
import pygame
import random
# 初始化Pygame
pygame.init()
# 屏幕大小
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
# 煙花粒子類
class Particle:
def __init__(self, x, y):
self.x = x
self.y = y
self.color = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
self.size = 5
self.speed = random.randint(1, 5)
self.angle = random.uniform(0, 2 * 3.14159)
def move(self):
self.x += self.speed * 0.5 * cos(self.angle)
self.y += self.speed * 0.5 * sin(self.angle)
self.size -= 0.05
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), int(self.size))
particles = []
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
x, y = pygame.mouse.get_pos()
for i in range(30):
particles.append(Particle(x, y))
for particle in particles:
particle.move()
if particle.size <= 0:
particles.remove(particle)
# 清屏
screen.fill((0, 0, 0))
# 繪制粒子
for particle in particles:
particle.draw()
pygame.display.flip()
pygame.quit()
這個(gè)代碼創(chuàng)建了一個(gè)窗口,當(dāng)你點(diǎn)擊鼠標(biāo)時(shí),會(huì)在鼠標(biāo)位置生成煙花粒子效果。這只是一個(gè)簡(jiǎn)單的示例,你可以根據(jù)需要進(jìn)行擴(kuò)展和改進(jìn)。注意,這只是一個(gè)基礎(chǔ)的煙花特效,實(shí)際的煙花特效通常更加復(fù)雜和精致。
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-735453.html
代碼二:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-735453.html
import pygame
import sys
import random
pygame.init()
# 設(shè)置屏幕尺寸和標(biāo)題
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Fireworks")
# 定義顏色
WHITE = (255, 255, 255)
# 定義煙花粒子類
class Particle:
def __init__(self, x, y):
self.x = x
self.y = y
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.radius = 2
self.dx = random.randint(-5, 5)
self.dy = random.randint(-5, 5)
def move(self):
self.x += self.dx
self.y += self.dy
def draw(self):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
particles = []
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 當(dāng)鼠標(biāo)點(diǎn)擊時(shí),產(chǎn)生新的煙花
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
for _ in range(100):
particle = Particle(x, y)
particles.append(particle)
screen.fill(WHITE)
# 更新和繪制煙花粒子
for particle in particles:
particle.move()
particle.draw()
# 移除已經(jīng)消失的煙花粒子
particles = [particle for particle in particles if particle.radius < 100]
pygame.display.flip()
clock.tick(60)
到了這里,關(guān)于python煙花代碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!