Add API plugin with common functionality

This commit is contained in:
Gary Tierney
2017-09-17 03:09:47 +01:00
parent 3a9e435189
commit cf0e3331e0
7 changed files with 99 additions and 9 deletions
@@ -335,12 +335,22 @@ public final class Region {
}
/**
* Removes an {@link Entity} from this Region.
* Removes an {@link Entity} from this Region and notifies listeners.
*
* @param entity The Entity.
* @throws IllegalArgumentException If the Entity does not belong in this Region, or if it was never added.
*/
public void removeEntity(Entity entity) {
removeEntity(entity, true);
}
/**
* Removes an {@link Entity} from this Region.
*
* @param entity The Entity.
* @throws IllegalArgumentException If the Entity does not belong in this Region, or if it was never added.
*/
public void removeEntity(Entity entity, boolean notifyListeners) {
EntityType type = entity.getEntityType();
if (type.isTransient()) {
throw new IllegalArgumentException("Tried to remove a transient Entity (" + entity + ") from " +
@@ -356,7 +366,9 @@ public final class Region {
throw new IllegalArgumentException("Entity (" + entity + ") belongs in (" + this + ") but does not exist.");
}
notifyListeners(entity, EntityUpdateType.REMOVE);
if (notifyListeners) {
notifyListeners(entity, EntityUpdateType.REMOVE);
}
}
@Override
@@ -4,7 +4,7 @@ import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.Job
import kotlinx.coroutines.experimental.channels.Channel
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.selects.select
import kotlinx.coroutines.experimental.runBlocking
class AsyncActionRunner(val actionSupplier: () -> Action<*>, val callback: suspend () -> Unit) {
var job: Job? = null
@@ -27,10 +27,10 @@ class AsyncActionRunner(val actionSupplier: () -> Action<*>, val callback: suspe
val action = actionSupplier.invoke()
job = launch(CommonPool) {
select {
pulseChannel.onReceive {
run {
while (action.isRunning) {
pulseChannel.receive()
callback()
action.stop()
}
}
}
@@ -45,12 +45,14 @@ class AsyncActionRunner(val actionSupplier: () -> Action<*>, val callback: suspe
pulseChannel.close()
}
suspend fun wait(pulses: Int = 1) {
suspend fun wait(pulses: Int = 1, pulseCallback: (() -> Unit)? = null) {
var remainingPulses = pulses
while (remainingPulses > 0) {
val numPulses = pulseChannel.receive()
remainingPulses -= numPulses
pulseCallback?.invoke()
}
}
@@ -3,7 +3,7 @@ package org.apollo.game.action
interface AsyncActionTrait {
val runner: AsyncActionRunner
suspend fun wait(pulses: Int = 1) {
runner.wait(pulses)
suspend fun wait(pulses: Int = 1, pulseCallback: (() -> Unit)? = null) {
runner.wait(pulses, pulseCallback)
}
}
@@ -15,12 +15,18 @@ abstract class AsyncDistancedAction<T : Mob> : DistancedAction<T>, AsyncActionTr
abstract suspend fun executeActionAsync()
open protected fun start() {
}
override fun stop() {
super.stop()
runner.stop()
}
override fun executeAction() {
start()
if (!runner.started()) {
runner.start()
}