UNPKG

@hiddentao/clockwork-engine

Version:

A TypeScript/PIXI.js game engine for deterministic, replayable games with built-in rendering

76 lines (75 loc) 2.11 kB
import { GameEventType } from "./types"; export class UserInputEventSource { constructor() { this.dataQueue = []; } /** * Queue input data to be processed * @param inputType The type of input (e.g., "direction", "button") * @param data The input data to queue */ queueInput(inputType, data) { this.dataQueue.push({ inputType, data, timestamp: Date.now() }); } /** * Get all events for the current tick * Transforms queued data into game events with the current tick * Clears the queue after returning events */ getNextEvents(totalTicks) { if (this.dataQueue.length === 0) { return []; } // Transform all queued data into events with current tick const events = this.dataQueue.map((item) => ({ type: GameEventType.USER_INPUT, tick: totalTicks, timestamp: item.timestamp, inputType: item.inputType, params: item.data, })); // Clear the queue this.dataQueue = []; return events; } /** * Check if there are more events available */ hasMoreEvents() { return this.dataQueue.length > 0; } /** * Reset the event source by clearing the queue */ reset() { this.dataQueue.length = 0; } /** * Get the number of queued data items */ getQueueLength() { return this.dataQueue.length; } /** * Get all queued data (read-only) */ getQueuedData() { return this.dataQueue.map((item) => item.data); } /** * Remove all data matching a predicate * @param predicate Function to test each data item * @returns Number of items removed */ removeData(predicate) { const originalLength = this.dataQueue.length; this.dataQueue = this.dataQueue.filter((item) => !predicate(item.data)); return originalLength - this.dataQueue.length; } /** * Clear all data from the queue */ clear() { this.dataQueue.length = 0; } }