首页 > 解决方案 > 弹跳海龟功能但不运行

问题描述

我正在为学校编写代码,其中乌龟在广场上弹跳。到目前为止它不可见,我打算改变它。问题是当我运行代码时,什么也没有发生,我不知道为什么。欢迎任何帮助。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()

标签: pythonturtle-graphics

解决方案


弹跳海龟功能但不运行

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

修复错误的缩进行,导致代码甚至无法启动,它没有做任何事情的原因是你编写了代码,当它“通过边界”时,但没有写任何东西让它做其他事情。如果它根本不动,它就不能徘徊在它的边界之外。

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

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

在此处输入图像描述


推荐阅读