【问题标题】:Turtle won't turn around after hitting a wall乌龟撞墙后不会转身
【发布时间】:2018-02-05 22:38:09
【问题描述】:

我这样做是为了让乌龟画一个 200x200 的盒子,然后在里面反弹。但问题是它不会从顶部或左侧墙壁反弹。

t = turtle.Turtle()
s = turtle.Screen()
t.speed(1)

for i in range(4):
    t.forward(200)
    t.left(90)

t.penup()
t.goto(4, 4)
t.seth(r.randint(1, 89))

while 200 > t.xcor() > 0 and 200 > t.ycor() > 0:
    if t.xcor() >= 197:
        t.right(200)
    if t.xcor() <= 3:
        t.seth(r.randint(t.heading(),180))
    if t.ycor() >= 197:
        t.seth(r.randint(t.heading(), 180))
    if t.ycor() <= 3:
        t.left(200)

    t.forward(1)

这段代码允许海龟从右边的墙壁和底部的墙壁上反弹。当它到达左侧或顶壁时,乌龟转向屏幕左侧并继续离开屏幕。我尝试了setHeading() 的随机数,还尝试使用left()right() 来控制乌龟撞墙时的行为。我在这里做错了什么?或者有什么更好的方法让乌龟远离墙壁?

解释不同:乌龟撞到左边和顶壁时不转身,为什么?我该如何解决?

【问题讨论】:

    标签: python-3.x turtle-graphics


    【解决方案1】:

    现在您已经解决了问题,让我们修复您的代码。当您编写这样的循环时:

    while 200 > t.xcor() > 0 and 200 > t.ycor() > 0:
        if t.xcor() >= 195:
    

    您实际上是在创建一个无限循环,因为内部逻辑阻止了while 条件永远是False。好像你说的是while True:。但是你不应该在像turtle这样的事件驱动环境中说while True:,因为你可以阻止其他事件和可能性。

    让我们重写您的代码,使其完全由事件驱动,并且在我们使用它时,以屏幕为中心:

    from turtle import Turtle, Screen
    from random import randint
    
    screen = Screen()
    
    turtle = Turtle()
    turtle.speed('fastest')
    
    turtle.penup()
    turtle.goto(-100, -100)
    turtle.pendown()
    
    for _ in range(4):
        turtle.forward(200)
        turtle.left(90)
    
    turtle.penup()
    turtle.home()
    turtle.setheading(randint(0, 360))
    
    def move():
        if -90 < turtle.xcor() < 90 and -90 < turtle.ycor() < 90:
            pass  # I hate 'if's like this but it's simpler than the alternative
        else:
            turtle.setheading(turtle.heading() + 180 + randint(-45, 45))
            turtle.forward(1)  # extra bump forward to get out of trouble
    
        turtle.forward(1)
        screen.ontimer(move, 25)
    
    move()
    screen.mainloop()
    

    并不完美,但您可以看到它获得了您想要的动作,而不会锁定您可能想要发生的其他事情(如键盘事件、通过单击关闭窗口等)

    【讨论】:

      【解决方案2】:

      事实证明我的数字有点偏,seth()setHeading() 实际上可以上升到 360。所以当我做 random.randint(heading(), 180) 时,如果 heading() 大于 180,它可能找不到值. 这些修改解决了我的问题。

      if t.xcor() >= 195:
              t.seth(150)
      
          if t.xcor() <= 5:
              t.seth(r.randint(t.heading(),310))
      
          if t.ycor() >= 195:
              t.seth(r.randint(t.heading(), 300))
      
          if t.ycor() <= 5:
              t.left(150)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-01
        • 2022-01-20
        • 2021-09-26
        • 2017-08-09
        • 1970-01-01
        相关资源
        最近更新 更多