Ted - 1 year ago 71

Python Question

I am trying to construct the game Konane (this link provides the game rules if you need to refer to them to better understand my question). I have created the function that will build the empty array, however am unclear as to what the best way is to go about filling the grid with alternating

`'B'`

`'W'`

Here is my current function that creates the empty array that I would like to alter to perform the above tasks:

`numrows = 3`

numcols = 4

def empty_grid():

return [['-' for y in range(numcols)]

for x in range(numrows)]

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

This is how I would implement the array initialization in the way that you want, and then print it to verify. There are other ways to accomplish the alternation you are looking for; taking the the sum of the indices modulo 2 is the most logical to me.

```
area = empty_grid() # get an empty_grid called area
for i in range(numrows): # go through the rows
for j in range(numcols): # go through the columns
if (i + j) % 2: # add the indices and check for oddness
area[i][j] = 'B' # if odd, set to B
else:
area[i][j] = 'W' # else (if even), set to W
for i in range(numrows): # for each row
print area[i] # print the row
```

Output:

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

The trickiest part is figuring out how to alternate on each row and offset each row so they are staggered by one. You can do this by using a counter variable (like `k`

) and adding one to it each time, although I would still end up checking evenness/oddness of something, so I found adding the indices to be the simplest for me to understand.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**