【问题标题】:TypeError: detectCollisions() takes exactly 8 arguments (9 given)TypeError:detectCollisions() 正好需要 8 个参数(给定 9 个)
【发布时间】:2015-03-09 14:21:09
【问题描述】:

我不断收到这种类型错误 TypeError:detectCollisions() 正好接受 8 个参数(给定 9 个)

def detectCollisions(x1,y1,w1,h1,x2,y2,w2,h2,):

    if (x2+w2>=x1>=x2 and y2+h2>=y1>=y2):

        return True

    elif (x2+w2>=x1+w1>=x2 and y2+h2>=y1>=y2):

        return True

    elif (x2+w2>=x1>=x2 and y2+h2>=y1+h1>=y2):

        return True

    elif (x2+w2>=x1+w1>=x2 and y2+h2>=y1+h1>=y2):

        return True

    else:

        return False

def update(self,gravity,blocklist):
    if(self.velocity<0):
        self.falling=True
    blockX,blockY=0,0

    collision=False

    for block in blocklist:

        collision = self.detectCollisions(self.x, self.y, self.width, self.height, block.x, block.y, block.width, block.height)

我不确定它有什么问题,我已经添加了一个 def 来检测碰撞

【问题讨论】:

  • 旁白:你为什么将自我属性传递给self.detectCollisions()detectCollisions() 不应该隐式访问self.xself.y 等吗?
  • 是的,该方法似乎应该简单地采用self, other
  • 你应该给我们看一些代码。还不够,你的class呢?
  • 我添加了更多代码。

标签: python pygame collision-detection typeerror


【解决方案1】:

我很确定您在方法声明中错过了self

def detectCollisions(x, y, ....

第一个参数应该是self,然后是您的自定义参数。

调用它时,self 被隐式传递(所以它有 9 个参数,而你在调用中只使用了 8 个参数)

【讨论】:

    【解决方案2】:

    这是一个典型的python学习问题。 成员函数中的第一个参数始终是“self”参数。 它包含在“幕后”的调用中。

    这就是为什么当你只给出 8 个参数时它会显示 9 个参数。 这是一个说明这一点的类声明,请尝试使用代码:

    class TestClass():
        def test(self, _param1, _param2):
            print("_param1:" + str(_param1) + "_param2:" + _param2)
    
    _instance = TestClass()
    _instance.test("a", "b")
    _instance.test("a", "b", "c")
    

    第一次调用有效,第二次无效,您会收到典型的错误消息。 反过来也一样,你总是需要在声明中添加“self”参数。

    【讨论】:

    • 不太清楚你的意思能不能多解释一下。
    • 类中的函数通常称为成员函数。 Python 中的成员函数将“self”作为第一个参数。看起来代码中的函数是类声明中的成员函数。如果是,您应该将def detectCollisions(x1,y1,w1,h1,x2,y2,w2,h2,) 更改为def detectCollisions(self, x1, y1, w1, h1, x2, y2, w2, h2)
    • @TobiAkinyemi 如果它不是一个类而是独立函数,那么我们将不得不重新开始......
    猜你喜欢
    • 2013-10-07
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 2015-07-17
    • 2014-05-06
    相关资源
    最近更新 更多