Skip to content

Instantly share code, notes, and snippets.

@tomaszrykala
Last active January 27, 2018 14:33
Show Gist options
  • Save tomaszrykala/edbf4320a4fd35b344f7d58d639cba36 to your computer and use it in GitHub Desktop.
Save tomaszrykala/edbf4320a4fd35b344f7d58d639cba36 to your computer and use it in GitHub Desktop.
GameController.kt
class GameController(private val abcButtons: AbcButtonsController,
private val abcLeds: AbcLedsController,
private val digiDisplay: DigiDisplayController,
private val timer: Timer,
private val game: Game) : AbcButton.Listener {
private val closeables: List<AutoCloseable> = listOf(abcButtons, abcLeds, digiDisplay)
init { abcButtons.setListener(this) }
fun startRound() {
showStarter()
timer.start()
start()
}
override fun onAbcButton(abcButton: AbcButton) {
if (!game.isStarted) {
startNewRound()
} else {
val onPad = game.onPad(abcButton)
abcButtons.setLastPressed(abcButton)
if (!onPad) {
start()
} else {
abcLeds.lightFor(abcButton)
if (game.isWon) {
stop()
}
}
}
}
private fun showStarter() {
digiDisplay.apply {
(3 downTo 1).forEach {
displayBlocking(String.format("%d...", it), 500)
}.also {
displayBlocking(" GO ", 500)
}
}
}
private fun start() {
abcButtons.apply {
setLastPressed(null)
enable()
}
abcLeds.reset()
game.start()
}
private fun stop() {
timer.stop()
abcButtons.disable()
digiDisplay.apply {
displayBlocking("WIN ", TimeUnit.SECONDS.toMillis(2).toInt())
display(digiDisplay.counter)
}
}
private fun startNewRound() {
startRound()
}
fun onDestroy() {
try {
closeables.forEach { it.close() }
game.onDestroy()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment