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 drawBoard( win, N, side, border ):
"""draw the board, including border and black and white
squares. N is the number of squares on the side. side
is the width of a square. border is the gutter around the
squares"""
#--- draw the border first ---
r = Rectangle( Point( border, border ),
Point( border+N*side, border+N*side ) )
r.draw( win )
#--- then all the black squares only ---
for row in range( N ):
drawRow( win, N, side, border, row )
def drawRow( win, N, side, border, row ):
"""draws one row of black squares on the board. if row is 0
the first top row is drawn."""
#--- offset every even row by 1 square width ---
offset = (row % 2) * side
#--- place half of N black squares ---
for c in range( 0, N, 2 ):
x = border + offset + c * side
y = border + row * side # must use row somehow
x2 = x + side
y2 = y + side
r = Rectangle( Point( x, y ), Point( x2, y2 ) )
r.setFill( "black" )
r.draw( win )
def drawSolution( win, N, side, border, solution ):
"""Given a solution for N queens on the board, show them as
red circles"""
for row, col in solution:
centerX = border + col*side + side/2
centerY = border + row*side + side/2
queen = Circle( Point( centerX, centerY ), side/4 )
queen.setFill( "red" )
queen.draw( win )
def main():
#--- the controlling parameters ---
N = 8 # number of squares on a side
border = 20 # gutter around the board
side = (200-2*border) / N # size of a square
solution = [ [0,0],[1,4],[2,7],[3,5],[4,2],[5,6],[6,1],[7,3] ]
#--- open a window ---
win = GraphWin( "Chessboard" )
#--- draw the board, then the queens ---
drawBoard( win, N, side, border )
drawSolution( win, N, side, border, solution )
#--- wait for users to click mouse on window ---
win.getMouse( )
win.close()
main()
.