wondering what happened to my python code that draw a checkerboard with turtle? any helps?

Viewed 71
import turtle
def main():
    turtle.pensize(4)
    for x in range(5):
        for y in range(5):
            turtle.penup()
            turtle.goto(x*50,y*50)
            turtle.pendown()
            if (x+y)%2 == 0:
                turtle.begin_fill()
                black_square(50)
                turtle.end_fill()
            else:
                turtle.begin_fill()
                white_square(50)
                turtle.end_fill()

def black_square(width):
    turtle.fillcolor('black')
    for x in range(4):
        turtle.forward(width)
        turtle.left(90)

def white_square(width):
    turtle.fillcolor('white')
    for x in range(4):
        turtle.forward(width)
        turtle.right(90)

main()

Current image: Image drawn by code

Intended image: Intended effect

My code won't draw a correct checkerboard pattern, but I wonder why every for loop my square black and white both executed at the same time? I am not asking for the correct code that will get me the correct checkerboard and I just want an explanation for the mistakes in my code.

2 Answers

I don't know how to explain your mistakes without giving you the correct code, but I will try:

basically the mistake is that black_square and white_square are drawing squares at the same location. The starting point is 50 units apart, but because the squares are drawn in opposite directions (clockwise and counter-clockwise), the resulting area overlaps. black_square would draw a square below the starting point, while white_square would draw a square above its starting point.

@Samson is totally right. You are almost there but there is a small mistake. For black squares you are rotating left and for the white square you are rotating right. So basically white square instruction is overwriting the black squares. Keep same direction.

The end result is as below. Correct Checkerbox

Related