Introduction to Programming using Python 1st Edition

Published by Pearson
ISBN 10: 0132747189
ISBN 13: 978-0-13274-718-9

Chapter 6 - Functions - Programming Exercises - Page 212: 6.47

Answer

This program uses the turtle module to display two chessboards on the screen. The drawChessboard function takes in the start and end coordinates of the chessboard and uses a nested loop to draw each square in the correct location and color. The program then calls the drawChessboard function twice to display two chessboards, once with the upper-left corner at (-200, 200) and the bottom-right corner at (200, -200), and once with the upper-left corner at (-400, 0) and the bottom-right corner at (-200, -200). (Please see the step by step algorithm below)

Work Step by Step

import turtle def drawChessboard(startx, endx, starty, endy): $\hspace{4mm}$# Define the square size (function starts here) $\hspace{4mm}$square_size = (endx - startx) / 8 $\hspace{4mm}$# Set the pen color to black $\hspace{4mm}$turtle.pencolor("black") $\hspace{4mm}$# increase speed of turtle $\hspace{4mm}$turtle.speed(0) $\hspace{4mm}$# Loop through each row $\hspace{4mm}$for row in range(8): $\hspace{8mm}$# Loop through each column $\hspace{8mm}$for col in range(8): $\hspace{12mm}$# Calculate the top-left corner of the square $\hspace{12mm}$x = startx + col * square_size $\hspace{12mm}$y = starty - row * square_size $\hspace{12mm}$# Draw the square $\hspace{12mm}$turtle.penup() $\hspace{12mm}$turtle.goto(x, y) $\hspace{12mm}$turtle.pendown() $\hspace{12mm}$turtle.begin_fill() $\hspace{12mm}$for i in range(4): $\hspace{16mm}$turtle.forward(square_size) $\hspace{16mm}$turtle.right(90) $\hspace{12mm}$turtle.end_fill() $\hspace{12mm}$# Change the fill color for the next square in the chessboard $\hspace{12mm}$if turtle.fillcolor() == "black": $\hspace{16mm}$turtle.fillcolor("white") $\hspace{12mm}$else: $\hspace{16mm}$turtle.fillcolor("black") $\hspace{8mm}$# Change the fill color for the next row in chessboard $\hspace{8mm}$if turtle.fillcolor() == "black": $\hspace{12mm}$turtle.fillcolor("white") $\hspace{8mm}$else: $\hspace{12mm}$turtle.fillcolor("black") # (function ends here) # Set the screen size turtle.screensize(800, 800) # Draw the first chessboard drawChessboard(-400, 0, 200, -200) # Draw the second chessboard drawChessboard(100, 500, 200, -200) # Hide the turtle and exit turtle.hideturtle() turtle.done()
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.