Implementing the Game Logic

The rest of the code in Game.java concerns itself with the logic of the game, in particular with determining which are and aren't valid moves according to the rules. The setTileIfValid() method is a key part of that. Given an x and y position and the new value of a tile, it changes the tile only if the value provided is valid.

protected boolean setTileIfValid(int x, int y, int value) { int tiles[] = getUsedTiles(x, y); if (value != 0) {

for (int tile : tiles) { if (tile == value) return false;

setTile(x, y, value); calculateUsedTiles(); return true;

To detect valid moves, we create an array for every tile in the grid. For each position, it keeps a list of filled-in tiles that are currently visible from that position. If a number appears on the list, then it won't be valid for the current tile. The getUsedTiles() method retrieves that list for a given tile position:

protected int[] getUsedTiles(int x, int y) { return used[x][y];

The array of used tiles is somewhat expensive to compute, so we cache the array and recalculate it only when necessary by calling calculate-UsedTiles():

private void calculateUsedTiles() { for (int x = 0; x < 9; x++) { for (int y = 0; y < 9; y++) {

used[x][y] = calculateUsedTiles(x, y); // Log.d(TAG, "used[" + x +"]["+ y + "] = " // + toPuzzleString(used[x][y]));

calculateUsedTiles() simply calls calculateUsedTiles(x, y) on every position in the nine-by-nine grid:

Line 1 private int[] calculateUsedTiles(int x, int y) {

- int c[] = new int[9]; // horizontal for (int i =0; i <9; i++) { 5 if (i == y)

- continue;

- continue;

return c1;

We start with an array of nine zeros. On line 4, we check all the tiles on the same horizontal row as the current tile, and if a tile is occupied, we stuff its number into the array.

On line 12, we do the same thing for all the tiles on the same vertical column, and on line 20, we do the same for tiles in the three-by-three block.

The last step, starting at line 32, is to compress the zeros out of the array before we return it. We do this so that array.length can be used to quickly tell how many used tiles are visible from the current position.

0 0