Walkthrough of setting up our Sudoku Board using Tkinter.
When thinking of Sudoku, we know that we must have some logic to automatically check the math of our input numbers to see if every horizontal row and vertical column, as well 3x3 box, contains all digits from 1 through 9. This is the logic of the game.
When running our Sudoku game, we want to take in arguments of the level of came that we want to play (n00b, l33t, or debug), as well as the board number we wish to play (if any). We will need to have a function that parses these arguments.
Of course, we’ll need a visual interface to play the game - a GUI (Graphical User Interface). We’ll need to create a separate class for drawing our Sudoku board, and we will use the Tkinter library.
Last, we’ll write some tests to make sure we’ve covered the initialization of the Sudoku board, the logic of the Sudoku, etc.
Now we’ll actually setup the board that the user will interact with. Since we are using Tkinter, we’ll need to import some objects to help us draw the board. We’ll also be using the argparse
module. Both modules are already within Python’s standard library, so no need to pip install
them beforehand.
1 2 | import argparse
from Tkinter import Tk, Canvas, Frame, Button, BOTH, TOP, BOTTOM
|
Let’s define some global variables in which we will use later on:
1 2 3 4 5 6 7 | import argparse
from Tkinter import Tk, Canvas, Frame, Button, BOTH, TOP, BOTTOM
BOARDS = ['debug', 'n00b', 'l33t', 'error'] # Available sudoku boards
MARGIN = 20 # Pixels around the board
SIDE = 50 # Width of every board cell.
WIDTH = HEIGHT = MARGIN * 2 + SIDE * 9 # Width and height of the whole board
|
The BOARDS
is the available list of boards for the user to choose from. The other global variables will be used for drawing the user interface.
We define our own Exception because we want to create error handling that’s specific to our Sudoku applcation, rather than file I/O exceptions, or database exceptions, etc. This is all we need to create our own exception:
1 2 3 4 5 | class SudokuError(Exception):
"""
An application specific error.
"""
pass
|
In the future, we will use this error class and pass our own error message when we try to catch any errors when creating our Sudoku game.
Simple enough! Let’s move onto setting up the game logic.