通过从存储的turtlegraphics函数列表中随机选择来创建randompath

2024-05-14 19:07:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在列表中存储了海龟图形函数,并且正在使用随机函数调用它来创建一个随机路径,但是代码不起作用

有人能看看这个并提供建议吗

from turtle import Turtle
from turtle import Screen
import random

pen = Turtle()
pen.pensize(8)
pen.speed(10)
window = Screen()
window.colormode(255)

moves=[pen.forward(30),pen.backward(30)]
turns=[pen.right(90),pen.left(90)]

is_true = True

while is_true:
    pen.color(random.randint(0,255),random.randint(0,255),random.randint(0,255))
    random.choice(turns)
    random.choice(moves)

window.exitonclick()

Tags: fromimporttrue列表israndomwindowscreen
3条回答

第一个问题是,您不在列表movesturns中列出函数调用,而是列出调用的结果。第二个问题是在random.choice调用之后不调用函数。你实际上从中得到的是可见笔尖的闪烁效果,它会无休止地改变颜色

buran的回答中已经显示了如何修复它。另一种使turn和move参数不在循环中的方法是,在这里lambda :将函数调用转换为匿名函数,引用存储在movesturns中:

另一个选项是提取实际移动并转化为函数

from turtle import Turtle
from turtle import Screen
import random

pen = Turtle()
pen.pensize(8)
pen.speed(10)
window = Screen()
window.colormode(255)
 
moves=[lambda : pen.forward(30), lambda : pen.backward(30)]
turns=[lambda : pen.right(90), lambda : pen.left(90)]

for _ in range(100):
    pen.color(random.randint(0,255),random.randint(0,255),random.randint(0,255))
    random.choice(turns)()
    random.choice(moves)()

window.exitonclick()

我决定只画10条线,所以海龟很可能会留在屏幕上。有关摆脱while True循环的更好方法(包括解释),请参阅cdlane的答案

我想说,这里的问题是,当您可以简单地使用数据作为数据时,您正在使用函数。也就是说,给forward()一个负距离与backward()相同。给left()一个负角度与right()相同。因此,我们可以简单地做到:

from turtle import Screen, Turtle
from random import random, choice

DISTANCES = [30, -30]
ANGLES = [90, -90]

def move():
    turtle.color(random(), random(), random())
    turtle.left(choice(ANGLES))
    turtle.forward(choice(DISTANCES))

    screen.ontimer(move, 10)

screen = Screen()

turtle = Turtle()
turtle.pensize(8)
turtle.speed('fastest')

move()

screen.exitonclick()

我还讨论了下一个问题,你的隐含while True:。按照您构建代码的方式,exitonclick()永远无法到达,也无法工作。现在它可以工作了,因为我们将绘图和exitonclick()都保存在事件循环中

只有在定义两个列表时,才能执行这些方法。像这样更改代码的相关部分

moves=[pen.forward, pen.backward]
turns=[pen.right, pen.left]

while True:
    pen.color(random.randint(0,255), random.randint(0,255), random.randint(0,255))
    random.choice(turns)(90)
    random.choice(moves)(30)

相关问题 更多 >

    热门问题