Exemplo n.º 1
0
	def __str__(self):

		if self.value != None:
			if self.given:
				return pp.format( supportedAlphabets[self.base][self.value], pp.TEXT_GREEN )
			else:
				return supportedAlphabets[self.base][self.value]
		elif len(self.domain) == 1:
			val = list(self.domain)[0]
			return pp.format( supportedAlphabets[self.base][val], pp.TEXT_RED )
		elif len(self.domain) == 0:
			return pp.format( '!', pp.BG_RED )
		else:
			#return pp.format( supportedAlphabets[self.base][len(self.domain)-1], pp.TEXT_MAGENTA )
			return '.'
Exemplo n.º 2
0
def parsePuzzleFile( filename ):
	'''Parse a puzzle file into a Grid object

	A properly formatted puzzle file should contain only value characters (in some squared base),
	spaces, and dividers (|-+). The correct base is inferred based on the width/height of the grid.

	For example, a properly formatted base-4 sudoku file might contain this:

		1 | 4
		 4|  
		--+--
		  |  
		41|23
	'''

	input = []
	with open(filename, 'r') as ifp:
		if ifp == None:
			print pp.format('Could not open file: '+filename, pp.RED_TEXT)
			return None

		input = ifp.readlines()
		input = [line[:-1] for line in input]


	# calculate the base, make sure it's valid
	l = len(input)
	base = ((sqrt(5+4*l)-1)/2)**2
	if len(input[0]) != len(input) or int(base) != base:

		raise SyntaxError('Input does not have appropriate dimensions')

	else:
		base = int(base)

	if base not in supportedAlphabets:
		raise IndexError('{} is not a supported base'.format(base))

	# start reading in numbers
	grid = Grid(base)
	blockBase = int(sqrt(base))
	dividers = '|-+'
	divFlag = False

	ri,ci = 0,0
	for row in input:
		ci = 0
		for focus in row:

			# check for dividers, but don't store them
			if focus in dividers:
				if ri % blockBase == 0 or ci % blockBase == 0:
					divFlag = True
					continue
				else:
					raise SyntaxError('Unexpected divider near ({},{})'.format(ri,ci))

			divFlag = False
			if focus != ' ':

				# read the cell value if provided in the correct radix
				value = supportedAlphabets[base].find(focus)
				if value == -1:
					raise ValueError('Value {} at ({},{}) is not a valid base-{} character'.format(focus, ri,ci, base))
				newCell = Cell(base, value, given=True)
				grid.insertCellAt( newCell, ri, ci )

			else:

				# fill in a blank cell
				newCell = Cell(base)
				grid.insertCellAt( newCell, ri, ci )
				

			ci = ci+1

		if not divFlag:
			ri = ri+1

	return grid