81 lines
1.6 KiB
JavaScript
81 lines
1.6 KiB
JavaScript
import {compose} from '@avocado/core';
|
|
import {StateProperty, Trait} from '@avocado/entity';
|
|
|
|
import {createContext} from '../context';
|
|
import {Routines} from '../item/routines';
|
|
|
|
const decorate = compose(
|
|
StateProperty('currentRoutine', {
|
|
track: true,
|
|
}),
|
|
StateProperty('isBehaving'),
|
|
);
|
|
|
|
export class Behaved extends decorate(Trait) {
|
|
|
|
static defaultParams() {
|
|
return {
|
|
routines: {},
|
|
};
|
|
}
|
|
|
|
static defaultState() {
|
|
return {
|
|
currentRoutine: 'initial',
|
|
isBehaving: true,
|
|
}
|
|
}
|
|
|
|
static type() {
|
|
return 'behaved';
|
|
}
|
|
|
|
constructor(entity, params, state) {
|
|
super(entity, params, state);
|
|
this._context = createContext();
|
|
this._context.add('entity', this.entity);
|
|
this._currentRoutine = undefined;
|
|
const routinesJSON = this.params.routines;
|
|
this._routines = (new Routines()).fromJSON(routinesJSON);
|
|
this._routines.context = this._context;
|
|
this.updateCurrentRoutine(this.state.currentRoutine);
|
|
}
|
|
|
|
destroy() {
|
|
this._context.clear();
|
|
this._currentRoutine = undefined;
|
|
this._routines = undefined;
|
|
}
|
|
|
|
get context() {
|
|
return this._context;
|
|
}
|
|
|
|
updateCurrentRoutine(currentRoutine) {
|
|
this._currentRoutine = this._routines.routine(currentRoutine);
|
|
}
|
|
|
|
listeners() {
|
|
return {
|
|
|
|
currentRoutineChanged: (old, currentRoutine) => {
|
|
this.updateCurrentRoutine(currentRoutine);
|
|
},
|
|
|
|
dying: () => {
|
|
this.entity.isBehaving = false;
|
|
},
|
|
|
|
};
|
|
}
|
|
|
|
tick(elapsed) {
|
|
if (AVOCADO_SERVER) {
|
|
if (this._currentRoutine && this.entity.isBehaving) {
|
|
this._currentRoutine.tick(elapsed);
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|