繁体   English   中英

如何在python中使乌龟随机改变颜色

[英]How to make a turtle in python change colors randomly

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秒更改一次颜色。 我应该怎么做。 我尝试导入随机。 这是用于学校作业。 请帮忙。

首先,您应该将代码分解为函数,例如:

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 s不需要那么多。 相反,请检查color in myColorList -如果不是,则报告“ 对不起”,但这不是颜色

要基于计时器更改乌龟的颜色(或通常要做一些事情),请使用turtle.ontimer()函数。 调用ontimer ,会给它一个函数和一个代表毫秒的数字。 一个很好的例子在这里 在此示例中,您可以看到他们在传递给ontimer的函数的末尾调用ontimer ,从而使它不断发生,而不仅仅是一次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM