game start/stop, snake rendered on board
This commit is contained in:
+6
-1
@@ -3,12 +3,17 @@ import "@vimazing/vim-snake/game.css";
|
||||
import { useKeyBindings } from "./useKeyBindings";
|
||||
|
||||
function App() {
|
||||
const { containerRef } = useGame(30, 20, useKeyBindings);
|
||||
const { containerRef, gameStatus } = useGame(30, 20, useKeyBindings);
|
||||
|
||||
return (
|
||||
<div className="relative mx-auto my-4 w-fit space-y-4">
|
||||
<h1 className="text-2xl font-bold text-center">VIMazing Snake</h1>
|
||||
<div ref={containerRef} className="relative" />
|
||||
<div className="text-center text-sm text-muted-foreground">
|
||||
{gameStatus === "waiting" && <p>Press <kbd className="px-2 py-1 bg-muted rounded">space</kbd> to start</p>}
|
||||
{gameStatus === "started" && <p>Use <kbd className="px-2 py-1 bg-muted rounded">hjkl</kbd> to move • Press <kbd className="px-2 py-1 bg-muted rounded">q</kbd> to quit</p>}
|
||||
{gameStatus === "game-over" && <p>Game Over! Press <kbd className="px-2 py-1 bg-muted rounded">space</kbd> to restart</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
import { useEffect } from "react";
|
||||
import type { UseGameType } from "@vimazing/vim-maze";
|
||||
import type { UseGameType } from "@vimazing/vim-snake";
|
||||
|
||||
export const useKeyBindings = (gameManager: UseGameType) => {
|
||||
const { gameStatus, initGame, stopGame, clearLog, resetCount } = gameManager;
|
||||
const { gameStatus, startGame, stopGame, clearLog, resetCount } = gameManager;
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
console.log("key pressed:", e.key, e.code);
|
||||
// start game
|
||||
if (e.key === "i" || e.key === "I") {
|
||||
if (e.code === "Space") {
|
||||
if (["waiting", "game-over", "game-won"].includes(gameStatus)) {
|
||||
clearLog();
|
||||
resetCount();
|
||||
// clearLog();
|
||||
// resetCount();
|
||||
if (gameStatus === "game-over" || gameStatus === "game-won") {
|
||||
stopGame();
|
||||
setTimeout(() => initGame(true), 0);
|
||||
// setTimeout(() => initGame(true), 0);
|
||||
} else {
|
||||
initGame(true);
|
||||
startGame();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -41,6 +42,6 @@ export const useKeyBindings = (gameManager: UseGameType) => {
|
||||
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [gameStatus, initGame, stopGame, clearLog, resetCount]);
|
||||
}, [gameStatus, startGame, stopGame, clearLog, resetCount]);
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user