1 问题
流星雨是可遇不可求的美景之一,除了在天空上看到,我们能不能用Python来绘画一场彩色的动态流星雨?
2 方法
先使用import函数引入turtle模块、random模块和math模块,然后利用turtle模块设置画布大小和颜色,以及流星的颜色。之后定义流星类,包括横纵坐标,移动速度,大小等;之后定义画流星的方法,最后用列表保存所有流星,定义80个流星,开始绘画!
代码清单 1
import random
import turtle
import math
turtle.setup(1.0,1.0)
turtle.screensize(1.0,1.0)
turtle.bgcolor('black')
t = turtle.Pen()
t.ht()
colors = ['skyblue','white','cyan','aqua','pink','green']
class Meteor(object):
def __init__(self):
self.r = random.randint(50, 100)
self.t = random.randint(1, 3)
self.x = random.randint(-2000, 1000)
self.y = random.randint(0, 500)
self.speed = random.randint(5, 10)
self.color = random.choice(colors)
self.outline = 1
def star(self):
t.pensize(self.outline)
t.penup()
t.goto(self.x,self.y)
t.pendown()
t.color(self.color)
t.begin_fill()
t.fillcolor(self.color)
t.setheading(-30)
t.right(self.t)
t.forward(self.r)
t.left(self.t)
t.circle(self.r * math.sin(math.radians(self.t)), 180)
t.left(self.t)
t.forward(self.r)
t.end_fill()
def move(self):
if self.y >= -500:
self.y -= self.speed
self.x += 2 * self.speed
else:
self.r = random.randint(50, 100)
self.t = random.randint(1, 3)
self.x = random.randint(-2000, 1000)
self.y = 500
self.speed = random.randint(5, 10)
self.color = random.choice(colors)
self.outline = 1
Stars = []
for i in range(100):
Stars.append(Meteor())
while True:
turtle.tracer(0)
t.clear()
for i in range(100):
Stars[i].move()
Stars[i].star()
turtle.update()
turtle.mainloop()
3 结语
针对如何利用python绘画彩色动态流星雨的问题,运用了import函数,以及各个模块自带的方法等,通过实验,证明该方法是有效的,需要注意的是,定义x和y的范围时,并不是唯一值,依图像而定。并且需要使流星出现时随机位置。本文方法并不是唯一方法,未来可以尝试用其他的方法绘画彩色动态流星雨。