diff --git a/src/main/kotlin/cc/lixou/stracciatella/game/Game.kt b/src/main/kotlin/cc/lixou/stracciatella/game/Game.kt index 632e1df..6b44bc2 100644 --- a/src/main/kotlin/cc/lixou/stracciatella/game/Game.kt +++ b/src/main/kotlin/cc/lixou/stracciatella/game/Game.kt @@ -10,10 +10,11 @@ import java.util.* abstract class Game { - protected val players = ArrayList() - protected lateinit var instance: Instance - protected val uuid: UUID = UUID.randomUUID() - protected val eventNode = + val players = ArrayList() + lateinit var instance: Instance + protected set + val uuid: UUID = UUID.randomUUID() + val eventNode = EventNode.type("${this.javaClass.simpleName}-${uuid}", EventFilter.INSTANCE) { event, instance -> if (event is PlayerEvent) { return@type players.contains(event.player) @@ -26,6 +27,8 @@ abstract class Game { Manager.globalEvent.addChild(eventNode) } + protected fun > initGameState(defaultState: T) = GameState(this, defaultState) + /** * @param newPlayers the players that should join * @return false if game is full, then creates new instance diff --git a/src/main/kotlin/cc/lixou/stracciatella/game/GameState.kt b/src/main/kotlin/cc/lixou/stracciatella/game/GameState.kt new file mode 100644 index 0000000..c37cfac --- /dev/null +++ b/src/main/kotlin/cc/lixou/stracciatella/game/GameState.kt @@ -0,0 +1,44 @@ +package cc.lixou.stracciatella.game + +import net.minestom.server.event.EventFilter +import net.minestom.server.event.EventNode +import net.minestom.server.event.trait.InstanceEvent + +class GameState>( + private val game: Game, + private val defaultState: T, + val parentEventNode: EventNode<*> = game.eventNode +) { + + private val eventNodes = mutableMapOf>() + + var state: T = defaultState + set(value) { + eventNodes[field]?.let { + @Suppress("unchecked_cast") + parentEventNode.removeChild(it as EventNode) + } + eventNodes[value]?.let { + @Suppress("unchecked_cast") + parentEventNode.addChild(it as EventNode) + } + field = value + } + + fun eventNode(ofState: T): EventNode = + eventNodes.getOrPut(ofState) { generateNode(ofState).also { if (state == ofState) register(it) } } + + private fun generateNode(ofState: T): EventNode = + EventNode.type("${game.javaClass.simpleName}-${game.uuid}-${state.name}", EventFilter.INSTANCE) { _, _ -> + this@GameState.state == ofState + } + + private fun register(node: EventNode?) { + node?.let { + @Suppress("unchecked_cast") + parentEventNode.addChild(it as EventNode) + } + } + + +} \ No newline at end of file