Fix timer queue

This commit is contained in:
DBotThePony 2022-10-02 12:48:53 +07:00
parent 4212345bd8
commit 2e93dc7b2c
Signed by: DBot
GPG Key ID: DCC23B5715498507

View File

@ -1,37 +1,44 @@
package ru.dbotthepony.mc.otm.core package ru.dbotthepony.mc.otm.core
import java.util.LinkedList
class TimerQueue { class TimerQueue {
private var ticks = 0 private var ticks = 0
private var head: Timer? = null private val list = LinkedList<Timer>()
inner class Timer(val timerTicks: Int, val runnable: Runnable) { inner class Timer(val timerTicks: Int, val runnable: Runnable) {
val ringAt = ticks + timerTicks val ringAt = ticks + timerTicks
var finished = false var finished = false
private set private set
var next: Timer? = null
var prev: Timer? = null
init { init {
if (head == null) { if (list.isEmpty()) {
head = this list.addLast(this)
} else { } else {
var next = head val iterator = list.listIterator()
var hit = false
while (next != null) { for (value in iterator) {
if (next.ringAt >= this.ringAt) { if (value.ringAt == ringAt) {
next.prev?.next = this hit = true
this.prev = next.prev iterator.add(this)
next.prev = this
this.next = next
break
} else if (next.next == null) {
next.next = this
this.prev = next
break break
} else if (value.ringAt > ringAt) {
if (iterator.hasPrevious()) {
iterator.previous()
iterator.add(this)
} else { } else {
next = next.next list.addFirst(this)
} }
hit = true
break
}
}
if (!hit) {
list.addLast(this)
} }
} }
} }
@ -46,14 +53,12 @@ class TimerQueue {
fun tick() { fun tick() {
ticks++ ticks++
var head = head while (list.isNotEmpty()) {
val head = list.first
while (head != null) {
if (head.ringAt <= ticks) { if (head.ringAt <= ticks) {
head.execute() head.execute()
head = head.next list.removeFirst()
head?.prev = null
this.head = head
} else { } else {
break break
} }
@ -62,6 +67,6 @@ class TimerQueue {
fun clear() { fun clear() {
ticks = 0 ticks = 0
head = null list.clear()
} }
} }