This project was completed as part of a group learning exercise. Using a server side state machine we can create a game that does not require JavaScript.
https://piratebattle.netifly.app/
- ✅ User can choose a character to play as.
- ✅ User is presented with a game board to try and sink pirate ships.
- ✅ User can choose locations on a grid and is informed if their choice results in a hit or a miss.
- ✅ User can identify that they have sunked a ship based on the colors on the grid.
- ✅ Use is able to retry once all of the ships are sunk.
- typescript
- react
- remix
- xstate
- vitest
After watching a the Reactathon talk given by Erik Rasumssen about server side state charts I decided to implement this game using a similar technique.
The game states are mapped to the urls /game/start
, /game/battle
, /game/end
. Each time the user takes an action, the server resolves the move.
When the user starts the game, the server encodes the game state into a cookie session. Each action will create a new cookie with the latest game state.
There are a few tests written for the findPlacement
function used by the game engine. These tests confirm that the algorithm will try again if a randomly placed ship would overlap an existing ship.
const findPlacement =
(state: Placement[]) => (direction: Symbol, size: number) => {
while (true) {
const long = Math.floor(Math.random() * GAME_BOARD_SIZE);
const short = Math.floor(Math.random() * (GAME_BOARD_SIZE - size - 1));
const cells = [];
for (let i = short; i < short + size; i++) {
cells.push(
direction === DIRECTION.HORIZONTAL
? GAME_BOARD_SIZE * long + i
: GAME_BOARD_SIZE * i + long
);
}
if (cells.every((value) => state[value] === null)) {
return cells;
}
}
};
The Netlify CLI starts your app in development mode, rebuilding assets on file changes.
npm run dev
Open up http://localhost:3000, and you should be ready to go!
There are two ways to deploy your app to Netlify, you can either link your app to your git repo and have it auto deploy changes to Netlify, or you can deploy your app manually. If you've followed the setup instructions already, all you need to do is run this:
npm run build
# preview deployment
netlify deploy
# production deployment
netlify deploy --prod