如何让乌龟变成随机颜色?

问题描述 投票:0回答:3

如何修复此代码以使乌龟具有随机颜色?我希望能够点击让乌龟转动并改变颜色。

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))
python turtle-graphics python-turtle
3个回答
3
投票

我希望能够点击然后乌龟转动然后改变颜色。

我相信这符合你的描述:

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()

而不是

range(10000)
循环,它使用计时器来保持乌龟移动,这也允许事件循环正常运行。 它应该继续运行,直到您关闭海龟窗口:

enter image description here


0
投票
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
投票
import import turtle
from turtle import Turtle, Screen
import random

pen = Turtle()
screen = Screen()
turtle.colormode(255)

def random_color():
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    colors = (r, g, b)
    return colors
pen.color(random_color())

你不能使用 randint 而不是 random 否则你会陷入困境
浮点数并且颜色选项有限,如果我错了请纠正我

© www.soinside.com 2019 - 2024. All rights reserved.