user5478619 user5478619 - 2 months ago 15
Python Question

How to get different colors in python turtle

Hi I am writing a python turtle file, where a function will return a random color (I can choose any three), and then a function will draw a face anywhere on the screen. It calls the function to draw a face 5 times, and each time it picks a different color. I have everything and it prints a face, but it will only print it in one color and I'm not sure how to get it to print a different color each time.

This is my code:

import turtle
import random

window = turtle.Screen()

sam = turtle.Turtle()
sam.pensize(3)

def getColor():
color = random.randint(1,3)
if color == 1:
sam.fillcolor("pink")
return "Color: Pink"
elif color == 2:
sam.fillcolor("lightblue")
return "Color: Light Blue"
else:
sam.fillcolor("purple")
return "Color: Purple"

def drawFace(x,y):
move = random.randint(1,2)
if move == 1:
sam.penup()
sam.left(x)
sam.forward(y)
sam.pendown()

else:
sam.penup()
sam.right(x)
sam.forward(y)
sam.pendown()

sam.begin_fill()
sam.right(90)
sam.forward(10)
sam.left(40)
sam.forward(30)
sam.left(50)
sam.forward(90)
sam.left(60)
sam.forward(20)
sam.left(30)
sam.forward(10)
sam.left(90)
sam.forward(118)
sam.end_fill()

sam.penup()
sam.right(90)
sam.forward(50)
sam.right(90)
sam.forward(40)
sam.pendown()

sam.begin_fill()
sides = 4
while sides > 0:
sam.forward(20)
sam.right(90)
sides = sides - 1
sam.end_fill()

sam.penup()
sam.forward(60)
sam.right(90)
sam.pendown()

sam.begin_fill()
sides = 4
while sides > 0:
sam.forward(20)
sam.right(90)
sides = sides - 1
sam.end_fill()



print(getColor())
drawFace(40,50)
drawFace(90,100)
drawFace(30,200)
drawFace(280,50)
drawFace(90,100)


Thank you

Answer

getColor() is only being called once, at the start of your program. You need to make a call to getColor() before drawing each face, like this:

print(getColor())
drawFace(40,50)
print(getColor())
drawFace(90,100)
print(getColor())
drawFace(30,200)
print(getColor())
drawFace(280,50)
print(getColor())
drawFace(90,100)

Your code would be a little more concise it you wrote that in a loop:

points = [(40,50), (90,100), (30,200), (280,50), (90,100)]

for x,y in points:
    print(getColor())
    drawFace(x, y)

Or you could put a call getColor() from your drawFace().