CSC111 drawChessBoard.py
.
# chess.py
# D. Thiebaut
# Draws a board with 8 queens on it, in such a way
# that none of them can take each other.
# The text exquivalent is shown below.
"""
Q . . . . . . .
. . . . Q . . .
. . . . . . . Q
. . . . . Q . .
. . Q . . . . .
. . . . . . Q .
. Q . . . . . .
. . . Q . . . .
"""
from graphics import *
def drawOneRow( win, xOffset, yOffset ):
"""draws a row of squares, alternating with the first one
being black, then white, etc."""
for x in range( xOffset, xOffset+ 8*20, 40 ):
coloredR = Rectangle( Point( x, yOffset ), Point( x+20, yOffset+20) )
coloredR.setFill( "black" )
coloredR.draw( win )
def drawBoard( win ):
""" draw the whole board of colored squares"""
#--- draw bigRectangle ---
topLeft = Point( 20, 20 )
botRight= Point( 180, 180 )
bigR = Rectangle( topLeft, botRight )
bigR.draw( win )
#--- draw first line ---
x = 20
for y in range( 20, 8*20+1, 20 ):
drawOneRow( win, x, y )
x = 60 - x
def drawQueens( win, solution ):
""" Puts the 8 queens on the board, in the right place.
Solution is a list containing the column location of each
queens, assuming that the first queen goes on the top row,
the second queen on the next row, etc."""
# pick each column one after the other
for row, col in solution:
# transform row and col into a y and x position
x = col * 20 + 20 + 10
y = row * 20 + 20 + 10
# put a circle at x,y
center = Point( x, y )
cir = Circle( center, 8 )
cir.draw( win )
cir.setFill( "red" )
def main():
#--- initialize the board ---
win = GraphWin( "Queens" )
drawBoard( win )
#--- the solution, where each number is a column number ---
#--- we assume that
solution = [ [0,0],[1,4],[2,7],[3,5],[4,2],[5,6],[6,1],[7,3] ]
drawQueens( win, solution )
#--- wait till user clicks mouse to close up ---
win.getMouse()
win.close()
main()
.