MadDoctor5813
MadDoctor5813

Reputation: 281

Nested for loops not functioning

I have this code:

def makeBoard():
    squareX = 0
    squareY = 0
    squareType = "dark"
    darkSquare = imageLoader("darkBrownSquare.png")
    lightSquare = imageLoader("lightBrownSquare.png")
    for x in range(8):
        for y in range(8):
            if squareType == "dark":
                MAIN_SURF.blit(darkSquare, (squareX, squareY))
                squareType = "light"
            elif squareType == "light":
                MAIN_SURF.blit(lightSquare, (squareX, squareY))
                squareType = "dark"
            squareY += 64
        squareX += 64

It's meant to draw a checkerboard pattern, but I only get this instead: enter image description here I assume it's because of the for loops, and the fact that they are nested, but otherwise, I have no idea.

Upvotes: 0

Views: 55

Answers (2)

Udy
Udy

Reputation: 2532

You need to zero squareY after finish its loop.

So after

squareX +=64

Just add

squareY = 0

Moreover, you can write a more readable code if you use range function step parameter and use the x and y instead of squareX and squareY (this will handle this bug as well)

Upvotes: 1

Blender
Blender

Reputation: 298176

Get rid of the squareX and squareY stuff and just create the right values of x and y from the beginning:

for x in range(0, 64, 8):
    for y in range(0, 64, 8):

Or multiply them by 8:

MAIN_SURF.blit(darkSquare, (8 * x, 8 * y))

Upvotes: 0

Related Questions