Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make the turtle a random color?

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))
like image 348
Cookie Avatar asked Dec 04 '25 13:12

Cookie


1 Answers

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

like image 174
cdlane Avatar answered Dec 06 '25 05:12

cdlane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!