Okiic. Okiic. - 3 years ago 116
Python Question

Why is this grid not even?

It's probably something extremely obvious, but I can't seem to find why the first to columns in the grid are the same.

grid = [[1]*8 for n in range(8)]

cellWidth = 70

def is_odd(x):
return bool(x - ((x>>1)<<1))

def setup():
size(561, 561)

def draw():
x,y = 0,0
for xrow, row in enumerate(grid):
for xcol, col in enumerate(row):
rect(x, y, cellWidth, cellWidth)
if is_odd(xrow+xcol):
fill(0,0,0)
else:
fill(255)
x = x + cellWidth
y = y + cellWidth
x = 0

def mousePressed():
print mouseY/cellWidth, mouseX/cellWidth
print is_odd(mouseY/cellWidth + mouseX/cellWidth)


The result I get from the code above is:
checkers board

Any ideas?

Answer Source

Looks like the fill command doesn't change the color of the last rectangle you drew; instead it changes the color of all the draw calls subsequent to it. According to the docs:

Sets the color used to fill shapes. For example, if you run fill(204, 102, 0), all subsequent shapes will be filled with orange.

So all of your colors are lagging one square behind. It's as if all of the tiles were shifted one to the right, except for the leftmost row which is shifted one down and eight to the left. This makes that row mismatch with all the others.

Try putting your fill calls before the rect call:

    for xcol, col in enumerate(row):
        if is_odd(xrow+xcol):
            fill(0,0,0)
        else:
            fill(255)
        rect(x, y, cellWidth, cellWidth)
        x = x + cellWidth
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download