Factor strategies into helper object instead of requiring methods on types

This commit is contained in:
Tangent Wantwight 2020-02-15 13:54:59 -05:00
parent 2e0b0c4ff4
commit 4c337f3579

View file

@ -29,9 +29,13 @@ export const enum TickType {
PREDICTED, PREDICTED,
} }
export type Advancer<Input, State> = (state: State, input: Input) => void; interface LockstepProcessor<Input, State> {
compareInput(a: Input, b: Input): boolean;
cloneState(source: State): State;
advanceState(state: State, input: Input): void;
}
export class LockstepState<Input extends Equals, State extends DeepCopy<State>> { export class LockstepState<Input, State> {
private inputIndex = -1; private inputIndex = -1;
private inputLog: Input[] = []; private inputLog: Input[] = [];
@ -40,21 +44,21 @@ export class LockstepState<Input extends Equals, State extends DeepCopy<State>>
private renderIndex = -1; private renderIndex = -1;
private renderState: State; private renderState: State;
constructor(private initialState: State, private advancer: Advancer<Input, State>) { constructor(private initialState: State, private engine: LockstepProcessor<Input, State>) {
this.canonState = initialState.deepCopy({}); this.canonState = engine.cloneState(initialState);
this.renderState = initialState.deepCopy({}); this.renderState = engine.cloneState(initialState);
} }
public addCanonInput(input: Input): void { public addCanonInput(input: Input): void {
this.canonIndex++; this.canonIndex++;
// advance canonical game state // advance canonical game state
this.advancer(this.canonState, input); this.engine.advanceState(this.canonState, input);
if(this.canonIndex <= this.renderIndex) { if(this.canonIndex <= this.renderIndex) {
// we're rendering predicted states, so if the input changes we need to invalidate the rendered state // we're rendering predicted states, so if the input changes we need to invalidate the rendered state
if(!equals(this.inputLog[this.canonIndex], input)) { if(!this.engine.compareInput(this.inputLog[this.canonIndex], input)) {
this.renderState = this.canonState.deepCopy({}); this.renderState = this.engine.cloneState(this.canonState);
this.renderIndex = this.canonIndex; this.renderIndex = this.canonIndex;
} }
} }
@ -81,7 +85,7 @@ export class LockstepState<Input extends Equals, State extends DeepCopy<State>>
while(this.renderIndex < targetIndex) { while(this.renderIndex < targetIndex) {
this.renderIndex++; this.renderIndex++;
this.advancer(this.renderState, this.inputLog[this.renderIndex]); this.engine.advanceState(this.renderState, this.inputLog[this.renderIndex]);
} }
return this.renderState; return this.renderState;