擅长:python、mysql、java
<p>一种让你自己更轻松的方法是不必担心棋子在哪里,而是将其委托给一个棋盘对象:</p>
<pre><code>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)
</code></pre>
<p>Board的<code>setup</code>方法接受一个元组列表,每个元组都包含实例化一个新片段所需的数据,并指定它应该在线路板上的位置。不需要递归,只需要简单的循环将数据传递到类中。在</p>