我设置了热键并且能够移动乌龟,但是当我运行代码时,如果我超过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)
答案 0 :(得分:1)
在你的边界逻辑下面(得到修复)成为它自己的函数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()
一只乌龟在100px的笼子里一次移动30px似乎非常有限,所以我增加了笼子的大小并缩短了他的步幅,因此当他遇到边界时更容易看到。
答案 1 :(得分:0)
当if
语句同时位于X和Y方向的边界之外时,您的if not (-50 <= Alex.xcor() <= 50 and -50 <= Alex.ycor() <= 50):
语句只会将乌龟返回到原点。
你可能想要这样的东西:
not
换句话说,定义乌龟何时在界限中#34; (X和Y坐标都在-50到50之间)然后用{{1}}否定它。