summaryrefslogtreecommitdiff
path: root/src/main/kotlin/io/dico/parcels2/listener/ParcelEntityTracker.kt
blob: 198e0e7b84d902174bae4fcac2d080fc73b4492e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package io.dico.parcels2.listener

import io.dico.parcels2.Parcel
import io.dico.parcels2.ParcelProvider
import io.dico.parcels2.util.ext.editLoop
import org.bukkit.entity.Entity

class ParcelEntityTracker(val parcelProvider: ParcelProvider) {
    val map = mutableMapOf<Entity, Parcel?>()

    fun untrack(entity: Entity) {
        map.remove(entity)
    }

    fun track(entity: Entity, parcel: Parcel?) {
        map[entity] = parcel
    }

    /*
     * Tracks entities. If the entity is dead, they are removed from the collection.
     * If the entity is found to have left the parcel it was created in, it will be removed from the world and from the list.
     * If it is still in the parcel it was created in, and it is on the ground, it is removed from the list.
     *
     * Start after 5 seconds, run every 0.25 seconds
     */
    fun tick() {
        map.editLoop { entity, parcel ->
            if (entity.isDead) {
                remove(); return@editLoop
            }

            if (parcel != null && parcel.hasBlockVisitors) {
                remove()

                val newParcel = parcelProvider.getParcelAt(entity.location)
                if (newParcel !== parcel && (newParcel == null || !newParcel.hasBlockVisitors)) {
                    entity.remove()
                }

                return@editLoop
            }

            val newParcel = parcelProvider.getParcelAt(entity.location)
            if (newParcel !== parcel && (newParcel == null || !newParcel.hasBlockVisitors)) {
                remove()
                entity.remove()
            }
        }
    }

    fun swapParcels(parcel1: Parcel, parcel2: Parcel) {
        map.editLoop { ->
            if (value === parcel1) {
                value = parcel2
            } else if (value === parcel2) {
                value = parcel1
            }
        }
    }

}