弹跳乌龟的功能,但不运行

2024-10-01 09:32:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在为一只乌龟在广场上蹦蹦跳跳的学校做一个代码。到目前为止还看不到,我打算改变。问题是当我运行代码时,什么都没有发生,我也不知道为什么。欢迎任何帮助。xxturt和yyturt是一种试图让海龟后退的方法,以防它越过边界

import turtle
import random
turt=turtle.Turtle()


while True:
  xturt = turt.xcor()
  yturt = turt.ycor()
  if abs(xturt) >= 50:
    heading = turt.heading()
    for i in range(1):
      rand=random.randint(90,150)
      xxturt=xturt-50
    turt.back(xxturt)
    turt.setheading(rand + heading)
    turt.fd(1)

  if abs(yturt) >= 50:
heading = turt.heading()
    for i in range(1):
      rando=random.randint(90,150)
      yyturt=yturt-50
    turt.back(yyturt)
    turt.setheading(rando + heading)
    turt.fd(1)
screen.exitonclick()

Tags: 代码inimportforifrangerandomabs
1条回答
网友
1楼 · 发布于 2024-10-01 09:32:26

Bouncing turtle functions but doesn't run

所以乌龟“不跑”,是“看不见”和“什么也没发生”,但它“起作用”?真的吗

修复了使代码无法启动的错误缩进行,它什么都不做的原因是,当它“通过边界”时,您为它编写了代码,但没有为它编写任何东西。如果它一点也不动,它就不能游荡在边界之外

让我们简化你的代码,看看我们是否能让海龟基本上移动:

from turtle import Screen, Turtle
from random import randint

screen = Screen()
turtle = Turtle('turtle')

while True:
    x, y = turtle.position()

    if not abs(x) < 100 > abs(y):
        turtle.backward(1)

        heading = turtle.heading()
        rand = 180 + randint(-30, 30)

        turtle.setheading(rand + heading)

    turtle.forward(1)

screen.exitonclick()  # never reached

enter image description here

相关问题 更多 >