Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a black and white chessboard in a two dimensional array

Tags:

python

Is there a better (and shorter) way of how to create chessboard like array. Requirements for the board are:

  • board can be different size (in my example it's 3x3)
  • bottom left square of the board should always be black
  • black square is presented by "B", white square is presented by "W"

Code that I have:

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

Output:

['B', 'W', 'B']
['W', 'B', 'W']
['B', 'W', 'B']
like image 227
4d4c Avatar asked May 02 '13 20:05

4d4c


3 Answers

How about:

>>> n = 3
>>> board = [["BW"[(i+j+n%2+1) % 2] for i in range(n)] for j in range(n)]
>>> print board
[['B', 'W', 'B'], ['W', 'B', 'W'], ['B', 'W', 'B']]
>>> n = 4
>>> board = [["BW"[(i+j+n%2+1) % 2] for i in range(n)] for j in range(n)]
>>> print board
[['W', 'B', 'W', 'B'], ['B', 'W', 'B', 'W'], ['W', 'B', 'W', 'B'], ['B', 'W', 'B', 'W']]
like image 62
DSM Avatar answered Nov 16 '22 05:11

DSM


Here is an itertools solution:

from itertools import cycle
N = 4

colors = cycle(["W","B"])
row_A  = [colors.next() for _ in xrange(N)]
if not N%2: colors.next()
row_B  = [colors.next() for _ in xrange(N)]

rows = cycle([row_A, row_B])
board = [rows.next() for _ in xrange(N)]

For N=4 this gives

['W', 'B', 'W', 'B']
['B', 'W', 'B', 'W']
['W', 'B', 'W', 'B']
['B', 'W', 'B', 'W']

This should be extensible to multiple colors (say a board that goes "B", "W", "G") if you make sure to add each new row and cycle to the list of rows.

like image 22
Hooked Avatar answered Nov 16 '22 04:11

Hooked


Kind of a hack but

print [["B" if abs(n - row) % 2 == 0 else "W" for n in xrange(3)] for row in xrange(3)][::-1]

This seems like requirements creep or something =)

def make_board(n):
    ''' returns an empty list for n <= 0 '''
    return [["B" if abs(c - r) % 2 == 0 else "W" for c in xrange(n)] for r in xrange(n)][::-1]
like image 2
John Avatar answered Nov 16 '22 05:11

John