102 lines
2.2 KiB
JavaScript
102 lines
2.2 KiB
JavaScript
import {behaviorItemFromJSON, Context} from '@avocado/behavior';
|
|
import {compose, Property} from '@avocado/core';
|
|
import {StateProperty, Trait} from '@avocado/entity';
|
|
|
|
import {TraitUpdatePlantPacket} from '../packets/trait-update-plant.packet';
|
|
|
|
const decorate = compose(
|
|
StateProperty('growthStage', {
|
|
track: true,
|
|
}),
|
|
);
|
|
|
|
export class Plant extends decorate(Trait) {
|
|
|
|
static defaultParams() {
|
|
return {
|
|
growthCondition: {
|
|
type: 'condition',
|
|
operator: 'or',
|
|
operands: [],
|
|
},
|
|
stageSpecs: {},
|
|
};
|
|
}
|
|
|
|
static defaultState() {
|
|
return {
|
|
growthStage: 0,
|
|
};
|
|
}
|
|
|
|
static type() {
|
|
return 'plant';
|
|
}
|
|
|
|
constructor(entity, params, state) {
|
|
super(entity, params, state);
|
|
this.growthCondition = behaviorItemFromJSON(this.params.growthCondition);
|
|
this.growthConditionContext = new Context({
|
|
entity: this.entity,
|
|
});
|
|
this.growthElapsed = 0;
|
|
}
|
|
|
|
acceptPacket(packet) {
|
|
if (packet instanceof TraitUpdatePlantPacket) {
|
|
this.entity.growthStage = packet.data.growthStage;
|
|
}
|
|
}
|
|
|
|
packets(informed) {
|
|
const {growthStage} = this.stateDifferences();
|
|
if (growthStage) {
|
|
return new TraitUpdatePlantPacket({
|
|
growthStage: this.state.growthStage,
|
|
});
|
|
}
|
|
}
|
|
|
|
listeners() {
|
|
return {
|
|
|
|
growthStageChanged: (oldStage, newStage) => {
|
|
const stageSpec = this.params.stageSpecs[newStage];
|
|
this.entity.currentImage = stageSpec.image;
|
|
},
|
|
|
|
};
|
|
}
|
|
|
|
methods() {
|
|
return {
|
|
|
|
growToNextStage: () => {
|
|
const growthStage = this.entity.growthStage;
|
|
const stageSpec = this.params.stageSpecs[growthStage];
|
|
if (!('growAt' in stageSpec)) {
|
|
return;
|
|
}
|
|
this.growthElapsed = stageSpec.growAt;
|
|
this.entity.growthStage = growthStage + 1;
|
|
},
|
|
|
|
};
|
|
}
|
|
|
|
tick(elapsed) {
|
|
if (this.growthCondition.get(this.growthConditionContext)) {
|
|
const growthStage = this.entity.growthStage;
|
|
const stageSpec = this.params.stageSpecs[growthStage];
|
|
// TODO variance
|
|
this.growthElapsed += elapsed;
|
|
if ('growAt' in stageSpec) {
|
|
if (this.growthElapsed >= stageSpec.growAt) {
|
|
this.entity.growthStage = growthStage + 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|