我试图为学校作业写一个国际象棋的实现,但我遇到了一个我似乎无法解决的问题。在
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上的rook),检查该工件是否存在以及该工件是否真正属于我,但随后生成一个TypeError:
^{pr2}$在askpiece中,self是一个名为“board”的字典,self[(x,y)]是字典中的一个棋子,当我要求代码打印self[(x,y)]时,它正确地声明对象是“class:Rook”,如果我要求它打印对象本身,则输出也是正确的。不管我如何改变语法,我似乎都会得到这个错误(除非我把它改成产生不同错误的东西),在剩下的代码中,当我调用self[(x,y)]
在您的代码中,
canmove
被分配给了list
,所以当您尝试canmove(board,player)
时,会出现错误:这行在
canmove()
意味着您在某个时刻将此属性设置为列表。方法和实例变量存在于同一个命名空间中(实际上,方法只不过是一个碰巧可调用的[class]变量),因此不能重用相同的名称。一个或另一个名称必须更改;由于list变量似乎更可能只在内部使用,我建议将其更改为
_canmove
,除非有更合适的名称可以使用。在相关问题 更多 >
编程相关推荐