【问题标题】:How do I check and change turtle coordinates efficiently in Python?如何在 Python 中有效地检查和更改海龟坐标?
【发布时间】:2023-03-12 10:40:01
【问题描述】:

我对 Python 很陌生,我已经开始玩推箱子游戏。我一直在测试此代码以检查坐标以确保盒子/播放器在走进墙壁时向后移动。我尝试制作一个小循环和函数,但我不断收到错误。

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

语法错误 - 无法分配给函数调用 最后一行中的 a 突出显示。

检查功能正常工作,因为这段代码运行良好。

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")

如果有人知道修复代码的方法,我将不胜感激。谢谢!

【问题讨论】:

  • 确实不能给函数赋值。 Turtle 有一个 setx() 函数,您可以使用它来设置 x 坐标。

标签: python function syntax-error coordinates turtle-graphics


【解决方案1】:

这一行有问题:

a.xcor()=a.xcor()+50

因为xcor() 用于访问一个坐标,而不是设置一个。你要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)

这是您的下一个问题——checking() 函数将无法长期使用。海龟爬过一个浮点平面,它们通常不会回到它们离开的确切位置,例如(0, 0)(0, 0.001)。为了解决这个问题,我们需要一个不太精确的比较:

def checking(a, b):
    return abs(a.xcor() - b.xcor()) < 1 > abs(a.ycor() - b.ycor())

或者更好:

def checking(a, b):
    return a.distance(b) < 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    相关资源
    最近更新 更多