2019-04-09 09:42:40 -05:00
|
|
|
import {compose} from '@avocado/core';
|
2019-04-14 20:21:52 -05:00
|
|
|
import {StateProperty, Trait} from '@avocado/entity';
|
2019-04-09 09:42:40 -05:00
|
|
|
|
2019-04-14 20:33:52 -05:00
|
|
|
import {createContext} from '../context';
|
|
|
|
import {Routines} from '../item/routines';
|
|
|
|
|
2019-04-09 09:42:40 -05:00
|
|
|
const decorate = compose(
|
2019-06-05 20:12:45 -05:00
|
|
|
StateProperty('currentRoutine', {
|
|
|
|
track: true,
|
|
|
|
}),
|
|
|
|
StateProperty('isBehaving'),
|
2019-04-09 09:42:40 -05:00
|
|
|
);
|
|
|
|
|
|
|
|
export class Behaved extends decorate(Trait) {
|
|
|
|
|
|
|
|
static defaultParams() {
|
|
|
|
return {
|
|
|
|
routines: {},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
static defaultState() {
|
|
|
|
return {
|
|
|
|
currentRoutine: 'initial',
|
2019-06-05 20:12:45 -05:00
|
|
|
isBehaving: true,
|
2019-04-09 09:42:40 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-05 04:26:35 -05:00
|
|
|
static type() {
|
|
|
|
return 'behaved';
|
|
|
|
}
|
|
|
|
|
2019-05-06 04:03:43 -05:00
|
|
|
constructor(entity, params, state) {
|
|
|
|
super(entity, params, state);
|
2019-04-09 09:42:40 -05:00
|
|
|
this._context = createContext();
|
|
|
|
this._context.add('entity', this.entity);
|
2019-04-16 18:04:53 -05:00
|
|
|
this._currentRoutine = undefined;
|
2019-05-04 14:06:47 -05:00
|
|
|
const routinesJSON = this.params.routines;
|
2019-04-09 09:42:40 -05:00
|
|
|
this._routines = (new Routines()).fromJSON(routinesJSON);
|
|
|
|
this._routines.context = this._context;
|
2019-05-13 21:07:51 -05:00
|
|
|
this.updateCurrentRoutine(this.state.currentRoutine);
|
2019-04-09 09:42:40 -05:00
|
|
|
}
|
|
|
|
|
2019-04-30 17:11:41 -05:00
|
|
|
destroy() {
|
|
|
|
this._context.clear();
|
|
|
|
this._currentRoutine = undefined;
|
|
|
|
this._routines = undefined;
|
|
|
|
}
|
|
|
|
|
2019-04-09 09:42:40 -05:00
|
|
|
get context() {
|
|
|
|
return this._context;
|
|
|
|
}
|
|
|
|
|
2019-05-06 04:03:43 -05:00
|
|
|
updateCurrentRoutine(currentRoutine) {
|
|
|
|
this._currentRoutine = this._routines.routine(currentRoutine);
|
2019-04-16 18:04:53 -05:00
|
|
|
}
|
|
|
|
|
2019-04-09 09:42:40 -05:00
|
|
|
listeners() {
|
|
|
|
return {
|
|
|
|
|
2019-05-06 04:03:43 -05:00
|
|
|
currentRoutineChanged: (old, currentRoutine) => {
|
|
|
|
this.updateCurrentRoutine(currentRoutine);
|
2019-04-16 18:04:53 -05:00
|
|
|
},
|
|
|
|
|
2019-04-09 09:42:40 -05:00
|
|
|
dying: () => {
|
2019-06-05 20:12:45 -05:00
|
|
|
this.entity.isBehaving = false;
|
2019-04-09 09:42:40 -05:00
|
|
|
},
|
|
|
|
|
|
|
|
};
|
|
|
|
}
|
2019-04-12 13:05:30 -05:00
|
|
|
|
|
|
|
tick(elapsed) {
|
2019-06-05 20:12:45 -05:00
|
|
|
if (AVOCADO_SERVER) {
|
|
|
|
if (this._currentRoutine && this.entity.isBehaving) {
|
|
|
|
this._currentRoutine.tick(elapsed);
|
|
|
|
}
|
2019-04-12 13:05:30 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-09 09:42:40 -05:00
|
|
|
}
|