0
我是新来的类,但试图努力将它们合并到所有采用相同输入的函数的程序中(我假设这样做时,它使得最多感...?)。我正在研究一个棋盘,所以它看起来合适。Python类 - 通过函数推下变量名称
我有一个例子,下面我试图拉一块有效的动作。
class Board:
def __init__(self, board, r, c):
self.board = board
self.r = r
self.c = c
def piece(self):
return self.board[self.r,self.c]
def color(self):
#does this line not get pushed down so 'legal_moves' can't see self.piece?
self.piece = Board(self.board,self.r,self.c).piece()
if self.piece == '-':
return 'N'
elif self.piece.istitle():
return 'w'
else:
return 'b'
#This is the function that returns None
def legal_moves(self):
moves = {'P':[(1,0)],
'p':[(-1,0)],
'r':[(1,0),(-1,0),(0,1),(0,-1)],
'n':[(2,1),(2,-1),(-2,-1),(-2,1)],
'b':[(1,1),(-1,-1),(-1,1),(1,-1)],
'k':[(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(-1,1),(1,-1)]}
return moves.get(self.piece)
我的板是一个标准的8x8棋盘与R-K表 'W' 和r-K在初始配置 'B'(没有取得移动)
print(Board(curr,1,2).piece()) #returns P - correct
print(Board(curr,1,2).color()) #returns w - correct
print(Board(curr,1,2).legal_moves()) #returns None - incorrect
谢谢!另外,我是编程新手,所以如果您有任何风格/效率评论,请添加它们。
非常感谢!完善。作为一个方面说明,我应该能够定义'def valid_move(self,r,c,r_offset):self.r_offset,self.c_offset = r + r_offset,c + c_offset',然后使用'self.r_offset'同一班级的其他职能?这似乎不是,但只是想仔细检查 – user6142489