Skip to content

Instantly share code, notes, and snippets.

@monkey-codes
Created June 9, 2023 23:09
Show Gist options
  • Select an option

  • Save monkey-codes/83fdec217e098efffde080d673d1b8af to your computer and use it in GitHub Desktop.

Select an option

Save monkey-codes/83fdec217e098efffde080d673d1b8af to your computer and use it in GitHub Desktop.
Game smart constructor
typealias State = List<List<Symbol>>
fun State.toGame(): Game = Game.of(this)
...
sealed class Game(val state: State) {
companion object {
...
fun of(state: State): Game {
val winningCells =
(rows + columns + diagonals)
.map { coordinates -> state.values(coordinates) }
.firstOrNull { it.allSymbolsMatch(CROSS) || it.allSymbolsMatch(NOUGHT) }
.orEmpty()
val isDrawn by lazy { state.all { it.none { symbol -> symbol == BLANK } } }
return when {
winningCells.isNotEmpty() -> Won(state, winningCells.first().second)
isDrawn -> Draw(state)
else -> InProgress(state)
}
}
...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment