今天周五,513330又不能666了,哎,腿都蹲麻了。

在上一節(jié)的教程中,我們講了怎么通過三角形畫一個多邊形的方法。
今天,我們先來給它弄點色彩,再讓它動起來,先來看看效果:

注:gif動圖上傳有1M限制,這個圖被壓縮了91.83%,原圖更酷炫,看文末視頻。
開始吧。
第一步,涂色
前面我們講到多邊形是用三角形拼接而成的,今天我們新引進(jìn)兩個函數(shù),用來對封閉區(qū)域涂色。
turtle.begin_fill()
To be called just before drawing a shape to be filled.
turtle.end_fill()
Fill the shape drawn after the last call to begin_fill().
效果如下:

代碼:
length?=?400
turtle.color("white")
turtle.goto(0,?0)
turtle.begin_fill()
turtle.pendown()
turtle.seth(0)
turtle.fd(length)
(x,y)=turtle.pos()
turtle.penup()
turtle.goto(0,?0)
turtle.pendown()
turtle.seth(72)
turtle.fd(length)
turtle.goto(x,y)
turtle.penup()
turtle.end_fill()
第二步,更多涂色
然后,我們再來畫多邊形,給每個三角形不同的顏色。
我們用到的庫是:colorsys。
The colorsys module defines bidirectional conversions of color values between colors expressed in the RGB (Red Green Blue) color space used in computer monitors and three other coordinate systems: YIQ, HLS (Hue Lightness Saturation) and HSV (Hue Saturation Value). Coordinates in all of these color spaces are floating point values. In the YIQ space, the Y coordinate is between 0 and 1, but the I and Q coordinates can be positive or negative. In all other spaces, the coordinates are all between 0 and 1.
我們使用其中的函數(shù):
colorsys.hsv_to_rgb(h,?s,?v)
Convert?the?color?from?HSV?coordinates?to?RGB?coordinates.
問:為什么用這個hsv轉(zhuǎn)rgb?
答:HSV分別是色調(diào)、飽和度和亮度,其中H代表顏色信息。
如果把S和V固定,那么調(diào)整H就可以調(diào)整顏色,比較簡單。
H,S,V ∈ ?[0, 1]
代碼變一下:
def?draw_gon(length,?start_angle,?line):
????angle?=?360//line
????for?index?in?range(line):
????????(r,g,b)?=?colorsys.hsv_to_rgb(index/line,1,1)
????????turtle.color((r,g,b))
????????turtle.goto(0,?0)
????????turtle.begin_fill()????????
????????turtle.pendown()
????????turtle.seth(start_angle?+?angle*index)
????????turtle.fd(length)
????????(x,y)=turtle.pos()
????????turtle.penup()
????????turtle.goto(0,?0)
????????turtle.pendown()
????????turtle.seth(start_angle+angle*(index+1))
????????turtle.fd(length)
????????turtle.goto(x,y)
????????turtle.penup()
????????turtle.end_fill()彩色五邊形示例:


第三步,動起來
參考第一個教程中,讓直線旋轉(zhuǎn)起來的方式,讓它動起來。
每次刷新的時候,我們改變多邊形的角度。
最簡單的代碼:
for?angle?in?range(360):
????turtle.clear()
????draw_gon(400,?angle,?60)
????turtle.update()
????time.sleep(0.05)ontimer版本:
angle=1
length=400
def?movie_gon():
????global?angle
????turtle.clear()
????draw_gon(length,?angle,?60)
????angle?+=?1
????if?angle?>?360:
????????angle?=?0
????turtle.ontimer(movie_gon,?0)
????
movie_gon() 
--EOF--
例行求粉,謝謝!


本文使用 文章同步助手 同步