A colourful random walk. The basic idea is very simple: choose a random heading in the range 0:360 degrees. Step in that direction. Choose another random heading & step again. Do this 2,000 times. As a bonus, we go through all the colours of the rainbow (or something similar) from beginning to end.

Dealing with colours complicates this program (or any other). The 2 main colour models in computer graphics are RGB and HSV. Turtle and many other graphics libraries accept RGB but not HSV. However, HSV is most convenient for cycling through rainbow colours (I say ‘rainbow’ but there are some hues in HSV that aren’t in real rainbows. Note for example the brownish colour in the picture. Never mind). Just start the hue at 0 and increment it at each step, up to 1 (or 100 in some systems), then convert to RGB using the colorsys library.

#   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()

[welcomewikilite wikiurl=”http://en.wikipedia.org/wiki/Random_walk” sections=”Short description” settings=””]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.