jules0707

Game2048Initializer.kt

Nov 19th, 2021 (edited)
704
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.06 KB | None | 0 0
  1. package games.game2048
  2.  
  3. import board.Cell
  4. import board.GameBoard
  5. import kotlin.random.Random
  6.  
  7. interface Game2048Initializer<T> {
  8.     /*
  9.      * Specifies the cell and the value that should be added to this cell.
  10.      */
  11.     fun nextValue(board: GameBoard<T?>): Pair<Cell, T>?
  12. }
  13.  
  14. object RandomGame2048Initializer : Game2048Initializer<Int> {
  15.     private fun generateRandomStartValue(): Int =
  16.         if (Random.nextInt(10) == 9) 4 else 2
  17.  
  18.     /*
  19.      * Generate a random value and a random cell among free cells
  20.      * that given value should be added to.
  21.      * The value should be 2 for 90% cases, and 4 for the rest of the cases.
  22.      * Use the 'generateRandomStartValue' function above.
  23.      * If the board is full return null.
  24.      */
  25.    override fun nextValue(board: GameBoard<Int?>): Pair<Cell, Int>? {
  26.         return if (board.all { it != null }) {
  27.             null // no more space available
  28.         } else {
  29.             val c = board.filter { it == null }.random()
  30.             return Pair( c!!, generateRandomStartValue())
  31.         }
  32.     }
  33. }
  34.  
  35.  
Add Comment
Please, Sign In to add comment