Reorganize example: move key bindings to usePlatformHook module
This commit is contained in:
+2
-2
@@ -1,14 +1,14 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useGame, type GameMode } from "@vimazing/typing-chud";
|
||||
import "@vimazing/typing-chud/game.css";
|
||||
import { useKeyBindings } from "./useKeyBindings";
|
||||
import { usePlatformHook } from "./usePlatformHook";
|
||||
import { testScenarios, getScenario, getScenarioNames, type TestScenario } from "./testStateMachines";
|
||||
|
||||
function App() {
|
||||
const [scenarioId, setScenarioId] = useState<string>("progressive");
|
||||
const scenario = getScenario(scenarioId);
|
||||
const [gameMode, setGameMode] = useState<GameMode>(scenario.initialMode);
|
||||
const gameManager = useGame({ gameMode }, useKeyBindings);
|
||||
const gameManager = useGame({ gameMode }, usePlatformHook);
|
||||
const { containerRef, gameStatus, scoreManager } = gameManager;
|
||||
const lastTransitionIndexRef = useRef<number>(-1);
|
||||
const triggeredScoreTransitionsRef = useRef<Set<number>>(new Set());
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export * from './usePlatformHook';
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useEffect } from "react";
|
||||
import type { GameManager } from "../../../src";
|
||||
|
||||
export const usePlatformHook = (gameManager: GameManager) => {
|
||||
useEffect(() => {
|
||||
const handler = (ev: KeyboardEvent) => {
|
||||
// start game
|
||||
if (ev.code === "Space") {
|
||||
ev.preventDefault(); // Prevent button activation
|
||||
if (["waiting", "game-over", "game-won"].includes(gameManager.gameStatus)) {
|
||||
gameManager.clearKeyLog();
|
||||
gameManager.renderBoard();
|
||||
if (gameManager.gameStatus === "game-over" || gameManager.gameStatus === "game-won") {
|
||||
gameManager.quitGame();
|
||||
setTimeout(() => gameManager.startGame(), 0);
|
||||
} else {
|
||||
gameManager.startGame();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ignore other keys while waiting
|
||||
if (gameManager.gameStatus === "waiting") return;
|
||||
|
||||
// quit
|
||||
if (ev.key === "Escape") {
|
||||
ev.preventDefault();
|
||||
gameManager.quitGame();
|
||||
return;
|
||||
}
|
||||
|
||||
// handle letter and punctuation typing during game
|
||||
if (gameManager.gameStatus === "started") {
|
||||
if (ev.key.length === 1 && /[a-zA-Z.,!? ]/.test(ev.key)) {
|
||||
gameManager.handleTypedLetter(ev.key);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [gameManager.gameStatus]);
|
||||
};
|
||||
Reference in New Issue
Block a user