如何在我的 Turtle Graphic 中添加随机颜色 - Python

How to add randomizing colors in my Turtle Graphic - Python

所以我有这个工作得很好的递归图形,但我想知道海龟图形,在我的例子中,我如何让每条线段成为随机颜色?

from turtle import *

def line(t, x1, y1, x2, y2):
    """draws the line segment from x1,y1 to x2,y2"""

    t.up()
    t.goto(x1, y1)
    t.down()
    t.goto(x2, y2)

def drawLine(t, x1, y1, x2, y2, level):
    """forms the shape"""

    if level == 0:
        line(t, x1, y1, x2, y2)
    else:
        xm = ((x1 + x2) + (y2 - y1)) // 2
        ym = ((y1 + y2) + (x1 - x2)) // 2
        drawLine(t, x1, y1, xm, ym, level-1)
        drawLine(t, xm, ym, x2, y2, level-1)

def main():
    """the main function"""

    myTurtle = Turtle()

    myTurtle.hideturtle()

    num = int(input("Please enter the number of levels: "))

    drawLine(myTurtle, 100, 0, 100, -200, num)


main()

您可以创建一个颜色列表,然后在绘制每条线时使用 random.choice 从列表中随机选择一种颜色。

这是代码更新

from turtle import *
import random

colors = ['red','green','blue','indianred','firebrick','ForestGreen'] # color list

def line(t, x1, y1, x2, y2):
    """draws the line segment from x1,y1 to x2,y2"""
    
    t.color(random.choice(colors))  # pick color from list
    t.up()
    t.goto(x1, y1)
    t.down()
    t.goto(x2, y2)

......

输出(10级)

您可以使用 tuple(randint(0,255) for _ in range(3)) 获得随机颜色三元组,其中 randint 来自 random 模块。然后你可以在每次画线时调用这个函数 t.pencolor(*get_rand_color()).

PS : colormode(255) 必须在将颜色设置为元组的代码中设置,现在理论上你可以获得任何可能的 16.8 million colors

from turtle import *
from random import randint
def line(t, x1, y1, x2, y2):
    """draws the line segment from x1,y1 to x2,y2"""

    t.up()
    t.goto(x1, y1)
    t.down()
    t.pencolor(*get_rand_color())
    t.goto(x2, y2)

def get_rand_color():
    """
    Returns a 3-tuple of random numbers in the range 0 - 255
    eg : (89, 103, 108)
    """
    return tuple(randint(0,255) for _ in range(3))


def drawLine(t, x1, y1, x2, y2, level):
    """forms the shape"""
    if level == 0:
        line(t, x1, y1, x2, y2)
    else:
        xm = ((x1 + x2) + (y2 - y1)) // 2
        ym = ((y1 + y2) + (x1 - x2)) // 2
        drawLine(t, x1, y1, xm, ym, level-1)
        drawLine(t, xm, ym, x2, y2, level-1)

def main():
    """the main function"""
    myTurtle = Turtle()
    myTurtle.hideturtle()
    colormode(255)
    num = 6
    drawLine(myTurtle, 100, 0, 100, -200, num)

main()

关卡5是这样的

编辑:正如@cdlane 在评论中指出的那样,“colormode(255) 必须设置为将颜色指定为 0 - 255 范围内的值。默认情况下,turtle 的颜色模式使用 0.0 - 1.0 范围内的值它们可以由元组指定:(0.5, 0.125, 0.333)".

换句话说,如果您不执行 colormode(255),您可以将 get_rand_color 函数更改为 return 范围内 0.01.0 的值] 而不是 0255.