I am trying to draw a checker board using the Turtle library and am running into an error where the board window does not open. It was working at the beginning of my session about 30 minutes ago but, I changed some stuff and want to know why it changed.
Here is my code:
##This program draws a checkboard using the turtle library import turtle #below initiates the turtle pen and screen penMain = turtle.Turtle() turtleMain = turtle.Screen() def turtleBoard(): for x in range(4): penMain.forward(30) penMain.left(90) penMain.forward(30) turtleMain.setup(600, 600) penMain.speed(50) for a in range(8): penMain.up() penMain.setpos(0, 30 * a) penMain.down() for x in range(8): if (a + x)% 2 == 0: squareColor = 'black' else: squareColor = 'white' penMain.fillcolor(squareColor) penMain.begin_fill() turtleBoard() penMain.end_fill()
I believe this code works besides my one error! Thank you all for your help in advance!
Now that we’ve seen that your code can be made to work, let’s consider stamping instead of drawing to make it work more simply and more quickly:
from turtle import Screen, Turtle SQUARES_PER_EDGE = 8 SQUARE_SIZE = 30 # in pixels OFFSET = SQUARE_SIZE * (SQUARES_PER_EDGE / 2) - SQUARE_SIZE/2 # center the board CURSOR_SIZE = 20 def turtleBoard(): turtle.shape('square') turtle.shapesize(SQUARE_SIZE / CURSOR_SIZE) turtle.penup() for y in range(SQUARES_PER_EDGE): for x in range(SQUARES_PER_EDGE): turtle.goto(x * SQUARE_SIZE - OFFSET, y * SQUARE_SIZE - OFFSET) turtle.fillcolor('black' if y % 2 == x % 2 else 'white') turtle.stamp() screen = Screen() screen.setup(600, 600) turtle = Turtle() turtle.speed('fastest') # because I have no patience turtleBoard() screen.exitonclick()