Python 乌龟 - 无法为乌龟设置边界?

Python Turtle - Can't manage to set up boundary for a turtle?

我设置了热键并且可以移动乌龟,但是当我 运行 代码时,如果我超过 x 和 y 值则什么也不会发生。也没有错误。 怎么了?

if (Alex.xcor()>50 or Alex.xcor()<-50) and \
   (Alex.ycor()>50 or Alex.ycor()<-50):
    Alex.goto(0,0)

完整代码:

import turtle
import random

#Setting up the screen to work on
wn=turtle.Screen()
wn.screensize(500,500)

#Setting up properties of Alex
Alex=turtle.Turtle()
Alex.shape('turtle')
Alex.color('blue')

#Setting up function to turn right by 45 degrees
def turn_right():
    Alex.right(45)

#Setting up function to turn left by 45 degrees
def turn_left():
    Alex.left(45)

#Setting up function to go forward by 30 px
def go_forward():
    Alex.forward(30)

#Setting up function to go backwards by 30 px
def go_backward():
    Alex.backward(30)

#Setting up keyboard controls for the turtle
turtle.listen()
turtle.onkey(go_forward,"w")
turtle.onkey(turn_left,"a")
turtle.onkey(turn_right,"d")
turtle.onkey(go_backward,"s")


#Setting up border boundaries
if (Alex.xcor()>50 or Alex.xcor()<-50) and \
(Alex.ycor()>50 or Alex.ycor()<-50):
    Alex.goto(0,0)

你的if语句只returns乌龟在X和Y方向同时在边界外时回到原点。

你可能想要这样的东西:

if not (-50 <= Alex.xcor() <= 50 and -50 <= Alex.ycor() <= 50):

换句话说,定义乌龟什么时候是"in bounds"(X和Y坐标都在-50到50之间),然后用not.

取反

在你的边界逻辑之下(得到修复并)成为它自己的函数,check_boundary() 并被 go_forward()go_backward() 调用,因为它们是唯一可以引导乌龟的函数误入歧途:

from turtle import Turtle, Screen

# Set up the screen to work on
screen = Screen()
screen.setup(500, 500)

# Set up properties of Alex
Alex = Turtle('turtle')
Alex.color('blue')

# Function to turn right by 45 degrees
def turn_right():
    Alex.right(45)

# Function to turn left by 45 degrees
def turn_left():
    Alex.left(45)

# Function to check boundaries
def check_boundary():
    if -100 <= Alex.xcor() <= 100 and -100 <= Alex.ycor() <= 100:
            return  # OK

    Alex.goto(0, 0)

# Function to go forward by 10 px
def go_forward():
    Alex.forward(10)
    check_boundary()

# Function to go backward by 10 px
def go_backward():
    Alex.backward(10)
    check_boundary()

# Set up keyboard controls for the turtle
screen.onkey(go_forward, "w")
screen.onkey(turn_left, "a")
screen.onkey(turn_right, "d")
screen.onkey(go_backward, "s")
screen.listen()

screen.mainloop()

让一只乌龟在 100 像素的笼子里一次移动 30 像素似乎非常有限,所以我增加了笼子的大小并缩短了他的步幅,这样当他遇到边界时更容易看到。