Sudoku
Sudoku
import sys
import time
from solver import Cell, Sudoku
pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Sudoku')
class RectCell(pygame.Rect):
'''
A class built upon the pygame Rect class used to represent individual cells in
the game.
This class has a few extra attributes not contained within the base Rect class.
'''
def create_cells():
'''Creates all 81 cells with RectCell class.'''
cells = [[] for _ in range(9)]
return cells
def draw_grid():
'''Draws the major and minor grid lines for Sudoku.'''
# Draw minor grid lines
lines_drawn = 0
pos = buffer + major_grid_size + cell_size
while lines_drawn < 6:
pygame.draw.line(screen, black, (pos, buffer),
(pos, width-buffer-1), minor_grid_size)
pygame.draw.line(screen, black, (buffer, pos),
(width-buffer-1, pos), minor_grid_size)
return button
def check_sudoku(sudoku):
'''
Takes a complete instance of Soduku and
returns whether or not the solution is valid.
'''
# Ensure all cells are filled
if sudoku.get_empty_cell():
raise ValueError('Game is not complete')
# Will hold values for each row, column, and box
row_sets = [set() for _ in range(9)]
col_sets = [set() for _ in range(9)]
box_sets = [set() for _ in range(9)]
def play():
'''Contains all the functionality for playing a game of Sudoku.'''
easy = [
[0, 0, 0, 9, 0, 0, 0, 3, 0],
[3, 0, 6, 0, 2, 0, 0, 4, 0],
[2, 0, 4, 0, 0, 3, 1, 0, 6],
[0, 7, 0, 0, 5, 1, 0, 8, 0],
[0, 3, 1, 0, 6, 0, 0, 5, 7],
[5, 0, 9, 0, 0, 0, 6, 0, 0],
[4, 1, 0, 0, 0, 2, 0, 7, 8],
[7, 6, 3, 0, 0, 5, 4, 0, 0],
[9, 2, 8, 0, 0, 4, 0, 0, 1]
]
game = Sudoku(easy)
cells = create_cells()
active_cell = None
solve_rect = pygame.Rect(
buffer,
height-button_height - button_border*2 - buffer,
button_width + button_border*2,
button_height + button_border*2
)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(white)
# Draw board
draw_board(active_cell, cells, game)
# Create buttons
reset_btn = draw_button(
width - buffer - button_border*2 - button_width,
height - button_height - button_border*2 - buffer,
button_width,
button_height,
button_border,
inactive_btn,
black,
'Reset'
)
solve_btn = draw_button(
width - buffer*2 - button_border*4 - button_width*2,
height - button_height - button_border*2 - buffer,
button_width,
button_height,
button_border,
inactive_btn,
black,
'Visual Solve'
)
# Update screen
pygame.display.flip()
if __name__ == '__main__':
play()