Create GameHandler

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 4 Update LiveData with Conditional Game Logic | TOC | Start a Game 👉

As I mentioned earlier, GameHandler is where all our game logic is going to live. In this way, we greatly simplify what needs to be done within the GameViewModel and avoid causing too much bloat in that class. Given that GameHandler has no state of its own, we can define it as a Kotlin object declaration rather than a class. Similar to companion objects we saw in Create the AI Class, object declarations are singleton instances. They look very similar to classes but instead use the object keyword, as you’ll see.

In our case, GameHandler will be an object declaration with only functions (as it will not be holding any state) that we can use to run our game. Create that object (under the game package) with some empty functions:

​ ​package​ ​dev.mfazio.pennydrop.game​

​ ​object​ GameHandler {

​ ​fun​ ​roll​(
​ players: List<Player>,
​ currentPlayer: Player,
​ slots: List<Slot>
​ ): TurnResult { }

​ ​fun​ ​pass​(
​ players: List<Player>,
​ currentPlayer: Player
​ ): TurnResult { }

​ ​private​ ​fun​ ​rollDie​(sides: Int = 6) { ... }

​ ​private​ ​fun​ ​nextPlayer​(
​ players: List<Player>,
​ currentPlayer: Player
​ ): Player { }
​ }

You can see the methods we’ll be implementing in this section, which will then be…

--

--

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.