Search code examples
pythonpython-3.xloopsturtle-graphicschess

Drawing a chessboard with Turtle (even number dimension fail)


I have written this Python code with turtle graphics for drawing a chessboard by given dimension. The problem I'm facing is when I enter an odd number everything works just fine:

  • The last square is also filled, I just didn't manage to screen shot it on time

But when I enter an even number, it's like:

enter image description here

Here's the code:

from turtle import *
import sys


def main():
    dimension = int(input('Enter dimension: '))
    side = 50

    x_coord = -250
    y_coord = 300

    turtle = Turtle()
    turtle.speed('fastest')
    turtle.pensize(5)

    for i in range(dimension ** 2):
        if not i % dimension:
            y_coord -= side
            turtle.penup()
            turtle.setx(x_coord)
            turtle.sety(y_coord)
            turtle.pendown()

        if not i % 2:
            turtle.begin_fill()

        for _ in range(4):
            turtle.forward(side)
            turtle.right(90)

        turtle.forward(side)
        turtle.end_fill()


if __name__ == '__main__':
    sys.exit(main())

Solution

  • A similar flag-based solution with alternate approaches. I don't understand what your main() layout gets you so I reworked it to be a potential library with the test code under __main__:

    import turtle
    
    def draw_board(dimension, x_coord, y_coord, side):
    
        parity = False
    
        for i in range(dimension ** 2):
            if i % dimension == 0:
                y_coord -= side
                turtle.penup()
                turtle.setpos(x_coord, y_coord)
                turtle.pendown()
                parity = parity != (dimension % 2 == 0)  # logical XOR
    
            if parity:
                turtle.begin_fill()
    
            for _ in range(4):
                turtle.forward(side)
                turtle.right(90)
    
            if turtle.filling():
                turtle.end_fill()
    
            turtle.forward(side)
    
            parity = not parity
    
    
    if __name__ == '__main__':
        size = int(input('Enter dimension: '))
    
        turtle.speed('fastest')
    
        turtle.pensize(5)
    
        draw_board(size, -250, 300, 50)
    
        turtle.hideturtle()
    
        turtle.exitonclick()