The main logic is straightforward. The Puzzle() constructor reads the puzzle file and
performs the initialization phase; see Section 14, “Puzzle.__init__(): Constructor”. See also Section 9, “usage(): Show command line argument usage” and Section 10, “fatal(): Write a message and stop”.
#================================================================
# Functions and classes
#----------------------------------------------------------------
# - - - m a i n
def main():
'''Kriss Kross puzzle solver, main procedure.
[ sys.argv names one readable, valid Kriss Kross puzzle file ->
sys.stdout +:= (solution(s) to the puzzle, if any) +
(number of solutions)
else ->
sys.stderr +:= error message(s) ]
'''
print "===== %s %s =====" % (PROGRAM_NAME, EXTERNAL_VERSION)
#-- 1 --
# [ if sys.argv names one readable file ->
# inFile := that file, opened for reading
# else ->
# sys.stderr +:= error message(s)
# stop execution ]
argList = sys.argv[1:]
if len(argList) == 1:
try:
inFileName = argList[0]
inFile = file ( inFileName )
except IOError, detail:
fatal ( "Couldn't open input file '%s': %s" %
(inFileName, detail) )
else:
usage ()
See Section 13, “class Puzzle: The top-level
container” and Section 14, “Puzzle.__init__(): Constructor”.
#-- 2 --
# [ if inFile contains a valid puzzle file ->
# puzzle := a Puzzle instance representing that file
# else ->
# sys.stderr +:= error message(s)
# stop execution ]
try:
puzzle = Puzzle ( inFile )
except SyntaxError, detail:
fatal ( "Terminated due to puzzle syntax errors: %s" %
detail )
print "=== Initial state"
print puzzle.show()
For the generator that produces all the solutions, see
Section 37, “Puzzle.genSolutions(): Generate all
solutions”. This generator
yields the Puzzle instance in a solved
state, and the method described in Section 27, “Puzzle.show(): Display the state of the
puzzle” returns the solution as a
multi-line string. We'll also need a counter to keep track
of how many solutions were produced.
#-- 3 --
nSolutions = 0
#-- 4 --
# [ nSolutions +:= number of solutions of puzzle, if any
# sys.stdout +:= solutions of puzzle, if any ]
for solution in puzzle.genSolutions():
nSolutions += 1
print "\n=== Solution #%d" % nSolutions
print solution.show()
#-- 5 --
# [ sys.stdout +:= nSolutions ]
print "=== Total number of solutions: %d" % nSolutions