简体   繁体   中英

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:

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 . Try redoing

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

before the if statement.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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