Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a simple callback decorator to behavior tree
- Loading branch information
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package net.citizensnpcs.api.ai.tree; | ||
|
||
import java.util.function.Consumer; | ||
|
||
/** | ||
* Wraps an {@link Behavior} and runs callbacks when the underlying Behavior is finished. | ||
*/ | ||
public class Callback extends BehaviorGoalAdapter { | ||
private final Consumer<BehaviorStatus> cb; | ||
private final Behavior wrapping; | ||
|
||
private Callback(Behavior wrapping, Consumer<BehaviorStatus> cb) { | ||
this.wrapping = wrapping; | ||
this.cb = cb; | ||
} | ||
|
||
@Override | ||
public void reset() { | ||
wrapping.reset(); | ||
} | ||
|
||
@Override | ||
public BehaviorStatus run() { | ||
BehaviorStatus status = wrapping.run(); | ||
switch (status) { | ||
case FAILURE: | ||
case SUCCESS: | ||
case RESET_AND_REMOVE: | ||
cb.accept(status); | ||
default: | ||
break; | ||
} | ||
return status; | ||
} | ||
|
||
@Override | ||
public boolean shouldExecute() { | ||
return wrapping.shouldExecute(); | ||
} | ||
|
||
public static Callback callback(Behavior wrapping, Consumer<BehaviorStatus> cb) { | ||
return new Callback(wrapping, cb); | ||
} | ||
} |