<p>更新依据:</p>
<blockquote>
<p>Every run of the program will give the option which size the board
should be ...
every board in the code shall be the same size</p>
</blockquote>
<p>我们将<code>size</code>作为一个类变量,并且只有在尚未设置大小时才提示输入大小。所有后续的电路板创建将使用与第一块板相同的尺寸:</p>
<pre><code>class BoardHandler:
size = None
def __init__(self):
self.board = None
if BoardHandler.size is None:
self.ask_size()
self.getNewBoard()
def ask_size(self): # no self use, method could be a function
while True:
try:
BoardHandler.size = int(input("Which size would you want? "))
break
except ValueError:
print("Wrong! try again")
def getNewBoard(self):
self.board = []
for _ in range(BoardHandler.size):
self.board.append([' '] * BoardHandler.size)
def resetBoard(self):
for x in range(BoardHandler.size):
for y in range(BoardHandler.size):
self.board[x][y] = ' '
n = int(BoardHandler.size / 2 - 1)
self.board[n][n] = 'B'
self.board[n + 1][n] = 'W'
self.board[n][n + 1] = 'W'
self.board[n + 1][n + 1] = 'B'
def drawBoard(self):
HLINE = ' ' + '-' * (4 * BoardHandler.size) + '-'
print(HLINE)
for y in range(BoardHandler.size):
print("{:2d}".format(y + 1), end=' ')
for x in range(BoardHandler.size):
print('| {}'.format(self.board[x][y]), end=' ')
print('|')
print(HLINE)
handler = BoardHandler()
handler.resetBoard()
handler.board[0][0] = 'W'
handler.drawBoard()
print(BoardHandler.size)
handler2 = BoardHandler()
handler2.drawBoard() # empty board but same size as first
</code></pre>