【发布时间】:2014-10-27 13:14:09
【问题描述】:
我正在尝试为学校作业编写国际象棋的实现,但我遇到了一个我似乎无法解决的问题。
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)] 是字典中的一个棋子,当我要求代码打印 self[(x,y)] 时,它正确地指出对象是“类:Rook”,如果我要求它打印对象本身,输出也是正确的。无论我如何更改语法,我似乎都会收到此错误(除非我将其更改为产生不同错误的内容),并且在其余代码中,当我调用 self[(x,y)] 时,我不会收到任何错误
【问题讨论】:
-
我无法在您的代码中找到
if board[(x,y)].canmove(board,player) == True:行。 -
您是否在代码中的任何地方重复使用了名称
canmove并将其分配给某个列表? -
是的!就是这样!我不敢相信我忽略了这一点。
标签: python dictionary typeerror