Miscellaneous

Here are a few other utility functions and variables that round out the implementation. easyPuzzle, mediumPuzzle, and hardPuzzle are our hard-coded Sudoku puzzles for easy, medium, and hard difficulty levels, respectively.

Download Sudokuv2/src/org/example/sudoku/Game.java

private final String easyPuzzle = "360000000004230800000004200" + "070460003820000014500013020" + "001900000007048300000000045"; private final String mediumPuzzle = "650000070000506000014000005" + "007009000002314700000700800" + "500000630000201000030000097"; private final String hardPuzzle = "009000000080605020501078000" + "000000700706040102004000000" + "000720903090301080000000600";

getPuzzle( ) simply takes a difficulty level and returns a puzzle:

Download Sudokuv2/src/org/example/sudoku/Game.java

private int[] getPuzzle(int diff) { String puz;

// TODO: Continue last game switch (diff) { case DIFFICULTY_HARD: puz = hardPuzzle; break;

case DIFFICULTY_MEDIUM: puz = mediumPuzzle; break; case DIFFICULTY_EASY: default:

puz = easyPuzzle; break;

return fromPuzzleString(puz);

Later we'll change getPuzzle() to implement a continue function.

toPuzzleString() converts a puzzle from an array of integers to a string. framPuzzleStringO does the opposite.

Download Sudokuv2/src/org/example/sudoku/Game.java

static private String toPuzzleString(int[] puz) { StringBuilder buf = new StringBuilder(); for (int element : puz) { buf.append(element);

return buf.toString();

static protected int[] fromPuzzleString(String string) { int[] puz = new int[string.length()]; for (int i =0; i < puz.length; i++) { puz[i] = string.charAt(i) - '0';

return puz;

The getTile() method takes x and y positions and returns the number currently occupying that tile. If it's zero, that means the tile is blank.

Download Sudokuv2/src/org/example/sudoku/Game.java

private int getTile(int x, int y) {

private void setTile(int x, int y, int value) { puzzle[y * 9 + x] = value;

getTileStringO is used when displaying a tile. It will return either a string with the value of the tile or an empty string if the tile is blank.

Download Sudokuv2/src/org/example/sudoku/Game.java

protected String getTileString(int x, int y) { int v = getTile(x, y); if (v == 0)

return ""; else return String.valueOf(v);

Once all these pieces are in place, you should have a playable Sudoku game. Give it a try to verify it works. As with any code, though, there is room for improvement.

0 0

Post a comment