Last active
January 27, 2018 14:33
-
-
Save tomaszrykala/edbf4320a4fd35b344f7d58d639cba36 to your computer and use it in GitHub Desktop.
GameController.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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