Skip to content

sunflowerseastar/snake

Repository files navigation

Snake

This is a web version of the classic snake game.

pnpm install  # install dependencies
pnpm dev      # vite, localhost:5173
pnpm build    # bundle in dist/
pnpm test     # vitest

It is written with React 19, XState 5, and thi.ng/transducers.

Game Play

Navigation

Keyboard:

control setleftdownupright
arrow
hjklhjkl

Mobile: gamepad shows < 768 viewport width when the gamepad setting is responsive, and shows for all sizes when the gamepad setting is on.

Settings

  • Speed: snake velocity in MS
  • Board width & board height: what you expect =)
  • Overlap: game over if the snake hits itself
  • Wall: game over if the snake hits a wall
  • Gamepad: whether or not to show the gamepad
  • Theme: light or dark mode

Settings persist via local storage. Board width & board height are calculated in order to adjust to the viewport width & height unless they have been customized.

High Score

Like Settings, High Score persists via local storage.

Codebase

Build

Run pnpm build to build with Vite.

Dependencies

dependencypurpose
pnpmpackages
Vitebundling, local dev, build, testing
Reactfrontend library/architecture
XStatestate management
thi.ng/transducersfun with FP
classnameshelp with vanilla css

Site Structure

.
├── dist
└── src
    ├── components
    ├── hooks
    ├── machines
    └── stories

State & Context

React & XState have overlapping terminology, so beware the homonyms.

What is often thought of (in React world, at least) as “app state” is in this app the XState context. The XState states themselves are statechart states.

This XState context plugs into the React app via a React context provider. Note that a React context is agnostic as to what type of app state it’s providing to the app; the fact that it just so happens to be providing something that’s also called “context” is coincidental.

XState Contextmanagement of the app’s values that change over time
XState Statesa model of the app in terms of statechart states
React Contextan arbitrary collection of app state that can reach all descendants
React Providera given React context’s root component

Here is the statechart:

./statechart.png

Test

Run unit tests with pnpm test for Vitest.

About

classic snake game for the web

Topics

Resources

Stars

Watchers

Forks