Implementing ViewHandler

As blocks will be moving along the fields in intervals with a constant time delay, we need a means of putting the thread that handles the movement of blocks to sleep and waking the thread to make a block motion after a period of time. A good way to take care of this requirement is to use a handler to process message delay requests and continue message handling after the delay has completed. Putting this in more direct terms, according to Android's documentation, the handler allows you to send and process Message objects associated with a thread's MessageQueue. Every handler instance is associated with a thread and the thread's message queue.

ViewHandler is a custom handler we will implement for TetrisView that caters to the view’s message-sending and processing needs. As ViewHandler is subclass of Handler, we must extend Handler and add our necessary behavior to the ViewHandler class.

Add the following VieHandler class as a private class within TetrisView:

private class ViewHandler(private val owner: TetrisView) : Handler() {

override fun handleMessage(message: Message) {
if (message.what == 0) {
if (owner.model != null) {
if (owner.model!!.isGameOver()) {
owner.model?.endGame()
Toast.makeText(owner.activity, "Game over",
Toast.LENGTH_LONG).show();
}
if (owner.model!!.isGameActive()) {
owner.setGameCommandWithDelay(AppModel.Motions.DOWN)
}
}
}
}

fun sleep(delay: Long) {
this.removeMessages(0)
sendMessageDelayed(obtainMessage(0), delay)
}
}

The ViewHandler class takes an instance of TetrisView as an argument in its constructor. ViewHandler overrides the handleMessage() function existing in its superclass class. handleMessage() checks that the what message was sent. The what is an integer value denoting the message sent. If what is equal to 0, and the instance—owner—of TetrisView passed possesses a model that is not equal to 0, some statuses of the game are checked. If the game is over, it will call endGame() of AppModel function and show a popup alerting the player that the game is over. If the game is in its active state, a down motion is fired.

The sleep() method simply removes any previously sent message and sends a new message with a delay specified by the delay argument.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.99