Entering Numbers

To handle keyboard input, we just add a few more cases to the onKey-Down() method for the numbers 0 through 9 (0 or space means erase the number).

Optimizing Refreshes

In an earlier version of this example, I invalidated the entire screen whenever the cursor was moved. Thus, on every key press, the whole puzzle had to be redrawn. This caused it to lag noticeably Switching the code to invalidate only the smallest rectangles that changed made it run much faster.

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

case KeyEvent.KEYCODE_' case KeyEvent.KEYCODE_: case KeyEvent.KEYCODE_ case KeyEvent.KEYCODE_ case KeyEvent.KEYCODE_ case KeyEvent.KEYCODE_ case KeyEvent.KEYCODE_ case KeyEvent.KEYCODE_' case KeyEvent.KEYCODE_ case KeyEvent.KEYCODE_ case KeyEvent.KEYCODE_ case KeyEvent.KEYCODE_ case KeyEvent.KEYCODEJ game.showKeypadOrEr break;

SPACE: setSelectedTile(O) 1: setSelectedTile(l) 2: setSe1ectedTi1e(2) 3: setSe1ectedTi1e(3) 4: setSe1ectedTi1e(4) 5: setSe1ectedTi1e(5) 6: setSe1ectedTi1e(6) 7: setSe1ectedTi1e(7) setSe1ectedTi1e(8) 9: setSe1ectedTi1e(9) ENTER:

DPAD_CENTER: ror(se1X, selY);

break break break break break break break break break break

To support the D-pad, we check for the Enter or center D-pad button in onKeyDown() and have it pop up a keypad that lets the user select which number to place.

For touch, we override the onTouchEvent() method and show the same keypad, which will be defined later:

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

@Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() != MotionEvent.ACTION_DOWN) return super.onTouchEvent(event);

(int) (event.getY() / height)); game.showKeypadOrError(selX, selY); Log.d(TAG, "onTouchEvent: x " + selX + return true;

Ultimately, all roads will lead back to a call to setSelectedTile( ) to change the number on a tile:

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

public void setSelectedTile(int tile) {

if (game.setTileIfValid(selX, selY, tile))

// Number is not valid for this tile Log.d(TAG, "setSelectedTile: invalid: "

The showKeypadOrError() and setTileIfValid() methods will be defined in Section 4.4, The Rest of the Story, on page 93.

Note the call to invalidated with no parameters. That marks the whole screen as dirty, which violates my own advice earlier! However, in this case, it's necessary because any new numbers added or removed might change the hints that we are about to implement in the next section.

0 0

Post a comment