我正在尝试为学校作业编写国际象棋的实施,但我遇到了一个似乎无法修复的问题。
def askpiece(self,player):
inputstring=input(player.name+ ", what is the location of the piece you would like to move (e.g.)? ")
x,y=inputstring
y=int(y)
if (x,y) in self and self[(x,y)].name[1] == player.tag:
if self[(x,y)].canmove(self,player):
return (x,y)
else:
print("the selected piece currently can't move, try again.")
elif self[(x,y)].name[1] != player.tag:
print("the piece you are trying to move belongs to the other player, try again.")
self.askpiece(player)
elif (x,y) not in self:
print("there is currently no piece on the specified location, try again.")
def canmove(self,board,player): #controls if the piece can move in atleast one way
#included the function canmove too in case that is what is causing the error
lettertonumber={"a":1,"b":2,"c":3,"d":4}
numbertoletter={1:"a",2:"b",3:"c",4:"d"}
for move in self.canmove:
if lettertonumber[self.x]+move[0] in [1,4] and self.y+move[1] in [1,5]:
if (lettertonumber[self.x]+move[0],self.y+move[1]) in board:
if self.name[1] != player.tag:
return True
else:
return True
return False
当我打电话给这个功能时,该功能正确地询问了我想要移动的棋子的位置(例如b1上的车),检查该棋子是否存在以及该棋子是否属于我,但是生成TypeError:
File "Schaak.py", line 31, in <module>
game()
File "Schaak.py", line 27, in game
(x,y)=askpiece(bord,player)
File "Schaak.py", line 9, in askpiece
if board[(x,y)].canmove(board,player) == True:
TypeError: 'list' object is not callable
在askpiece中,self是一个名为“board”的词典,self [(x,y)]是字典中的一个棋子,当我要求代码打印自[(x,y)]时,它正确地说明了对象是“class:Rook”,如果我要求它打印对象本身,输出也是正确的。无论我如何更改语法,我似乎得到这个错误(除非我将其更改为生成不同错误的东西),在其余的代码中,当我调用self [(x,y)]时,我不会得到任何错误
答案 0 :(得分:1)
canmove()
for move in self.canmove:
表示您在某个时刻将此属性设置为列表。方法和实例变量存在于同一名称空间中(实际上,方法只不过是一个恰好可调用的[class]变量),因此您不能重用相同的名称。一个名字或另一个名字必须改变;由于列表变量似乎更有可能只在内部使用,我建议将其更改为_canmove
,除非有更合适的名称可供使用。
答案 1 :(得分:0)
代码canmove
中的某个位置已分配给list
,因此当您尝试canmove(board,player)
时会收到错误消息:
In [26]: canmove = []
In [27]: canmove = []
In [28]: canmove()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-28-2a6706ff3740> in <module>()
----> 1 canmove()
TypeError: 'list' object is not callable