[英]If statement not working when using random numbers
我的代码有一只乌龟在随机位置画一个点。 绘制后,另一只乌龟前进到相同的坐标。 应该发生的是当第二只乌龟到达点时,该点应该消失并立即在其他地方重新绘制,但由于某种原因if
语句不起作用:
import turtle, random
t = turtle.Turtle()
t.speed(1)
dot = turtle.Turtle()
dot.hideturtle()
dot.speed(0)
dx = random.randint(1,100)
dy = random.randint(1,100)
tx = t.xcor()
ty = t.ycor()
def createDot(dx, dy):
dot.penup()
dot.goto(dx, dy)
dot.pendown()
dot.circle(5)
createDot(dx, dy)
t.goto(dx,dy)
if tx == dx and ty == dy:
dot.clear()
createDot(dx, dy)
移动乌龟
t.goto(dx,dy)
不会改变tx
和ty
的值。 尝试重做
tx = t.xcor()
ty = t.ycor()
在 if 语句之前。
这是一个脆弱的策略:
if tx == dx and ty == dy:
因为海龟在浮点平面上徘徊,很少在完全相同的地方着陆。 让我们重新编写这段代码,以真正利用乌龟的方法并完全消除tx, ty
和dx, dy
:
from turtle import Screen, Turtle
from random import randint
def moveDot():
dot.goto(randint(-100, 100), randint(-100, 100))
def chaseDot():
if turtle.distance(dot) < 1:
moveDot()
turtle.setheading(turtle.towards(dot))
turtle.forward(2)
screen.ontimer(chaseDot, 50)
screen = Screen()
turtle = Turtle()
turtle.speed('slowest')
dot = Turtle('circle')
dot.shapesize(0.5)
dot.speed('fastest')
dot.penup()
chaseDot()
screen.exitonclick()
这让海龟不断追逐这个点——当海龟到达它时,这个点会重新定位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.