input handlers

This commit is contained in:
2025-05-18 16:34:33 +02:00
parent e0797d2cfc
commit 102c1f59dc
18 changed files with 595 additions and 376 deletions

View File

@@ -3,11 +3,13 @@ root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
indent_style = tab
insert_final_newline = true
trim_trailing_whitespace = true
# Add this to help VSCode and Copilot use tabs for indentation
indent_size = tab
[*.ts]
quote_type = single
ij_typescript_use_double_quotes = false

View File

@@ -4,5 +4,8 @@
"fileMatch": ["src/assets/data/*.json"],
"url": "./schemas/gdRoot.json"
}
]
],
"editor.insertSpaces": false,
"editor.detectIndentation": false,
"editor.tabSize": 4
}

View File

@@ -1,4 +1,4 @@
{
"tabWidth": 4,
"useTabs": true
"useTabs": true,
"printWidth": 9999
}

View File

@@ -12,6 +12,7 @@
<button (click)="step()">Step</button>
<button (click)="fastForward()">⏭ Fast Forward</button>
<div>Step: {{ simMain.currentStep }}</div>
<button (click)="startNextWave()">Start next wave</button>
<button (click)="openOptions()">Options</button>
</div>
</div>

View File

@@ -5,6 +5,7 @@ import { GdRoot } from './data/GdRoot';
import { SimCommand } from './sim/commands/SimCommand';
import { VisMain } from './vis/VisMain';
import { SplashComponent } from '../splash/splash.component';
import { SimCommandStartNextWave } from './sim/commands/SimCommandStartNextWave';
@Component({
selector: 'app-game',
@@ -27,7 +28,6 @@ export class GameComponent {
const gdRoot = await this.loadGdRoot();
this.simMain.setGdRoot(gdRoot);
this.visMain = new VisMain(this.simMain, SplashComponent.assetPreloader, this.wrapperRef.nativeElement, this.canvasRef.nativeElement);
window.addEventListener('resize', _ => this.visMain.onResized());
}
start() {
@@ -35,15 +35,24 @@ export class GameComponent {
}
stop() {
this.visMain.start();
this.visMain.stop();
}
step() {
this.simMain.step();
this.visMain.onRender();
}
rewind() {
//this.simMain.rewindToZero();
if (this.simMain.currentLevel)
this.simMain.currentLevel.currentStep = -1;
this.simMain.currentStep = -1;
}
startNextWave() {
this.simMain.addCommand(new SimCommandStartNextWave());
this.simMain.currentLevel!.paused = false;
}
fastForward() {

View File

@@ -1,11 +1,11 @@
import { GdRoot } from "../data/GdRoot";
import { EDirection } from "../util/EDirection";
import { Hex } from "../util/Hex";
import { PathFinding } from "../util/PathFinding";
import { ECellType } from "./ECellType";
import { SimCell } from "./SimCell";
import { SimEnemy } from "./SimEnemy";
import { SimProjectile } from "./SimProjectile";
import { GdRoot } from '../data/GdRoot';
import { EDirection } from '../util/EDirection';
import { Hex } from '../util/Hex';
import { PathFinding } from '../util/PathFinding';
import { ECellType } from './ECellType';
import { SimCell } from './SimCell';
import { SimEnemy } from './SimEnemy';
import { SimProjectile } from './SimProjectile';
export class SimLevel {
paused: boolean = true;
@@ -62,7 +62,7 @@ export class SimLevel {
});
this.updatePaths(gdRoot);
};
}
public getCellIndex(hex: Hex) {
const x = hex.col + this.radius;
@@ -105,19 +105,16 @@ export class SimLevel {
try {
if (!!hexToBlock) {
const reservedCell = this.cells[this.getCellIndex(hexToBlock)];
if (reservedCell.type != ECellType.Free || !!reservedCell.tower)
return false;
if (reservedCell.type != ECellType.Free || !!reservedCell.tower) return false;
reservedCell.type = ECellType.Reserved;
}
return this.updatePaths(gdRoot);
}
finally {
} finally {
if (!!hexToBlock) {
const reservedCell = this.cells[this.getCellIndex(hexToBlock)];
if (reservedCell.type == ECellType.Reserved)
reservedCell.type = ECellType.Free
if (reservedCell.type == ECellType.Reserved) reservedCell.type = ECellType.Free;
}
}
}

View File

@@ -36,29 +36,29 @@ export class SimMain {
}
executeUntilStep(target: number) {
this.currentStep = 0;
while (this.currentStep < target) {
this.step();
}
}
step() {
const nextStep = this.currentStep + 1;
this.currentStep++;
if (this.currentLevel && !this.currentLevel.paused) {
this.currentLevel.currentStep++;
}
// Get all commands for this step
const commands = this.commandHistory.filter((c) => c.step === nextStep);
this.currentStep = nextStep;
for (const action of this.actions) {
action.execute(this);
}
const commands = this.commandHistory.filter((c) => c.step === this.currentStep);
for (const cmd of commands) {
cmd.execute(this);
}
}
addCommand(command: SimCommand) {
command.step = this.currentStep + 1;
this.commandHistory = this.commandHistory.filter(
(c) => c.step < command.step
);

View File

@@ -1,17 +1,23 @@
import { EEnemySize } from "../../data/EEnemySize";
import { SimCommandStartNextWave } from "../commands/SimCommandStartNextWave";
import { SimEnemy } from "../SimEnemy";
import { SimMain } from "../SimMain";
import { ISimAction } from "./ISimAction";
import { EEnemySize } from '../../data/EEnemySize';
import { SimCommandStartNextWave } from '../commands/SimCommandStartNextWave';
import { SimEnemy } from '../SimEnemy';
import { SimMain } from '../SimMain';
import { ISimAction } from './ISimAction';
export class SimActionSpawnEnemies implements ISimAction {
public execute(simMain: SimMain) {
const level = simMain.currentLevel;
if (!level) return;
if (!level) {
return;
}
const gdLevel = simMain.gdRoot.levels[level.index];
const step = level.currentStep;
const gdWave = gdLevel.waves[level.currentWave];
if (!gdWave) {
return;
}
let spawnDelay = simMain.gdRoot.simulation.spawnDelay;
switch (gdWave.size) {
case EEnemySize.Huge:

View File

@@ -1,6 +1,7 @@
import { SimMain } from "../SimMain";
import { SimMain } from '../SimMain';
export abstract class SimCommand {
step: number = -1;
abstract execute(simMain: SimMain): void;
abstract check(simMain: SimMain): boolean;
}

View File

@@ -1,7 +1,7 @@
import { Hex } from "../../util/Hex";
import { ECellType } from "../ECellType";
import { SimMain } from "../SimMain";
import { SimCommand } from "./SimCommand";
import { Hex } from '../../util/Hex';
import { ECellType } from '../ECellType';
import { SimMain } from '../SimMain';
import { SimCommand } from './SimCommand';
export class SimCommandBlockTerrain extends SimCommand {
private hex: Hex;
@@ -17,9 +17,6 @@ export class SimCommandBlockTerrain extends SimCommand {
const cellIndex = level.getCellIndex(this.hex);
const cell = level.cells[cellIndex];
if (cell.type != ECellType.Free || cell.tower != null || !level.reservePaths(simMain.gdRoot, this.hex)) {
return;
}
cell.type = ECellType.Blocked;
level.updateBlockedType(cell);
for (let i = 0; i < 6; ++i) {
@@ -29,4 +26,21 @@ export class SimCommandBlockTerrain extends SimCommand {
}
level.updatePaths(simMain.gdRoot);
}
public check(simMain: SimMain): boolean {
const level = simMain.currentLevel;
if (!level) {
return false;
}
const cellIndex = level.getCellIndex(this.hex);
const cell = level.cells[cellIndex];
if (!cell) {
return false;
}
if (cell.type != ECellType.Free || cell.tower != null || !level.reservePaths(simMain.gdRoot, this.hex)) {
return false;
}
return true;
}
}

View File

@@ -1,9 +1,9 @@
import { Hex } from "../../util/Hex";
import { ECellType } from "../ECellType";
import { SimEnemy } from "../SimEnemy";
import { SimMain } from "../SimMain";
import { SimTower } from "../SimTower";
import { SimCommand } from "./SimCommand";
import { Hex } from '../../util/Hex';
import { ECellType } from '../ECellType';
import { SimEnemy } from '../SimEnemy';
import { SimMain } from '../SimMain';
import { SimTower } from '../SimTower';
import { SimCommand } from './SimCommand';
export class SimCommandCreateTower extends SimCommand {
hex: Hex;
@@ -25,14 +25,6 @@ export class SimCommandCreateTower extends SimCommand {
const cell = level.cells[cellIndex];
const towerData = simMain.gdRoot.towers[this.index];
if (cell.type != ECellType.Free) {
return;
}
if (cell.tower != null) {
return;
}
level.enemies.forEach((enemy: SimEnemy) => {
const hex = Hex.fromWorld(enemy.position);
const enemyCellIndex = level.getCellIndex(hex);
@@ -51,4 +43,33 @@ export class SimCommandCreateTower extends SimCommand {
level.updatePaths(simMain.gdRoot);
}
}
public check(simMain: SimMain): boolean {
const level = simMain.currentLevel;
if (!level) {
return false;
}
const cellIndex = level.getCellIndex(this.hex);
const cell = level.cells[cellIndex];
if (!cell) {
return false;
}
const towerData = simMain.gdRoot.towers[this.index];
if (cell.type != ECellType.Free) {
return false;
}
if (cell.tower != null) {
return false;
}
if (level.currency < towerData.cost) {
return false;
}
return true;
}
}

View File

@@ -1,13 +1,12 @@
import { GdRoot } from "../../data/GdRoot";
import { SimLevel } from "../SimLevel";
import { SimMain } from "../SimMain";
import { SimCommand } from "./SimCommand";
import { SimMain } from '../SimMain';
import { SimCommand } from './SimCommand';
export class SimCommandStartNextWave extends SimCommand {
execute(simMain: SimMain) {
public execute(simMain: SimMain) {
const level = simMain.currentLevel;
if (!level) return;
if (!level) {
return;
}
const data = simMain.gdRoot.levels[level.index];
level.currentWave += 1;
@@ -19,4 +18,12 @@ export class SimCommandStartNextWave extends SimCommand {
level.lastEnemySpawnStep = level.currentStep;
level.enemiesLeftToSpawn = data.waves[level.currentWave].amount;
}
public check(simMain: SimMain): boolean {
const level = simMain.currentLevel;
if (!level) {
return false;
}
return true;
}
}

View File

@@ -27,6 +27,7 @@ export class VisLevel {
private simMain: SimMain;
private gdRoot: GdRoot;
assets: AssetPreloaderService;
private hoveredHex: Hex | null = null;
constructor(visMain: VisMain, simMain: SimMain, gdRoot: GdRoot, assets: AssetPreloaderService) {
this.assets = assets;
@@ -60,6 +61,15 @@ export class VisLevel {
this.drawBackground();
ctx.globalCompositeOperation = "source-over";
// Highlight hovered cell first (under everything else)
if (this.hoveredHex) {
const hoveredIdx = simLevel.getCellIndex(this.hoveredHex);
const hoveredCell = simLevel.cells[hoveredIdx];
if (hoveredCell && hoveredCell.distance <= gdLevel.radius) {
this.drawCellImage(ctx, hoveredCell, "cell-highlighted.svg");
}
}
simLevel.cells.forEach((cell: SimCell) => {
if (cell.distance > gdLevel.radius) {
return;
@@ -161,6 +171,10 @@ export class VisLevel {
this.lastStep = currentStep;
}
public setHoveredHex(hex: Hex | null) {
this.hoveredHex = hex;
}
public getScreenCoords(hex: Hex): Vector2 {
const coord = Hex.toPixel(hex, this.hexSize);
return new Vector2(coord.x + this.screenXOffset - this.screenCellWidth / 2, coord.y + this.screenYOffset - this.screenCellHeight / 2);

View File

@@ -1,7 +1,10 @@
import { AssetPreloaderService } from "../../../assetPreloaderService";
import { SplashComponent } from "../../splash/splash.component";
import { SimMain } from "../sim/SimMain";
import { VisLevel } from "./VisLevel";
import { AssetPreloaderService } from '../../../assetPreloaderService';
import { SimMain } from '../sim/SimMain';
import { VisLevel } from './VisLevel';
import { Vector2 } from '../util/Vector2';
import { InputHandler } from './input/InputHandler';
import { Hex } from '../util/Hex';
import { DefaultInputHandler } from './input/DefaultInputHandler';
export class VisMain {
canvas: HTMLCanvasElement;
@@ -9,28 +12,31 @@ export class VisMain {
wallPattern: CanvasPattern;
visLevel: VisLevel;
simMain: SimMain;
private startTimestamp: number = 0;
private active: boolean = true;
private ready: boolean = false;
private gap: number = 0;
active: boolean = true;
assets: AssetPreloaderService;
wrapper: HTMLDivElement;
inputHandlers: InputHandler[] = [];
private startTimestamp: number = 0;
private ready: boolean = false;
private gap: number = 0;
constructor(simMain: SimMain, assets: AssetPreloaderService, wrapper: HTMLDivElement, canvas: HTMLCanvasElement) {
this.assets = assets;
this.simMain = simMain;
this.canvas = canvas;
this.wrapper = wrapper;
this.context = this.canvas.getContext("2d")!;
this.context.globalCompositeOperation = "source-over";
this.wallPattern = this.createPattern(assets.getImage("images/wall.png"), 48);
this.context = this.canvas.getContext('2d')!;
this.context.globalCompositeOperation = 'source-over';
this.wallPattern = this.createPattern(assets.getImage('images/wall.png'), 48);
this.visLevel = new VisLevel(this, this.simMain, this.simMain.gdRoot, assets);
this.setupInput();
this.start();
this.inputHandlers.push(new DefaultInputHandler(this));
}
private createPattern(image: HTMLImageElement, size: number): CanvasPattern {
const tempCanvas = document.createElement("canvas");
const tempContext = tempCanvas.getContext("2d")!;
const tempCanvas = document.createElement('canvas');
const tempContext = tempCanvas.getContext('2d')!;
tempCanvas.width = size;
tempCanvas.height = size;
@@ -48,24 +54,19 @@ export class VisMain {
this.step(timestamp);
});
if (!this.startTimestamp) {
this.startTimestamp = timestamp;
}
const simLevel = this.simMain.currentLevel;
if (!simLevel) {
return;
}
let targetStep = (timestamp - this.startTimestamp) * this.simMain.gdRoot.simulation.stepsPerSecond / 1000 - this.gap;
let targetStep = Math.floor(((timestamp - this.startTimestamp) * this.simMain.gdRoot.simulation.stepsPerSecond) / 1000 - this.gap);
if (simLevel.paused) {
this.gap += targetStep - simLevel.currentStep;
targetStep = simLevel.currentStep;
this.gap += targetStep - this.simMain.currentStep;
}
this.simMain.executeUntilStep(targetStep);
this.visLevel.updateEveryFrame(targetStep);
this.onRender();
};
}
public onResized() {
// Always get the latest wrapper size
@@ -82,12 +83,12 @@ export class VisMain {
this.context.scale(ratio, ratio);
this.visLevel.updateSize();
};
}
private onRender() {
onRender() {
this.clear();
const ctx = this.context;
ctx.font = "12px Tahoma";
ctx.font = '12px Tahoma';
const simLevel = this.simMain.currentLevel;
if (!!simLevel) {
if (!this.ready) {
@@ -96,7 +97,7 @@ export class VisMain {
}
this.visLevel.draw();
}
};
}
private clear() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
@@ -109,7 +110,57 @@ export class VisMain {
start() {
this.active = true;
requestAnimationFrame((timestamp: number) => {
this.startTimestamp = timestamp - (this.simMain.currentStep / this.simMain.gdRoot.simulation.stepsPerSecond) * 1000;
this.step(timestamp);
});
}
private setupInput() {
this.canvas.addEventListener('mousedown', (e) => this.handleMouseDown(e));
this.canvas.addEventListener('mousemove', (e) => this.handleMouseMove(e));
window.addEventListener('keydown', (e) => this.handleKeyDown(e));
window.addEventListener('resize', (_) => this.onResized());
}
private getHexFromMouseCoords(event: MouseEvent): Hex {
const rect = this.canvas.getBoundingClientRect();
const ratio = this.canvas.width / rect.width;
const x = ((event.clientX - rect.left) * ratio) / window.devicePixelRatio;
const y = ((event.clientY - rect.top) * ratio) / window.devicePixelRatio;
const coords = new Vector2(x, y);
const hex = this.visLevel.getHexFromScreenCoords(coords);
return hex;
}
private handleMouseDown(event: MouseEvent) {
const hex = this.getHexFromMouseCoords(event);
for (let i = this.inputHandlers.length - 1; i >= 0; i--) {
const handled = this.inputHandlers[i].onMouseDown?.(event, hex);
if (handled) {
event.preventDefault();
return;
}
}
}
private handleMouseMove(event: MouseEvent) {
const hex = this.getHexFromMouseCoords(event);
for (let i = this.inputHandlers.length - 1; i >= 0; i--) {
const handled = this.inputHandlers[i].onMouseMove?.(event, hex);
if (handled) {
event.preventDefault();
return;
}
}
}
handleKeyDown(event: KeyboardEvent) {
for (let i = this.inputHandlers.length - 1; i >= 0; i--) {
const handled = this.inputHandlers[i].onKeyDown?.(event);
if (handled) {
event.preventDefault();
return;
}
}
}
}

View File

@@ -0,0 +1,47 @@
import { SimCommandBlockTerrain } from '../../sim/commands/SimCommandBlockTerrain';
import { SimCommandCreateTower } from '../../sim/commands/SimCommandCreateTower';
import { Hex } from '../../util/Hex';
import { VisMain } from '../VisMain';
import { HexInteractionInputHandler } from './HexInteractionInputHandler';
import { InputHandler } from './InputHandler';
export class DefaultInputHandler implements InputHandler {
visMain: VisMain;
constructor(visMain: VisMain) {
this.visMain = visMain;
}
onKeyDown(event: KeyboardEvent): boolean {
if (event.code === 'Escape') {
if (this.visMain.inputHandlers.length > 1) {
this.visMain.inputHandlers.pop();
this.visMain.visLevel.setHoveredHex(null);
event.preventDefault();
return true;
}
} else if (event.code === 'Space') {
if (this.visMain.active) {
this.visMain.stop();
} else {
this.visMain.start();
}
return true;
} else if (event.code === 'KeyT') {
this.visMain.inputHandlers.push(new HexInteractionInputHandler(this.visMain, (hex) => new SimCommandCreateTower(hex, 0)));
return true;
} else if (event.code === 'KeyB') {
this.visMain.inputHandlers.push(new HexInteractionInputHandler(this.visMain, (hex) => new SimCommandBlockTerrain(hex)));
return true;
}
return false;
}
onMouseDown(event: MouseEvent, hex: Hex): boolean {
return false;
}
onMouseMove(event: MouseEvent, hex: Hex): boolean {
return false;
}
}

View File

@@ -0,0 +1,39 @@
import { SimCommand } from '../../sim/commands/SimCommand';
import { Hex } from '../../util/Hex';
import { VisMain } from '../VisMain';
import { InputHandler } from './InputHandler';
export class HexInteractionInputHandler implements InputHandler {
private hexCallback: (hex: Hex) => SimCommand;
private command: SimCommand | null = null;
visMain: VisMain;
constructor(visMain: VisMain, hexCallback: (hex: Hex) => SimCommand) {
this.visMain = visMain;
this.hexCallback = hexCallback;
}
onKeyDown(event: KeyboardEvent): boolean {
return false;
}
onMouseDown(event: MouseEvent, hex: Hex): boolean {
if (!this.command) {
return false;
}
this.visMain.simMain.addCommand(this.command);
return true;
}
onMouseMove(event: MouseEvent, hex: Hex): boolean {
this.command = this.hexCallback(hex);
if (this.command && this.command.check(this.visMain.simMain)) {
this.visMain.visLevel.setHoveredHex(hex);
}
else {
this.visMain.visLevel.setHoveredHex(null);
}
return false;
}
}

View File

@@ -0,0 +1,7 @@
import { Hex } from "../../util/Hex";
export interface InputHandler {
onKeyDown?: (event: KeyboardEvent) => boolean;
onMouseDown?: (event: MouseEvent, hex: Hex) => boolean;
onMouseMove?: (event: MouseEvent, hex: Hex) => boolean;
}