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