[英]How do I check and change turtle coordinates efficiently in Python?
I am quite new to Python and I have started a Sokoban game. 我对Python很陌生,已经开始了推箱子游戏。 I have been testing this code for checking coords to ensure the box/player moves back when walking into a wall. 我一直在测试此代码以检查坐标,以确保进入墙壁时盒子/播放器能够向后移动。 I tried making a little loop and the function, but I keep getting errors. 我试着做一些循环和函数,但是我不断出错。
import turtle
wn=turtle.Screen()
a=turtle.Turtle()
b=turtle.Turtle()
def checking(x,y):
if x.xcor()==y.xcor() and x.ycor()==y.ycor():
return True
else:
return False
if checking(a,b)==True:
a.xcor()=a.xcor()+50
Syntax error- Cannot assign to function call The a in the last line is highlighted. 语法错误-无法分配给函数调用最后一行中的a被突出显示。
The checking function works as this code worked perfectly. 检查功能可以正常工作,因为此代码可以完美运行。
import turtle
wn=turtle.Screen()
a=turtle.Turtle()
b=turtle.Turtle()
def checking(x,y):
if x.xcor()==y.xcor() and x.ycor()==y.ycor():
return True
else:
return False
if checking(a,b)==True:
wn.bgcolor("blue")
I would appreciate if anyone knew a way to fix the code. 如果有人知道修复代码的方法,我将不胜感激。 Thank you! 谢谢!
This line is a problem: 这行是个问题:
a.xcor()=a.xcor()+50
as xcor()
is used to access a coordinate, not set one. 因为xcor()
用于访问坐标,而不是设置坐标。 You want setx()
: 您需要setx()
:
from turtle import Screen, Turtle
wn = Screen()
a = Turtle()
b = Turtle()
def checking(x, y):
return x.xcor() == y.xcor() and x.ycor() == y.ycor()
# or better yet: return x.position() == y.position()
if checking(a, b):
a.setx(a.xcor() + 50)
Here's your next issue -- the checking()
function won't work in the long term. 这是您的下一个问题checking()
函数无法长期使用。 Turtles crawl a floating point plane and they often don't return to the exact position they left, eg (0, 0)
vs (0, 0.001)
. 乌龟爬行浮点平面,它们通常不会返回到它们原来的确切位置,例如(0, 0)
vs (0, 0.001)
。 To deal with this, we'll need a less exact comparison: 为了解决这个问题,我们需要一个不太精确的比较:
def checking(a, b):
return abs(a.xcor() - b.xcor()) < 1 > abs(a.ycor() - b.ycor())
or better yet: 或更好:
def checking(a, b):
return a.distance(b) < 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.