Skip to content

Commit

Permalink
🕹️ simple gamestate managment
Browse files Browse the repository at this point in the history
  • Loading branch information
DasLixou committed May 9, 2022
1 parent 428a443 commit 95f3fcb
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/main/kotlin/cc/lixou/stracciatella/game/Game.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ import java.util.*

abstract class Game {

protected val players = ArrayList<Player>()
protected lateinit var instance: Instance
protected val uuid: UUID = UUID.randomUUID()
protected val eventNode =
val players = ArrayList<Player>()
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)
Expand All @@ -26,6 +27,8 @@ abstract class Game {
Manager.globalEvent.addChild(eventNode)
}

protected fun <T : Enum<*>> initGameState(defaultState: T) = GameState(this, defaultState)

/**
* @param newPlayers the players that should join
* @return false if game is full, then creates new instance
Expand Down
44 changes: 44 additions & 0 deletions src/main/kotlin/cc/lixou/stracciatella/game/GameState.kt
Original file line number Diff line number Diff line change
@@ -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<T : Enum<*>>(
private val game: Game,
private val defaultState: T,
val parentEventNode: EventNode<*> = game.eventNode
) {

private val eventNodes = mutableMapOf<T, EventNode<in InstanceEvent>>()

var state: T = defaultState
set(value) {
eventNodes[field]?.let {
@Suppress("unchecked_cast")
parentEventNode.removeChild(it as EventNode<out Nothing>)
}
eventNodes[value]?.let {
@Suppress("unchecked_cast")
parentEventNode.addChild(it as EventNode<out Nothing>)
}
field = value
}

fun eventNode(ofState: T): EventNode<in InstanceEvent> =
eventNodes.getOrPut(ofState) { generateNode(ofState).also { if (state == ofState) register(it) } }

private fun generateNode(ofState: T): EventNode<in InstanceEvent> =
EventNode.type("${game.javaClass.simpleName}-${game.uuid}-${state.name}", EventFilter.INSTANCE) { _, _ ->
this@GameState.state == ofState
}

private fun register(node: EventNode<in InstanceEvent>?) {
node?.let {
@Suppress("unchecked_cast")
parentEventNode.addChild(it as EventNode<out Nothing>)
}
}


}

0 comments on commit 95f3fcb

Please sign in to comment.