让自己更轻松的一种方法是不要让这些部分担心它们在哪里,而是将其委托给 Board 对象:
import string
class Piece(object):
def __init__(self, type, colour):
self.type = type
self.colour = colour
def __str__(self):
return 'Piece(%(type)s, %(colour)s)' % self.__dict__
class Board(dict):
def __init__(self, width, height):
self.update(
dict(((x,y), None)
for x in string.ascii_lowercase[:width] # alphabetic axis
for y in xrange(1, height+1) # numeric axis
)
)
def setup(self, position_seq):
for type, colour, position in position_seq:
self[position] = Piece(type, colour)
initial_positions = [
('rook', 'W', ('a', 1)),
('knight', 'W', ('b', 1)),
('bishop', 'W', ('c', 1)),
('queen', 'W', ('d', 1)),
('king', 'W', ('e', 1)),
('pawn', 'W', ('a', 2)),
]
b = Board( 8,8 )
b.setup( initial_positions )
print b['a',1] # returns Piece(rook, W)
Board的setup
方法采用一个元组列表,每个元组都包含实例化新片段所需的数据,并指定它应该在板上的位置。不需要递归,只需一个简单的循环将数据传递到类中。