Rewrite the printer to be cleaner
This commit is contained in:
parent
77456d5114
commit
e329208db9
1 changed files with 37 additions and 24 deletions
|
@ -42,6 +42,13 @@ class Sudoku:
|
||||||
'''
|
'''
|
||||||
return self.size ** 4
|
return self.size ** 4
|
||||||
|
|
||||||
|
@property
|
||||||
|
def all_squares(self):
|
||||||
|
'''
|
||||||
|
Iterator of xy-coordinates for every square in the grid.
|
||||||
|
'''
|
||||||
|
return itertools.product(range(self.row_size), repeat=2)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def all_boxes(self):
|
def all_boxes(self):
|
||||||
'''
|
'''
|
||||||
|
@ -131,32 +138,38 @@ class Sudoku:
|
||||||
def solve(self, solver):
|
def solve(self, solver):
|
||||||
return solver.solve(self)
|
return solver.solve(self)
|
||||||
|
|
||||||
|
def _xy_to_idx(self, x, y):
|
||||||
|
return y * self.row_size + x
|
||||||
|
|
||||||
def _apply_index_ranges(self, ranges):
|
def _apply_index_ranges(self, ranges):
|
||||||
return ((self._board[i] for i in r) for r in ranges)
|
return ((self._board[i] for i in r) for r in ranges)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
field_width = len(str(max(self.possible_values)))
|
field_width = len(str(max(self.possible_values)))
|
||||||
sz = self.size
|
spacer = '{0}{1}{0}'.format('+', '+'.join(['-' * (field_width * self.size) for _ in range(self.size)]))
|
||||||
lines = []
|
|
||||||
spacer = '{0}{1}{0}'.format('+', '+'.join(['-' * (field_width * sz) for _ in range(sz)]))
|
fmt = ''
|
||||||
for line in range(self.row_size):
|
for (y,x) in self.all_squares:
|
||||||
chunks = []
|
if x == 0:
|
||||||
for i in range(sz):
|
if y % self.size == 0:
|
||||||
fields = []
|
if y != 0:
|
||||||
for j in range(sz):
|
fmt += '\n'
|
||||||
idx = line * self.size + i * sz + j
|
fmt += '{spacer}'
|
||||||
if idx in self._clues:
|
fmt += '\n'
|
||||||
bold = BOLD_SEQUENCE
|
|
||||||
unbold = UNBOLD_SEQUENCE
|
if x % self.size == 0:
|
||||||
else:
|
fmt += '|'
|
||||||
bold = unbold = ''
|
|
||||||
fields.append('{bold}{{board[{i}]:^{{width}}}}{unbold}'.format(i=idx, bold=bold, unbold=unbold))
|
idx = self._xy_to_idx(x,y)
|
||||||
chunks.append(''.join(fields))
|
if idx in self._clues:
|
||||||
if (line % sz) == 0:
|
bold = BOLD_SEQUENCE
|
||||||
lines.append(spacer)
|
unbold = UNBOLD_SEQUENCE
|
||||||
lines.append('{0}{1}{0}'.format('|', '|'.join(chunks)))
|
else:
|
||||||
lines.append(spacer)
|
bold = unbold = ''
|
||||||
fmt = '\n'.join(lines)
|
fmt += '{bold}{{board[{i}]:^{{width}}}}{unbold}'.format(i=idx, bold=bold, unbold=unbold)
|
||||||
str_board = [str(n) if n != 0 else ' ' for n in self._board]
|
|
||||||
out = fmt.format(board=str_board, width=field_width)
|
if x == (self.row_size - 1):
|
||||||
return out
|
fmt += '|'
|
||||||
|
fmt += '\n{spacer}'
|
||||||
|
|
||||||
|
return fmt.format(board=[str(i) if i != 0 else ' ' for i in self._board], spacer=spacer, width=field_width)
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue