Handle AI Turns with Coroutines and First-Class Functions

Kotlin and Android Development featuring Jetpack — by Michael Fazio (36 / 125)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Create Turn Summary Text | TOC | Summary and Next Steps 👉

We’re going to add the ability for the app to run one (or more) of the players in the game and give users the option to have Penny Drop be a single-(human-)player game. When the AI is playing, we’re going to disable both the Roll and Pass buttons and have the app start rolling/passing on its own. A handy way to trigger this is from the updateFromGameHandler function once everything else is updated. Add a call to playAITurn near the end of that function:

​ ​if​ (!result.isGameOver && result.currentPlayer?.isHuman == ​false​) {
​ canRoll.value = ​false​
​ canPass.value = ​false​
» playAITurn()
​ }

We’re only going to have a player be run by the app if we’re sure it’s not human. We’re using the same approach we did earlier with our LiveData, where we compare against false as result.currentPlayer?.isHuman is a Boolean? rather than a Boolean.

The playAITurn function in the GameViewModel is our first example of Kotlin coroutines. However, I don’t want to get into them too much here since there’s too much to discuss in one section. If you want to see more, we’re going to use them again in Chapter 5, Persist Game Data with Room, and especially in Chapter 10, Load and Save Data with Coroutines and Room. For the sake of…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.