Docs
useSnakeGame

A simple Snake game implemented as a React hook, allowing users to play the game with customizable settings.

Loading...

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-snake-game

Usage

"use client"
 
import { useSnakeGame } from "@/hooks/use-snake-game"
 
export function Component() {
  const {
    snake,
    food,
    isGameOver,
    score,
    resetGame,
    gridSize,
    isRunning,
    startGame,
  } = useSnakeGame()
 
  return (
    <div>
      <h1>Snake Game</h1>
      <div>Score: {score}</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>
  )
}

API Reference

Parameters

NameTypeDescriptionDefault ValueOptional
speednumberSpeed of the snake in ms per move.150Yes

Return Values

NameTypeDescription
snake{ x: number; y: number }[]Array of positions representing the snake.
food{ x: number; y: number }Position of the food.
isGameOverbooleanWhether the game is over.
isRunningbooleanWhether the game is currently running.
scorenumberThe current score.
direction"UP" | "DOWN" | "LEFT" | "RIGHT"Current direction of the snake.
startGame() => voidFunction to start the game.
resetGame() => voidFunction to reset the game.
gridSizenumberThe size of the grid (width and height).

Notes

  • The hook manages the game state, including snake position, food, score, and game over state.
  • Use keyboard arrow keys to control the snake's direction.
  • The game grid is square and its size is defined by gridSize (default 20).
  • Designed for React and Next.js client components.