How can I make the turtle a random color?

52.1k views Asked by At

How can I fix this code to make the turtle a random color? I want to be able to click to make the turtle turn and change color.

import turtle
import random
turtle.colormode(255)
R = 0
G = 0
B = 0
def color(x, y):
    turtle.color((R, G, B))
def turn(x, y):
    turtle.left(10)
for i in range(10000):
    turtle.onscreenclick(turn)
    turtle.forward(1)
    turtle.onrelease(color)
    R = random.randrange(0, 257, 10)
    B = random.randrange(0, 257, 10)
    G = random.randrange(0, 257, 10)
    def color(x, y):
        turtle.color((R, G, B))
2

There are 2 answers

1
kaidokuuppa On
import turtle, random


def color(x, y):
    R = random.randrange(0,257,10)
    G = random.randrange(0,257,10)
    B = random.randrange(0,257,10)
    turtle.color(R,G,B)
    turtle.left(10)

turtle.colormode(255)

for i in range(10000):
    turtle.onscreenclick(color)
    turtle.forward(1)
0
cdlane On

I want to be able to click then the turtle turns then change color.

I believe this does what you describe:

import turtle
import random

def change_color():
    R = random.random()
    B = random.random()
    G = random.random()

    turtle.color(R, G, B)

def turn_and_change_color(x, y):
    turtle.left(10)
    change_color()

turtle.onscreenclick(turn_and_change_color)

def move_forward():
    turtle.forward(1)
    turtle.ontimer(move_forward, 25)

move_forward()

turtle.mainloop()

Rather than the range(10000) loop, it uses a timer to keep the turtle moving which also allows the event loop to run properly. It should keep running until you close the turtle window:

enter image description here