Reputation: 3
So I have this recursive graphic that works perfectly fine, but I was wondering for turtle graphics, and in my case how do I get each line segment to be a random color?
from turtle import *
def line(t, x1, y1, x2, y2):
"""draws the line segment from x1,y1 to x2,y2"""
t.up()
t.goto(x1, y1)
t.down()
t.goto(x2, y2)
def drawLine(t, x1, y1, x2, y2, level):
"""forms the shape"""
if level == 0:
line(t, x1, y1, x2, y2)
else:
xm = ((x1 + x2) + (y2 - y1)) // 2
ym = ((y1 + y2) + (x1 - x2)) // 2
drawLine(t, x1, y1, xm, ym, level-1)
drawLine(t, xm, ym, x2, y2, level-1)
def main():
"""the main function"""
myTurtle = Turtle()
myTurtle.hideturtle()
num = int(input("Please enter the number of levels: "))
drawLine(myTurtle, 100, 0, 100, -200, num)
main()
Upvotes: 0
Views: 3239
Reputation: 7123
You can get a random color triple using tuple(randint(0,255) for _ in range(3))
where randint
is from random
module. You can then call this function every time you draw a line t.pencolor(*get_rand_color())
.
PS : colormode(255)
must be set in the code for setting colors as tuples, now in theory you can get any of the 16.8 million colors
possible.
from turtle import *
from random import randint
def line(t, x1, y1, x2, y2):
"""draws the line segment from x1,y1 to x2,y2"""
t.up()
t.goto(x1, y1)
t.down()
t.pencolor(*get_rand_color())
t.goto(x2, y2)
def get_rand_color():
"""
Returns a 3-tuple of random numbers in the range 0 - 255
eg : (89, 103, 108)
"""
return tuple(randint(0,255) for _ in range(3))
def drawLine(t, x1, y1, x2, y2, level):
"""forms the shape"""
if level == 0:
line(t, x1, y1, x2, y2)
else:
xm = ((x1 + x2) + (y2 - y1)) // 2
ym = ((y1 + y2) + (x1 - x2)) // 2
drawLine(t, x1, y1, xm, ym, level-1)
drawLine(t, xm, ym, x2, y2, level-1)
def main():
"""the main function"""
myTurtle = Turtle()
myTurtle.hideturtle()
colormode(255)
num = 6
drawLine(myTurtle, 100, 0, 100, -200, num)
main()
For level 5
this is how it looks like
Edit : As @cdlane points out in comments, "colormode(255)
must be set to specify colors as values in the range 0 - 255. By default, turtle's color mode uses values in the range 0.0 - 1.0 and they can be specified by a tuple: (0.5, 0.125, 0.333)".
In other words if you don't do colormode(255)
, you can change the get_rand_color
function to return values in the range 0.0
to 1.0
instead of 0
to 255
.
Upvotes: 0
Reputation: 11342
You can create a list of colors then use random.choice
to pick a random color from the list when drawing each line.
Here is the code update
from turtle import *
import random
colors = ['red','green','blue','indianred','firebrick','ForestGreen'] # color list
def line(t, x1, y1, x2, y2):
"""draws the line segment from x1,y1 to x2,y2"""
t.color(random.choice(colors)) # pick color from list
t.up()
t.goto(x1, y1)
t.down()
t.goto(x2, y2)
......
Output (10 levels)
Upvotes: 1