Skip to content

sunflowerseastar/snake

Repository files navigation

Snake

This is a web version of the classic snake game.

bun i
yarn dev          # vite, localhost:5173
yarn build
yarn test         # to use vitest
bun test --watch  # to use bun test

It is written with React 18, 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

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 bun build to build with Vite.

Dependencies

dependencypurpose
Bunpackages, testing
Vitebundling, local dev, build, testing
Reactfrontend library/architecture
XStatestate management
thi.ng/transducershave fun 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

Test

Run unit tests with yarn test for Vitest or bun test --watch for bun test. Same tests, though.