avocado-old/packages/behavior/traits/behaved.trait.js

80 lines
1.6 KiB
JavaScript
Raw Normal View History

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-09-08 04:33:13 -05:00
import {Context} from '../context';
import {Routines} from '../item/routines';
2019-04-09 09:42:40 -05:00
const decorate = compose(
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',
isBehaving: true,
2019-04-09 09:42:40 -05:00
}
}
2019-05-05 04:26:35 -05:00
static type() {
return 'behaved';
}
constructor(entity, params, state) {
super(entity, params, state);
2019-09-08 06:04:31 -05:00
this._context = new Context({
entity: this.entity,
});
this._currentRoutine = undefined;
2019-10-10 01:30:33 -05:00
this._routines = (new Routines()).fromJSON(this.params.routines);
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() {
2019-09-08 04:33:13 -05:00
this._context.destroy();
2019-04-30 17:11:41 -05:00
this._currentRoutine = undefined;
this._routines = undefined;
}
2019-04-09 09:42:40 -05:00
get context() {
return this._context;
}
updateCurrentRoutine(currentRoutine) {
this._currentRoutine = this._routines.routine(currentRoutine);
}
2019-04-09 09:42:40 -05:00
listeners() {
return {
currentRoutineChanged: (old, currentRoutine) => {
this.updateCurrentRoutine(currentRoutine);
},
2019-10-10 01:27:02 -05:00
isDyingChanged: (_, isDying) => {
this.entity.isBehaving = !isDying;
2019-04-09 09:42:40 -05:00
},
};
}
tick(elapsed) {
if (AVOCADO_SERVER) {
if (this._currentRoutine && this.entity.isBehaving) {
2019-09-08 08:18:16 -05:00
this._currentRoutine.tick(this._context, elapsed);
}
}
}
2019-04-09 09:42:40 -05:00
}