简体   繁体   中英

When using the turtle function in python, how can I generate a random dot color?

For a my class, I am tasked with programming a turtle function that is user controlled via the arrow keys. The function displays itself and then a mirror of itself with dots. Each dot should be a completely randomized color. So far, I have this:

from turtle import *
from random import randrange

FRAMES_PER_SECOND = 10
mirrorTurtle = Turtle()

def turnRight():
    global turtle
    global mirrorTurtle

    turtle.right(45)

def turnLeft():
    global turtle
    global mirrorTurtle

    turtle.left(45)

def randomColor(turtle):
    r = randrange(256)    # red component of color
    g = randrange(256)    # green component
    b = randrange(256)    # blue component

def move():
    colormode(255)
    global turtle
    global mirrorTurtle
    global moving

    if moving:
        for i in range(1):
            turtle.penup()
            mirrorTurtle.penup()
            turtle.forward(40)
            turtle.dot(20, "red")
            mirrorTurtle.dot(10, "blue")
            turtle.forward(1)
            mirrorTurtle.setpos(-turtle.xcor(), -turtle.ycor())
            ontimer(move, 1000 // FRAMES_PER_SECOND)

def start():
    global moving

    moving = True
    move()

def stop():
    global moving

    moving = False


def main():
    colormode(255)
    global turtle
    global mirrorTurtle

    turtle = Turtle()
    turtle.hideturtle()
    mirrorTurtle.hideturtle()


    onkey(turnRight, "Right")
    onkey(turnLeft, "Left")
    onkey(start, "Up")
    onkey(stop, "Down")
    listen()



if __name__ == "__main__":
    main()

the issue for me is, where I have "red" and "blue" are supposed to be random colors (that still act as a mirror (ie; if the first dot typed is blue, the mirror should be blue as well).

If you search for a function that gives you a random color string, see this:

def randcolor():
    return "#"+"".join([random.choice("0123456789ABCDEF") for i in range(6)]

You are very close to a solution. You need small changes to randomColor and to move .

In randomColor , you have successfully created three random numbers. Now you just need to create a tuple and return it, like so:

def randomColor():
    r = randrange(256)    # red component of color
    g = randrange(256)    # green component
    b = randrange(256)    # blue component
    return r,g,b

Then, you need to use that random color in your call to dot() :

        mirrorTurtle.dot(10, randomColor())

Additionally, to get your program to work in my environment, I need to add a call to update() at the end of move() , and a call to mainloop() at the end of main() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM