Reputation: 11
i am trying to create a game similar to the classic Simon Says. I have an array of buttons placed on the screen, and for showing the user the sequence that he must introduce I have thought of toggling them in order. Im new to android and Libgdx and looking for a solution, I have found things similar to this:
for (i in 0 until array.size) {
array[i].toggle()
Timer.schedule(object : Timer.Task() {
override fun run() {
array[i].toggle()
}
}, delay)
}
Since timer works with threads, or at least that is what I think, this is not working properly, any suggestion?
Thanks in advance.
Upvotes: 1
Views: 163
Reputation: 93769
Timer is the correct way to run a future task without blocking the rendering thread. You may need to be more specific about "not working properly" because I don't see any issues with the code shown. Problems could arise if the array were mutated during the delay.
However, since the delay is the same for each item, it would be much simpler and go easier on the garbage collector if you make a single timer task that iterates the array, like this:
for (item in array) {
item.toggle()
}
Timer.schedule(object : Timer.Task() {
override fun run() {
for (item in array) {
item.toggle()
}
}
}, delay)
Or more concisely:
array.forEach(MyClass::toggle)
Timer.schedule(object : Timer.Task() {
override fun run() = array.forEach(MyClass::toggle)
}, delay)
I highly recommend using the libktx library if you're using libGDX with Kotlin, so you can write clearer code in a Kotlin sytle. For example, using libktx async, the above code becomes:
array.forEach(MyClass::toggle)
schedule(delay) {
array.forEach(MyClass::toggle)
}
Upvotes: 2