diff --git a/src/main/kotlin/ru/dbotthepony/mc/otm/core/TimerQueue.kt b/src/main/kotlin/ru/dbotthepony/mc/otm/core/TimerQueue.kt index a9d1ed54f..8f357be6a 100644 --- a/src/main/kotlin/ru/dbotthepony/mc/otm/core/TimerQueue.kt +++ b/src/main/kotlin/ru/dbotthepony/mc/otm/core/TimerQueue.kt @@ -1,38 +1,45 @@ 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() 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 + for (value in iterator) { + if (value.ringAt == ringAt) { + hit = true + iterator.add(this) break - } else if (next.next == null) { - next.next = this - this.prev = next + } else if (value.ringAt > ringAt) { + if (iterator.hasPrevious()) { + iterator.previous() + iterator.add(this) + } else { + list.addFirst(this) + } + + hit = true break - } else { - next = next.next } } + + 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() } -} \ No newline at end of file +}