import turtle
tina = turtle.Turtle()
tina.shape('turtle')
your_name = input("What is your name")
tina.penup()
tina.forward(20)
tina.write("Why, hello there, " + your_name + "!")
tina.backward(20)
tina.color("green")
tina.left(90)
tina.forward(100)
tina.right(90)
tina.pendown()
tina.pencolor("red")
tina.forward(50)
tina.right(50)
tina.forward(50)
tina.right(100)
tina.forward(55)
tina.left(50)
tina.forward(55)
tina.penup()
tina.forward(30)
tina.pendown()
tina.dot(10)
tina.penup()
tina.goto(100, 100)
color = input("What color is the shape")
try:
if color == ("red"):
tina.write("Your are correct" + your_name + "!")
tina.backward(20)
elif color == ("green" or "Green"):
tina.write("Sorry, It is actually Red")
tina.backward(20)
elif color == ("black" or "Black"):
tina.write("Sorry, Its is actually Red")
tina.backward(20)
elif color == ("purple" or "Purple"):
tina.write("Sorry, It is actually Red")
tina.backward(20)
elif color == ("blue" or "Blue"):
tina.write("Sorry, It is actually Red")
tina.backward(20)
except:
tina.backward(20)
tina.write("Sorry, but that isn't a color")
tina.backward(20)
这是我的代码。我想知道如何让乌龟在整个程序中随机改变颜色。它应该在整个程序中每隔0.5秒改变一次颜色。我该怎么做我试图随机导入。这是为了学校作业。请帮助。
答案 0 :(得分:0)
首先,您应该将代码分解为函数,例如:
def drawShape (myTurtle, turtleColor, shapeColor):
myTurtle.penup()
myTurtle.backward(20)
myTurtle.color(turtleColor)
myTurtle.left(90)
myTurtle.forward(100)
myTurtle.right(90)
myTurtle.pendown()
myTurtle.pencolor(shapeColor)
myTurtle.forward(50)
myTurtle.right(50)
myTurtle.forward(50)
myTurtle.right(100)
myTurtle.forward(55)
myTurtle.left(50)
myTurtle.forward(55)
myTurtle.penup()
myTurtle.forward(30)
myTurtle.pendown()
myTurtle.dot(10)
myTurtle.penup()
myTurtle.goto(100, 100)
您可以使用random
创建随机数:
import random
randomNumber = random.randint(0,5) #created random integer between 0 and 5
现在,为了对颜色使用随机值,首先创建一个颜色列表:
myColorList = ["red","green","black","purple","blue","yellow"]
然后创建一个随机整数,并将该整数用作此列表的索引。
查看答案时,您不需要那么多if
。而是检查color in myColorList
-如果不是,则报告 对不起,但这不是颜色
要根据计时器更改乌龟的颜色(或通常做某事),请使用turtle.ontimer()
函数。调用ontimer
时,会给它一个函数和一个代表毫秒的数字。 here是一个很好的例子。在此示例中,您可以看到他们在传递给ontimer
的函数的末尾调用ontimer
,这样它就不断发生,而不仅仅是一次。