有没有更好(和更短)的方法来创建像数组一样的棋盘。对董事会的要求是:
- 板可以有不同的尺寸(在我的例子中是 3x3)
- 棋盘的左下角应始终为黑色
- 黑色方块由 呈现
"B"
,白色方块由 呈现"W"
我拥有的代码:
def isEven(number):
return number % 2 == 0
board = [["B" for x in range(3)] for x in range(3)]
if isEven(len(board)):
for rowIndex, row in enumerate(board):
if isEven(rowIndex + 1):
for squareIndex, square in enumerate(row):
if isEven(squareIndex + 1):
board[rowIndex][squareIndex] = "W"
else:
for squareIndex, square in enumerate(row):
if not isEven(squareIndex + 1):
board[rowIndex][squareIndex] = "W"
else:
for rowIndex, row in enumerate(board):
if not isEven(rowIndex + 1):
for squareIndex, square in enumerate(row):
if isEven(squareIndex + 1):
board[rowIndex][squareIndex] = "W"
else:
for squareIndex, square in enumerate(row):
if not isEven(squareIndex + 1):
board[rowIndex][squareIndex] = "W"
for row in board:
print row
输出:
['B', 'W', 'B']
['W', 'B', 'W']
['B', 'W', 'B']