Loading...
Please waitLoading...
Please waitA simple Snake game implemented as a React hook, allowing users to play the game with customizable settings.
pnpm dlx uselab@latest add use-snake-game
import * as React from "react"
import { Difficulty, useSnakeGame } from "@/hooks/use-snake-game"
export function Component() {
const [level, setLevel] = React.useState<Difficulty>(Difficulty.NORMAL)
const {
snake,
food,
isGameOver,
score,
resetGame,
gridSize,
isRunning,
startGame,
level: currentLevel,
} = useSnakeGame(level)
return (
<div>
<h1>Snake Game</h1>
<div>Score: {score}</div>
<div>
Difficulty:
{Object.values(Difficulty).map((lvl) => (
<button
key={lvl}
onClick={() => {
if (lvl !== level) {
setLevel(lvl)
resetGame()
}
}}
style={{
marginLeft: 8,
padding: "6px 10px",
borderRadius: 6,
border: "1px solid #ccc",
background: currentLevel === lvl ? "#111" : "#222",
color: "#fff",
}}
>
{lvl}
</button>
))}
</div>
{/* Render your grid here using snake and food positions */}
{!isRunning && !isGameOver && (
<button
style={{
padding: "8px 16px",
borderRadius: 4,
background: "#222",
color: "#fff",
border: "none",
cursor: "pointer",
}}
onClick={startGame}
>
Start Game
</button>
)}
{isGameOver && (
<button
style={{
padding: "8px 16px",
borderRadius: 4,
background: "#e53e3e",
color: "#fff",
border: "none",
cursor: "pointer",
}}
onClick={resetGame}
>
Restart Game
</button>
)}
</div>
)
}| Name | Type | Description | Default Value | Optional |
|---|---|---|---|---|
level | "easy" | "normal" | "hard" | Difficulty preset that controls speed | "normal" | Yes |
| Name | Type | Description |
|---|---|---|
snake | { x: number; y: number }[] | Array of positions representing the snake. |
food | { x: number; y: number } | Position of the food. |
isGameOver | boolean | Whether the game is over. |
isRunning | boolean | Whether the game is currently running. |
score | number | The current score. |
direction | "UP" | "DOWN" | "LEFT" | "RIGHT" | Current direction of the snake. |
startGame | () => void | Function to start the game. |
resetGame | () => void | Function to reset the game. |
gridSize | number | The size of the grid (width and height). |
level | "easy" | "normal" | "hard" | Current difficulty in use. |
gridSize (default 20).