Skip to content

Commit 834097f

Browse files
committed
Refactor SelectorNode and SequenceNode to use vararg for children
1 parent f897b78 commit 834097f

1 file changed

Lines changed: 19 additions & 6 deletions

File tree

korge-fleks/src/commonMain/kotlin/korlibs/korge/fleks/entity/behavior/BehaviorTreeNodes.kt

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,14 @@ class EmptyTreeNode : BTNode {
2727
* or perform some action when the selector fails, which can be helpful for debugging or for triggering certain
2828
* behaviors in the game when a certain branch of the behavior tree fails.
2929
*/
30-
class SelectorNode(
31-
private val children: List<BTNode>,
32-
private val failureCall: () -> Unit = {}
33-
) : BTNode {
30+
class SelectorNode private constructor() : BTNode {
31+
private lateinit var children: List<BTNode>
32+
33+
constructor(vararg children: BTNode) : this() {
34+
if (children.isEmpty()) throw IllegalArgumentException("SelectorNode must have at least one child")
35+
// Create a list of children from the vararg parameter. We use a vararg parameter for convenience when constructing the behavior tree.
36+
this.children = children.toList()
37+
}
3438

3539
override fun World.tick(entity: Entity, deltaTime: Float): BTStatus {
3640
children.forEach { child ->
@@ -40,7 +44,7 @@ class SelectorNode(
4044
BTStatus.Failure -> {}
4145
}
4246
}
43-
failureCall.invoke()
47+
//println("WARNING: SelectorNode '${this::class.simpleName}' failed all children")
4448

4549
return BTStatus.Failure
4650
}
@@ -51,7 +55,15 @@ class SelectorNode(
5155
* Second Composite Node: A sequence node (symbol: [->]) that ticks its children in order and returns failure on the
5256
* first child that fails, success if all children succeed, and running if any child is still running.
5357
*/
54-
class SequenceNode(private val children: List<BTNode>) : BTNode {
58+
class SequenceNode private constructor() : BTNode {
59+
private lateinit var children: List<BTNode>
60+
61+
constructor(vararg children: BTNode) : this() {
62+
if (children.isEmpty()) throw IllegalArgumentException("SequenceNode must have at least one child")
63+
// Create a list of children from the vararg parameter. We use a vararg parameter for convenience when constructing the behavior tree.
64+
this.children = children.toList()
65+
}
66+
5567
override fun World.tick(entity: Entity, deltaTime: Float): BTStatus {
5668
children.forEach { child ->
5769
when (child.run { tick(entity, deltaTime) }) {
@@ -62,6 +74,7 @@ class SequenceNode(private val children: List<BTNode>) : BTNode {
6274
}
6375
return BTStatus.Success
6476
}
77+
6578
}
6679

6780
/**

0 commit comments

Comments
 (0)