簡體   English   中英

如果使用隨機數時語句不起作用

[英]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)

不會改變txty的值。 嘗試重做

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

在 if 語句之前。

這是一個脆弱的策略:

if tx == dx and ty == dy:

因為海龜在浮點平面上徘徊,很少在完全相同的地方着陸。 讓我們重新編寫這段代碼,以真正利用烏龜的方法並完全消除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()

這讓海龜不斷追逐這個點——當海龜到達它時,這個點會重新定位。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM