处理颜色会使该程序(或其他任何程序)复杂化。 计算机图形学中的两种主要颜色模型是RGB和HSV。 Turtle和许多其他图形库接受RGB,但不接受HSV。 但是,HSV最适合在彩虹色之间循环(我说“彩虹”,但HSV中有些色不是真正的彩虹。请注意,例如图片中的褐色。没关系)。 只需将色相从0开始,并在每一步将其递增,直到1(在某些系统中为100),然后使用colorsys库将其转换为RGB。
代码如下:
# Random Walk, in glorious Technicolour
# https://docs.python.org/3/library/turtle.html
# Authour: Alan Richmond, Python3.codes
from turtle import *
from random import randint
from colorsys import hsv_to_rgb
step=30 # length of each step
nsteps=2000 # number of steps
hinc=1.0/nsteps # hue increment
width(2) # width of line
(w,h)=screensize() # boundaries of walk
speed('fastest')
colormode(1.0) # colours 0:1 instead of 0:255
bgcolor('black') # black background
hue=0.0
for i in range(nsteps):
setheading(randint(0,359))
# https://docs.python.org/2/library/colorsys.html
color(hsv_to_rgb(hue, 1.0, 1.0)) # pen colour in RGB
hue+=hinc # change colour
forward(step) # step along!
(x,y)=pos() # where are we?
if abs(x) > w or abs(y) > h: # if at boundary
backward(step) # step back
done()
效果图如下: