Game loop in Kotlin

To start the game, the first thing I need is a game loop. Kotlin’s timers, unfortunately, lack some clear documentation. The first thing I noticed was that the timer functionality is, once again, just a wrapper of Java timer and not available for Javascript. This really makes me think I’m using a second-class version of java rather than a cross platform library, but perhaps that’s the documentation leaving a bad impression.

Instead for timers you ultimately write code that is directly analogous to the javascript underneath; you use setInterval or setTimeout. I couldn’t find a tutorial for using it online, and the documentation has no examples in it.

Mini Tutorial: Using setInterval in Kotlin as a Timer

To use a timer in Kotlin, we first need to find a Window object. I used the defaultView property of the document:

val window = document.defaultView

This may be null, so you need to either check for null directly or use the null conditional dot operator. From this you need to use the setTimeout / setInterval functions. The final part of the puzzle was that this needs to be a lambda function, not just a function name. This can be done simply by wrapping the call in braces as there are no inputs or outputs. So to call my update function every second, I use the following:

window?.setInterval(fun() { update() }, 1000)

Back to the Game Loop

This does seem a bit basic, but that gets me to where I want – a function called every cycle (I use 200ms cycles, as 1 second is a bit slow).

I’ve already created a Player class with a Ticks field, and initialised it as a global variable. There’s only ever one player. All I’m going to do in my game is count up the ticks, for now:

fun update() {
    document.getElementById("main")?.innerHTML = CurrentPlayer.Ticks.toString()

And here we are, I’ve got a basic loop that is called repeatedly. Next step: add in a resource tracking system and implement the actors and actions that I had in the Elm version. I’m hoping these things will be written in a way that can take advantage of Kotlin’s cross-platform abilities, so I want to distance them from the Javascript setInterval call here.

Leave a Reply

Your email address will not be published. Required fields are marked *