简体   繁体   English

如果使用随机数时语句不起作用

[英]If statement not working when using random numbers

My code has a turtle draw a dot at a random location.我的代码有一只乌龟在随机位置画一个点。 After it's drawn, another turtle goes forward to the same coordinates.绘制后,另一只乌龟前进到相同的坐标。 What's supposed to happen is when the second turtle reaches the dot, the dot is supposed to disappear and instantly be redrawn somewhere else, but for some reason the if statement isn't working:应该发生的是当第二只乌龟到达点时,该点应该消失并立即在其他地方重新绘制,但由于某种原因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)

Moving the turtle with移动乌龟

t.goto(dx,dy)

isn't changing the values of tx and ty .不会改变txty的值。 Try redoing尝试重做

tx = t.xcor() 
ty = t.ycor()

before the if statement.在 if 语句之前。

This is a fragile strategy to begin with:这是一个脆弱的策略:

if tx == dx and ty == dy:

as turtles wander a floating point plane and rarely land at the exact same spot.因为海龟在浮点平面上徘徊,很少在完全相同的地方着陆。 Let's rework this code to actually take advantage of turtle's methods and eliminate tx, ty and dx, dy completely:让我们重新编写这段代码,以真正利用乌龟的方法并完全消除tx, tydx, 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()

This has the turtle continuously chase the dot -- the dot relocates when the turtle reaches it.这让海龟不断追逐这个点——当海龟到达它时,这个点会重新定位。

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

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