Implementing a game status check

In this section, we will work on functions that will help us figure out the winner of our game.

Start by adding the following function to the MainActivity class:

private fun isBoardFull(gameBoard:Array<CharArray>): Boolean {
for (i in 0 until gameBoard.size) {
for (j in 0 until gameBoard[i].size) {
if(gameBoard[i][j] == ' ') {
return false
}
}
}
return true
}

This function is used to check whether the game board is full. Here, we go through all the cells on the board and return false if any of them are empty. If none of the cells are empty, we return true

Next, add the isWinner() method:

private fun isWinner(gameBoard:Array<CharArray>, w: Char): Boolean {
for (i in 0 until gameBoard.size) {
if (gameBoard[i][0] == w && gameBoard[i][1] == w &&
gameBoard[i][2] == w) {
return true
}

if (gameBoard[0][i] == w && gameBoard[1][i] == w &&
gameBoard[2][i] == w) {
return true
}
}
if ((gameBoard[0][0] == w && gameBoard[1][1] == w && gameBoard[2]
[2] == w) ||
(gameBoard[0][2] == w && gameBoard[1][1] == w &&
gameBoard[2][0] == w)) {
return true
}
return false
}

Here, you check whether the character passed is the winner. The character is the winner if it appears three times in either a horizontal, vertical or diagonal row. 

Now add the checkGameStatus() function:

private fun checkGameStatus() {
var state: String? = null
if(isWinner(gameBoard, 'X')) {
state = String.format(resources.getString(R.string.winner), 'X')
} else if (isWinner(gameBoard, 'O')) {
state = String.format(resources.getString(R.string.winner), 'O')
} else {
if (isBoardFull(gameBoard)) {
state = resources.getString(R.string.draw)
}
}

if (state != null) {
turnTextView?.text = state
val builder = AlertDialog.Builder(this)
builder.setMessage(state)
builder.setPositiveButton(android.R.string.ok, { dialog, id ->
startNewGame(false)

})
val dialog = builder.create()
dialog.show()

}
}

The preceding function makes use of the isBoardFull() and isWinner() functions to determine who the winner of the game is. If neither X nor O has won and the board is full, then it's a draw. Show an alert displaying either the winner of the game or a message telling the user that the game was a draw.

Next, add a call to checkGameStatus() at the end of the cellClickListener() function.

Build and run:

Lastly, implement the functionality for the FloatingActionButton. In the onCreate() function, replace the following:

fab.setOnClickListener { view -> HelloKotlin("Get ready for a fun game of Tic Tac Toe").displayKotlinMessage(view) }

 Replace it with:

fab.setOnClickListener {startNewGame(false)}

Again, build and run. Now, when you click the FloatingActionButton, the board will be cleared for you to restart the game:

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

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