每次运行代码时,如何为我的Turtle设置随机速度?

时间:2017-02-10 23:56:17

标签: python turtle-graphics

我试图制作一个海龟赛车游戏(使用Python - Turtle),但我无法弄清楚每次运行代码时如何为每只乌龟设置一个随机速度(这样Turtle x赢了& #39;每次都赢)

#define race fuction. Move each Turtle fd(random number between 2-10)  
red.pensize(10)
blue.pensize(10)
green.pensize(10)
red.speed(random)
blue.speed(random)
green.speed(random)

1 个答案:

答案 0 :(得分:0)

turtle.speed()设置为任何值,包括random.randint()的结果,既不必要也不充分。它很方便。下面是我的极简主义海龟赛车代码。 turtle.speed()方法用作藏匿乌龟速度的地方,但如果你改变:

turtle.forward(turtle.speed() + 1)

到固定值:

turtle.forward(10)

你会发现,无论turtle.speed()的设置如何,海龟都以相同的速度移动。 turtle.speed()值仅确定乌龟绘制更新的速度。最终,turtle.forward()的论证中的差异控制着向前运动的数量:

from random import randint
from turtle import Turtle, Screen

TURTLE_SIZE = 20
MAXIMUM_SPEED = 10
DEFAULTS = {'shape':"turtle", 'visible': False}

screen = Screen()

starting_line = TURTLE_SIZE - screen.window_width()/2
finish_line = screen.window_width()/2 - TURTLE_SIZE - MAXIMUM_SPEED

turtles = dict(red=Turtle(**DEFAULTS), green=Turtle(**DEFAULTS), blue=Turtle(**DEFAULTS))

for i, (color, turtle) in enumerate(turtles.items()):
    turtle.color(color)
    turtle.penup()
    turtle.goto(starting_line, i * TURTLE_SIZE)
    turtle.speed(randint(0, MAXIMUM_SPEED))
    turtle.showturtle()

racing = True

while racing:
    for turtle in turtles.values():
        turtle.forward(turtle.speed() + 1)
        if turtle.xcor() >= finish_line:
            racing = False
            break

screen.exitonclick()

为了让龟赛变得更复杂,您可能需要使用ontimer()事件来让他们更独立地移动。

enter image description here