Simple User Interaction - Buttons
Let´s add some user interaction. A simple button which can be used to pause and resume the game.
As this is UI specific code we implement it in the Android, and the iOS project without any shared code at all.
However, as we already have the Game class as shared code which provides this “Business Logic” the implementation is simple.
class MainActivity : AppCompatActivity() {
…
override fun onCreate(savedInstanceState: Bundle?) {
…
}
…
override
fun onOptionsItemSelected(item: MenuItem?): Boolean {
return when (item?.itemId) {
R.id.action_pause_resume -> {
if (game.running) {
item.icon = resumeIcon
game.pause()
} else {
item.icon = pauseIcon
game.resume()
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
struct ContentView: View {
let game = Game()
@State var pauseResumeButtonText = "Pause"
@ObservedObject var boardStore = BoardStore()
var body: some View {
NavigationView {
BoardView(board: $boardStore.board)
.navigationBarItems(trailing:
Button(self.pauseResumeButtonText) {
if self.game.running {
self.game.pause()
self.pauseResumeButtonText = "Resume"
} else {
self.game.resume()
self.pauseResumeButtonText = "Pause"
}
}
)
}
.onAppear(perform: {
self.boardStore.board = self.game.board
self.game.afterNextGenerationCalculated = {
self.boardStore.calculateNextGeneration()
}
self.game.resume()
})
.onDisappear(perform: {
self.game.pause()
})
}
}