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

问题描述:

我有我的热键设置和能够移动乌龟,但是当我运行代码时,没有任何反应,如果我超过了x和y值..没有错误。 有什么问题?Python龟 - 无法设置为乌龟边界?

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) 

下面的边界逻辑(获取固定的和)成为其自身的功能,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() 

有一只乌龟moves30px在一个100px的笼子里,这个时候看起来非常有限,所以我增加了笼子的尺寸,缩短了他的步幅,所以在他碰到边界时更容易看到。

if声明,只有当它是X,并在同一时间Y方向两个边界外返回龟原点。

你可能想是这样的:

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

换句话说,当乌龟“的界限”定义(X和Y坐标为-50至50之间),然后否定与not

+0

改变它到你刚才所说的,现在对我来说完全合理,但它不再工作。有任何想法吗? –

+0

那么,只有在程序启动时才检查一次,而不是在乌龟移动之后。也许把它添加到移动龟的功能... – kindall