base2020/src/game/Main.ts

78 lines
2.3 KiB
TypeScript

import pipe from "callbag-pipe";
import subscribe from "callbag-subscribe";
import { KeyControl, KeyName } from "../applet/Keyboard";
import { DrawSet } from "../applet/Render";
import { FixedPoint, Location, PolygonComponent, RenderBounds } from "../ecs/Components";
import { Create } from "../ecs/Data";
import { RunRenderBounds } from "../ecs/Renderers";
import { LockstepClient, Server } from "../net/LockstepClient";
import { Data, Engine, PlayerControl } from "./GameComponents";
import { Buttons } from "./Input";
export class Main extends LockstepClient<KeyName[], KeyName[][], Data> {
buttons = new Buttons();
constructor(canvas: HTMLCanvasElement, cx: CanvasRenderingContext2D, keys: KeyControl, server: Server<KeyName[], KeyName[][], Data>) {
super(new Engine());
keys.setHandler(this.buttons);
this.connect(server);
pipe(
this.renderFrames,
subscribe((frame: Data) => {
const drawSet = new DrawSet();
cx.fillStyle = "#000";
cx.fillRect(0, 0, canvas.width, canvas.height);
RunRenderBounds(frame, drawSet);
drawSet.draw(cx, 0);
})
);
}
gatherInput() {
return this.buttons.getPressed();
}
initState(patch: Partial<Data>) {
const newState = new Data(patch);
Create(newState, {
playerControl: new PlayerControl({
playerNumber: 0
}),
location: new Location({
X: 100 as FixedPoint,
Y: 200 as FixedPoint,
}),
bounds: new PolygonComponent({points: [-30, 0, 30, 0, 0, 40] as FixedPoint[]}),
renderBounds: new RenderBounds({
color: "#a0f",
layer: 0
}),
});
Create(newState, {
playerControl: new PlayerControl({
playerNumber: 1
}),
location: new Location({
X: 400 as FixedPoint,
Y: 200 as FixedPoint,
}),
bounds: new PolygonComponent({points: [-30, 0, 30, 0, 0, 40] as FixedPoint[]}),
renderBounds: new RenderBounds({
color: "#f0a",
layer: 0
}),
});
return newState;
}
}