Pirates: Sails of Infamy logo

Pirates: Sails of Infamy

A top-down pirate game in plain HTML, CSS and JavaScript. Project guide.

Overview

You captain a pirate ship — starting with a nimble sloop — in a stylised Caribbean — Cuba, Hispaniola, Jamaica, Puerto Rico, the Bahamas, the Lesser Antilles and the Spanish Main coast — with thirteen ports in four nations: Havana, Santiago, San Juan, Cartagena and Maracaibo (Spanish), Nassau, Port Royal and Barbados (English), Tortuga, Petit-Goâve and Martinique (French), Willemstad and St. Martin (Dutch). Each town is built in its nation's style and its guards wear their nation's colours. Away from the towns stand five plantations, five clifftop monasteries and four coastal forts (see Beyond the ports). The world is drawn top-down at a slight angle (3/4 view) with pixel-art terrain and a fully animated pixel-art captain in a black tricorn with a white feather. Sail and fight broadsides, board struck ships and fight their crews hand to hand, and walk port towns to trade, refit and hire crew.

Everything is drawn with the HTML Canvas 2D API — no WebGL, no libraries. Islands, ships, towns and characters (including the captain's limbs, sword and pistol) are generated in code; the files in /assets are UI art. Single Player needs no server, build tools or network requests (only the Google Fonts stylesheet, which falls back to local serif fonts offline) — open index.html straight from disk. Online World needs an internet connection and the Firebase setup in Online world.

Quick start: unzip the folder anywhere, double-click index.html, choose Single Player → New Game (or Online World to sail with others), then pick your captain. You start ashore at Port Royal; walk up the gangplank onto your ship, go to the wheel and press G to cast off.

How it plays

Sailing

Naval combat

Ramming, boarding and gunnery

On foot aboard ship

Press G to let go of the wheel. The ship keeps her sails set but drifts and slows. Walk with WASD, run with Shift, jump with Space. Walk over the rail to go overboard (you are hauled back to the wheel). Stand by the wheel and press G or F to take the helm again.

Below deck: on every hull, the grating in the middle of the deck is a hatch. Stand beside it and press F to climb down to the gun deck: guns run out through their ports, a mess table laid with food and rum (press F at it to eat for +30 health or drink a tot for +8 — each uses one from your hold), hammocks, stores, and a red powder keg beside the shot. Climb the ladder (F) to go back up. While you're below, the ship holds her heading under the sail she carries — mind the coast.

Captain's quarters: brigs, frigates and galleons have a door in the starboard half of the stern-castle front. Inside: stern windows, your desk and a high-backed captain's chair, a guest chair, a bed (rest to full health), a wardrobe, a sea chest, a globe, and a table with food, rum and a medicine chest (uses your tonics). Press F at a chair to sit; move to stand up.

Your crew aboard: one or two sailors work the deck at all times (swabbing, checking the barrels, tending the lines, keeping watch) and three to five more are below (eating, minding the stores and powder, singing by the hammocks). They are part of your real crew count: kill one and you lose a sailor and morale. Press F to talk to one; punching one may make them drop a little gold (30%), start a fist fight (60%) or quit your crew (10%, −1 crew); a blade or a shot always starts an armed fight. They calm down if you walk away. Fallen sailors are replaced from your crew roster. If one gets wedged against a mast or furniture he steers round it, and gives up on that job if he can't reach it.

Long guns: with the Long Rifle or the Blunderbuss equipped, it's carried on your back (rifle over the shoulder, blunderbuss across the hip). Shooting pulls it out — the rifle comes over the shoulder and up to a two-handed aim, the blunderbuss swings round from the hip — fires with a heavy kick, then goes back on your back.

Ports

Sail near a port's pier and press F to dock (you must be below ~14 kn). The game auto-saves and your captain's health refills. Walk the town and press F at a door:

Press F near a port to dock: your crew brings the ship in, warps her alongside the pier and lowers the gangplank. Let go of the wheel (G) and walk down the gangplank to go ashore. To leave, walk back up the gangplank, go to the wheel and press G to cast off.

Docking sides: every pier can be moored on either side; the crew brings her in on whichever side is nearest your ship. Now and then one or two idle sailors loiter on the pier — press F to hire one on (prices.hireCrew), or rough them up.

Luxuries & inventory: the Luxuries stall stocks 10–20 red roses a day plus one of a box of chocolates, a shell necklace or a locket. English towns may also have a rare gold necklace, Dutch towns a rare silver bracelet, and only Willemstad sells the diamond ring (5000g, one a day). Stock and going rates change at 6am; resell anywhere for whatever that stall pays today. Bought trinkets go in the 8-slot inventory shown under the chart (settings in lux, logic in src/goods.js). Each clothier carries one variant per slot (hat, coat, shirt, pants, dress); every variant is sold somewhere.

Dropping items: open the chart (M) and press and hold any item in your inventory to set it down just in front of you — on the town ground or your deck. It won't go into the water, over the side or past the edge of town; if there's no room you'll be told. Anyone nearby (you or another captain) picks it up with F / ◆. Items left behind vanish once every captain has left that part of the map.

Weddings (online): two captains in the same church, at least one carrying a ring, get a Marry option from the priest. Both must answer “I do”; the ring is used up. With more than one other captain present the priest asks whom you wish to marry. While both spouses are online they take marriage.dmgMul damage and crew morale drains at marriage.moraleMul speed. Re-publish the database rules below — they now allow the rm, ring and sp presence fields and the wed messages.

Sailing as crew (online): in port, stand by another captain's moored ship (or beside them in town) and press F to ask to sail as their crew. When they welcome you aboard, your own ship stays moored where it is and you ride their deck: walk about, fight boarders and duels at their side, and stand by either rail and press F to fire that broadside for them. Their sailors work the deck and below, and you can go below or into the quarters with the hatch and door. When they're moored at the pier you step ashore at the foot of their gangplank. To get back to your ship from any other port, talk to the shipwright — the passage home is free. If the owner disconnects or their ship sinks while you're at sea, you're sent straight back to the port where your ship is moored.

Coffee houses: every town has one near the waterfront (the free house nearest the docks, picked after the homes so saved houses never change). The keeper sells black coffee: each cup gives +5% on-foot speed, up to 3 cups, and each cup wears off after 4 real minutes (PG.Coffee CF in src/coffee.js). Ask the keeper to work a shift. Shifts can start between 6am and 11pm, and the keeper refuses while you have any wanted stars. Up to 3 customers queue from 6am to 6pm, 1–2 from 6pm to 9pm, and 1 after 9pm. The house closes at 2am, which ends the shift, and staying until closing pays a 120–200g bonus. The keeper goes and sits by the fire, and customers come in and queue in single file out from the hatch and wait. Take each order at the hatch, which shows it in a bubble over their head and starts their patience timer. To make a cup: scoop green beans from the sacks, then roast them in the pan. Tip them out once they are dark and oily; too pale is weak and too long burns them. Turn the mill crank 10 times, take the grounds, and tip them into the pot. Lift the pot off the fire when the foam reaches the rim, before it boils over. Take a mug from the shelf, ladle out a cup, add sugar, cinnamon, milk or rum, and serve it at the hatch. You earn half the price, and well-made cups often earn a tip. Weak or burnt coffee is refused. Serving is one press at a time, so the touch ◆ button and the F key both work. Online, other captains in the room order from you at the hatch (inbox cofshift / cofask / cofserve / cofno). They pay the price and get the speed boost. NPC customers only appear on the worker's screen.

Rafting up (online): heave to beside another captain anywhere at sea outside docking range of a port (combat.dockRange) and press F to throw them lines. When they press F to make them fast, your ship is hauled alongside theirs and gangplanks run across. Leave the wheel and walk over to board each other’s ships. Either captain casts off from the wheel with F. Rafting needs the updated database rules below (the on fields and raft… inbox kinds).

Visiting docked ships (online): any captain's ship moored at a pier has her gangplank down — walk up it to go aboard, look around the deck and go below or into the captain’s quarters (you can sit in the chairs, but her stores aren't yours). Captains on the pier see ships come in, get warped alongside and drop their plank. If she casts off while you're aboard you hop back onto the pier. On touch screens, when several actions are available the prompt shrinks to one line (“Speak to …”, “Interact with …” or “Press interact for options”); tap ◆ to pick.

Bribes, clothes and ship names: while a nation wants you, its governor takes a bribe of town.bribePerStar (150g) per star to clear it. Wanted stars otherwise fade at one per in-game day. At the clothier, Wear tries an item on the preview in the chosen colour without buying it. The shipwright repaints your ship's name for renameCost (25g).

Port Royal's harbour town

Port Royal is the only port with a harbour layout; every other town uses the standard layout. Port Royal's harbour is built by (buildHarbor in src/ports2d.js, settings in HB):

Resources and progression

Map and HUD

The HUD shows hull, captain's health, crew, morale, resources, hold usage, sail level, speed, reload bars (or cutlass moves and pistol reload on foot), wind compass, a minimap and context prompts. In port the minimap shows a street plan of the town (shops, piers, your ship and other captains) instead of the sea. M opens the full chart with ports (visited ones in red), nearby ships and rumoured treasure; in port it opens the town map first, with a World chart button to switch to the chart and back. A full day/night cycle lasts 10 minutes; town lanterns glow at night.

Ships

Buy ships at any Shipwright. Each class has its own mast count, speed, gun deck and hold:

ClassMastsSpeedGuns (max)HoldHullCrewPrice
Sloop1 (midships)Fastest (27)8 (16)60110301,200g
Brig2Slow (20)12 (24)100170503,500g
Frigate3Fast (23)16 (32)80240807,500g
Galleon3Slowest (16)20 (40)12034011013,000g

Sails billow more the fuller you set them — furled, half and full sail each look different. A new ship comes with the standard guns shown first; add more at 160g per pair. Hull and sail upgrades belong to the ship and reset when you change ships, and their cost scales with the ship's size. You can't move to a smaller ship until your cargo and crew fit aboard her.

Fighting on foot

Your captain is fully animated — arms and legs swing as he walks and runs, he tucks up when jumping, and each move below has its own wind-up, strike and recovery.

Six captains, six styles. Each playable captain (avatars in config.js) has their own fighting animation set: the Marquis (balanced cutlass), Bartholomew “Bull” Okafor (brawler), Don Rafael Ibarra (fencer), Anne “Quickstep” Byrne (acrobat), Lin Mei (reverse-grip shadow) and Zahra al-Rais (Barbary corsair).

Missions

Every tavern has a notice board with three contracts, refreshed each in-game day. You can hold up to three at once. They show in the HUD tracker (desktop), in Pause → Missions (where you can abandon them) and on the chart (M).

Beyond the ports

Plantations, monasteries and forts sit on the existing coastline (the land isn't reshaped), each with its own pier. They share one set of plumbing: PG.PLANTS, with abbey: true or garrison: true marking the kind.

Plantations & supply runs (src/supply.js)

Five estates: Negril (Jamaican coffee), Santa Clara (Cuban tobacco), Hacienda del Istmo (Panamanian cacao), Higüey (Hispaniolan sugar) and Plantage Essequibo (a Dutch polder estate in Guiana). Each has a walkable compound and an enterable storehouse. Shopkeepers at the coffee house, general store, tavern, cabinetmaker and shipwright offer supply runs: buy a crate at the named plantation, carry it (hands full — only interact works), stow it in the hold, sail home and set it down in the shop's delivery corner for 900–1500g. Leave the storehouse without paying and the whole plantation turns on you.

Clifftop monasteries (src/abbey.js)

San Lázaro (Cuba), Porta Coeli (Puerto Rico), Port-Salut (Hispaniola), San Miguel (Mosquito Coast) and San José (Guajira). Each has a quay, a switchback stair up the cliff, a gatehouse and a walled cloister with an enterable church. The abbot offers a sanctuary run: lead a hunted refugee down to your ship, sail to the named town, get them past soldiers who attack on sight, and into that town's church.

Coastal forts & raids (src/forts.js)

Nations, law and war

Controls

ActionKeyboard + mouseGamepad (standard layout)Touch (iPhone / iPad)
Raise sailW / ↑RT, D-pad ↑, flick left stick upSail +, or flick joystick up
Lower sailS / ↓LT, D-pad ↓, flick left stick downSail −, or flick joystick down
SteerA / DLeft stick ←→Joystick ←→ (left side of screen)
Fire port broadsideQLBPort
Fire starboard broadsideERBStbd
Slash — tap up to 3× to chain (on foot)J · left-click · ERBSlash
Thrust (on foot)K · middle-clickRTThrust
Block — hold (on foot)L · hold right-clickHold LTHold Block
Gun — pistol, rifle or blunderbuss (on foot)Q · ILBShoot
Aim (on foot)Mouse cursorFacing + auto-aimFacing + auto-aim
Punch (on foot)U · XR3 (click right stick)Punch
Drink a healing tonicH—Tonic button on the HUD
Crew stance: attack / defend (ship lashed alongside)V—Shield/sword button
Trade with a nearby captain (online)Y—◆ → Trade
Chat (online)C · /—◆ → Chat
InventoryClick the ship & captain card—Tap the status card to flip it
Interact (dock, board, shop, set sail)F / EnterXF
Leave / take the wheelGYCentre interact button
WalkWASDLeft stickJoystick
RunShiftL3 (click left stick)Push joystick to the edge
JumpSpaceAJump
Repair with woodRBFix
ZoomMouse wheel / trackpad scrollRight stick up/downDrag up/down on the right half
Map (town map in port; tabs switch to the world chart). Tap/click a spot to set a waypoint; a red arrow then points the way on foot and at sea. Tap the X again to clear it.M / TabBack / ViewMap
PauseEsc / PStart / MenuII
MenusMouse, Esc closesD-pad moves focus, A selects, B closesTap

Phones and tablets

The game runs in portrait or landscape on iPhone, Android and iPad. Touch controls appear automatically (or on the first touch):

Choosing a captain — one captain is shown at a time: use the ‹ › arrows (or the arrow keys) to cycle through them. The last slot, Custom, turns Set Sail into Customize and opens Create your captain, where ‹ › cycle the avatar and the Body, Hair and Colour rows each have their own arrows.

All buttons are at least 44×44 px and sit inside the safe-area insets. Pause → Settings has volume, graphics quality, Invert zoom direction and Reduce screen shake.

File & folder structure

project layout
/index.html            Main file: HUD/menu/touch markup, all CSS, game state, modes, boarding, renderer, main loop
/instructions.html     This guide
/htp.html              Player-facing How to Play (controls and mechanics, tabbed)
/README.md             What the game is and how to play
/manifest.webmanifest  PWA manifest: name, colours, icons (lets browsers install the game)
/sw.js                 Service worker: offline cache so the installed app works without a connection (reads the script list from index.html)
/style.css             Page, HUD and panel styles
/assets/
  logo.svg             Game logo (tricorn skull & crossed cutlasses) used on the title screen and this guide
  icon.svg             Favicon / app icon (logo on a dark rounded tile)
  icon-maskable.svg    Full-bleed version with extra padding for Android adaptive icons
  icon-192.png, icon-512.png, icon-maskable-512.png   PNG app icons for the manifest
  apple-touch-icon.png 180×180 home-screen icon for iPhone / iPad
  favicon-32.png       PNG favicon fallback for older browsers
  parchment.svg        Tiled paper texture for panels
  compass-rose.svg     HUD compass background
  icons/*.svg          Gold, food, rum, balls, wood, crew, cargo, sugar, tobacco, spice
  flag-*.svg           Merchant, navy and pirate flags (used in htp.html)
/src/
  util.js              PG.U shared helpers: random picks, clamp/lerp, string hash, seeded RNG, colour shading, polygons, nearest/spot search
  iso.js               PG.Iso isometric room kit (projection, boxes, lamps, room shell, front wall, particles, motes) + PG.Glow light sprites
  game.js              Game core: settings, view, state, save/load, overlays, per-mode updates, main loop, loading (index.html only links it)
  game-docking.js      Game part: gangplanks, mooring lines, docking, casting off, taking the wheel
  game-naval.js        Game part: broadsides, hits, ramming, repairs, wrecks, grappling and boarding
  game-crewing.js      Game part: working the sails at a mast, sailing as another captain's crew
  game-render.js       Game part: camera, sea/world rendering, wind, sky, on-foot HUD
  mp-trade.js, mp-raft.js, mp-fleet.js, mp-crew.js, mp-social.js   multiplayer.js parts: trading, rafting + PvP, shared sea + town, crewing + helm, chat + weddings
  counter.js           Counter view: every shopkeeper, stall, shelf, desk, altar and notice board as a full-screen scene you pick items from
  counter-art.js       Artwork for the counter view (backdrops, counters, shelves, goods, trinkets, weapons, garments)
  ui-maps.js, ui-shops.js, ui-wardrobe.js                          ui.js parts: minimap + chart, shop/shipyard/governor panels, wardrobe
  missions.js          Notice-board contracts: cargo runs, bounty ships, town duels
  config.js            Every tunable number: world, NPCs, hull classes, prices, melee, view, graphics, controls
  audio.js             Procedural Web Audio (waves, cannon, hits, splashes, slash, clang, pistol, UI)
  input.js             Keyboard, mouse clicks + cursor aim, touch joystick/buttons, Gamepad API
  ports2d.js           Port data (positions, prices) and towns drawn in 3/4 view (ground, buildings, pier, townsfolk)
  world2d.js           Island data & height function, cached pixel terrain chunks, waves, palms, map canvases
  ships2d.js           Hull classes, ship drawing (1–3 masts, gun decks), sailing physics, cannonballs, particles, NPC AI
  combat.js            Articulated captain/boarder rigs + poses, slash/thrust/block, pistol, boarders
  cabins.js            Below deck, captain's quarters (furniture, eat/drink/rest/sit) and your crew working deck and hold
  shipcrew.js          Crews and captains aboard NPC ships, battle stations, ship-to-ship musketry, boarding defence, pirate raids
  ui.js                HUD, minimap (town plan in port), compass, chart / town map, shop/loot panels, pause/settings
  online.js            Firebase: auth, profiles, cloud saves, presence, chat, action events, inbox; PG.Clock (shared world time)
  menu.js              Title menu: offline/online, sign-in, create account, captain profile
  multiplayer.js       Other captains' ships/avatars, chat bubbles, PvP, trading
  coffee.js            Coffee house: room, keeper, shifts (roast, grind, boil, serve), customers, speed boost
  goldicon.js          Turns every "25g" in the UI into the number + gold icon (MutationObserver)
  town.js              PG.Town: civilians, nation guards with vision cones, crime, robbery, wanted levels
  rooms.js             PG.Rooms: building interiors (shipwright, tavern, store, governor, church, cabinetmaker, coffee, storehouse, general's quarters); KSLOT keeps them aligned online
  tavern.js, store.js  PG.Tavern / PG.Store: the tavern and general store in 2:1 isometric, with props, particles and soundscapes
  interiors.js         PG.Interiors: isometric look for every other room (shipwright, governor, church, cabinetmaker, homes, gun deck, quarters)
  homes.js             PG.Homes: houses for sale, rooms to let, cabinetmaker furniture, placing furniture at home
  goods.js             PG.Lux: luxury trinkets, daily stock and rates (hashed from port + day), 2×4 inventory, clothier stock
  deckshare.js         PG.DeckShare: publishes fighting figures to world/crews so PvP boarding and player crews fight on shared decks
  drops.js             PG.Drops: dropped items on town ground or deck; shared via world/drops online
  supply.js            PG.PLANTS + PG.Supply: plantations, storehouses, crate carrying, supply runs
  forts.js             PG.FORTS: coastal forts, town garrisons, bombardment, raids and sacking
  abbey.js             PG.ABBEYS: clifftop monasteries and sanctuary runs
  diplomacy.js         PG.Diplo: war and peace between nations, treaties on governors' desks
  admin.js             PG.Admin: in-game admin console (same tools as god.html)
  ambient.js           PG.Ambient: ground cover, cloud shadows, gulls, pollen, leaves, fireflies
  god.html             Standalone admin page (see Admin console)
/server/               Cloud Functions (username sign-in & reset) — deployed to Firebase, not loaded by the game

Scripts load in the order of the <script src> tags in index.html (classic scripts, no modules, no fetch), sharing a single global namespace window.PG. Every tag carries its own ?v= number (omitted below):

index.html
<script src="src/config.js"></script>
<script src="src/util.js"></script>      <!-- PG.U, needed by everything after it -->
<script src="src/audio.js"></script>
<script src="src/input.js"></script>
<script src="src/ports2d.js"></script>
<script src="src/world2d.js"></script>
<script src="src/ships2d.js"></script>
<script src="src/combat.js"></script>
<script src="src/missions.js"></script>
<script src="src/goldicon.js"></script>
<script src="src/town.js"></script>
<script src="src/rooms.js"></script>
<script src="src/iso.js"></script>
<script src="src/tavern.js"></script>
<script src="src/store.js"></script>
<script src="src/interiors.js"></script>
<script src="src/coffee.js"></script>
<script src="src/homes.js"></script>
<script src="src/cabins.js"></script>
<script src="src/shipcrew.js"></script>
<script src="src/goods.js"></script>
<script src="src/ui-maps.js"></script>      <!-- ui parts, then ui.js -->
<script src="src/ui-shops.js"></script>
<script src="src/ui-wardrobe.js"></script>
<script src="src/ui.js"></script>
<script src="src/counter-art.js"></script>
<script src="src/counter.js"></script>
<script src="src/online.js"></script>
<script src="src/admin.js"></script>
<script src="src/menu.js"></script>
<script src="src/mp-trade.js"></script>     <!-- multiplayer parts, then multiplayer.js -->
<script src="src/mp-raft.js"></script>
<script src="src/mp-fleet.js"></script>
<script src="src/mp-crew.js"></script>
<script src="src/mp-social.js"></script>
<script src="src/multiplayer.js"></script>
<script src="src/deckshare.js"></script>
<script src="src/drops.js"></script>
<script src="src/supply.js"></script>
<script src="src/forts.js"></script>
<script src="src/abbey.js"></script>
<script src="src/diplomacy.js"></script>
<script src="src/game-docking.js"></script>  <!-- game parts, then the core that wires them up -->
<script src="src/game-naval.js"></script>
<script src="src/game-crewing.js"></script>
<script src="src/ambient.js"></script>
<script src="src/game-render.js"></script>
<script src="src/game.js"></script>

Part files. game.js, multiplayer.js and ui.js are each split into a core plus part files. A part file only defines functions: PG.GameParts.docking = function (K) { … }. The core creates a shared object K, calls every part with it, and keeps shared mutable state on it (K.mode, K.player, K.dock …), so all the files read and write the same values. Parts must load before their core.

What each script does

Configuration

All values below live in src/config.js. Save the file and reload the page.

World size and time

src/config.js
world: {
  minX: -5400, maxX: 6300, minZ: -3600, maxZ: 5000,
  dayLengthSec: 600,      // one full day/night cycle in real seconds
  startTime: 0.32,        // 0 = midnight, 0.25 = sunrise, 0.5 = noon (Single Player)
  worldOffset: 0,         // Online World: shifts the shared clock (fraction of a day, 0–1)
  townRadius: 88,         // flat, walkable radius of each port town
  seed: 1715
},
wind: { changeRate: 0.02, minStrength: 0.6, maxStrength: 1.3 },

Geography frame: since config version: 3 the map is laid into game space turned 45°, so screen-up is true north. PG.Geo (bottom of config.js) converts between geo coordinates (e, s — what charts, minimaps and the world bounds use) and game x, z (everything else); inside() and clamp() test against the world rectangle.

The map uses 400 world units per degree of latitude/longitude.

To reshape or add islands, edit the ISLANDS array in src/world2d.js — each blob is [x, z, radiusX, radiusZ, peakHeight, rotation]:

src/world2d.js
{ name: 'Jamaica', blobs: [[-1920, 360, 400, 150, 70, 0.05]] },
{ name: 'My Island', blobs: [[1200, 1500, 180, 120, 30, 0]] },

View

src/config.js
view: { tilt: 0.78, height: 0.62, sailZoom: 2.6, footZoom: 20, minSailZoom: 1.1, maxSailZoom: 6, minFootZoom: 11, maxFootZoom: 34, lookAhead: 1.6 },

tilt sets how steep the view angle looks (1 = straight down). height sets how tall ships, buildings and sails stand. Zoom values are pixels per world unit at sea and on foot.

NPC count and behaviour

src/config.js
npc: {
  maxActive: 8,           // overridden per quality by graphics.*.npcMax
  spawnRadiusMin: 650, spawnRadiusMax: 1150,
  despawnRadius: 1900,
  spawnInterval: 5,
  weights: { merchant: 0.5, navy: 0.2, pirate: 0.3 },
  aggroRange: { pirate: 600 },   // only pirates attack unprovoked
  fleeRange: 340,
  struckSinkDelay: 150
},

Ship classes

src/config.js
hulls: {
  sloop:   { name: 'Sloop',   masts: 1, scale: 0.9,  castle: 1.3, hp: 110, speed: 27, turn: 0.64, cargo: 60,  maxGuns: 16, baseGuns: 8,  crewMax: 30,  reload: 4.2, price: 1200,  upMul: 1 },
  brig:    { name: 'Brig',    masts: 2, scale: 1.35, castle: 1.6, hp: 170, speed: 20, turn: 0.52, cargo: 100, maxGuns: 24, baseGuns: 12, crewMax: 50,  reload: 4.5, price: 3500,  upMul: 1.5 },
  frigate: { name: 'Frigate', masts: 3, scale: 2.1,  castle: 1.8, hp: 240, speed: 23, turn: 0.5,  cargo: 80,  maxGuns: 32, baseGuns: 16, crewMax: 80,  reload: 4.6, price: 7500,  upMul: 2.2 },
  galleon: { name: 'Galleon', masts: 3, scale: 2.5,  castle: 3.0, hp: 340, speed: 16, turn: 0.36, cargo: 120, maxGuns: 40, baseGuns: 20, crewMax: 110, reload: 5.2, price: 13000, upMul: 3 }
},
roles: {   // NPCs: which hulls they sail (array = equal odds, object = weights) + multipliers
  merchant: { label: 'Merchant', hulls: ['sloop', 'brig', 'brig', 'galleon'], hp: 0.55, guns: 0.3, speed: 0.9, crew: 0.4 },
  navy:     { label: 'Navy',     hulls: ['brig', 'frigate', 'frigate'],       hp: 0.85, guns: 0.5, speed: 1.0, crew: 0.9 },
  pirate:   { label: 'Pirate',   hulls: { sloop: 0.55, brig: 0.42, frigate: 0.03 }, hp: 0.7, guns: 0.5, speed: 1.04, crew: 0.8 },
  treasure: { label: 'Treasure', hulls: ['galleon'],                          hp: 0.8, guns: 0.5, speed: 1.0, crew: 1.0 },
  refugee:  { label: 'Refugee',  hulls: ['sloop', 'brig'],                    hp: 0.7, guns: 0.1, speed: 1.0, crew: 0.3 }   // escort missions
},
upgrades: {
  maxLevel: 3,
  hull:  { cost: [400, 900, 1800], hpPct: 0.15 },     // costs x hull upMul
  sails: { cost: [350, 800, 1600], speedPer: 0.08 },
  gunPair: 160, tradeIn: 0.5,
  repairCostPerHp: 2, woodRepairHp: 15, woodPerRepair: 3
},
combat: {
  gunDmg: 8, ballsPerGun: 12,
  muzzleSpeed: 72, gravity: 12, minRange: 25, maxRange: 175, defaultRange: 110,
  chainRange: 0.75, chainDmg: 0.5, chainCost: 2000,   // chain shot: disables, never sinks
  spread: 0.035, boardRange: 38, dockRange: 75,
  ramDmg: 2.2, ramSelf: 0.25, ramMinSpeed: 5
},
paint: { cost: 40, sails: { white, black, purple, red, blue }, hulls: { brown, oak, birch } },
renameCost: 25,

scale sizes the hull and deck, castle sets the stern castle height. Role colours are in the VIS table at the top of src/ships2d.js; mast positions are in MASTS. Loot ranges in loot are per 60 hold units and scale with the captured ship's hold.

Melee and boarding

src/config.js
melee: {
  playerHp: 100, regenPerSec: 3, iframes: 0.5,
  slash:  { dmg: 40, range: 2.3, arc: 1.25, time: 0.42, hitAt: 0.5, lunge: 2.5, knock: 10,
            comboWindow: 0.45, comboDmg: [1, 1, 1.3], comboArc: [1.25, 1.25, 2.3] },
  thrust: { dmg: 20, range: 4.3, arc: 0.35, time: 0.34, hitAt: 0.45, lunge: 7, knock: 5 },
  punch:  { dmg: 9, range: 1.6, arc: 0.85, time: 0.32, hitAt: 0.4, lunge: 1.4, knock: 6 },
  koTime: 15,           // knocked out this long when punched to 0 (fists never kill)
  sheathAfter: 8,       // seconds idle before the blade is sheathed
  block:  { meleeReduce: 0.85, shotReduce: 0.6, arc: 1.4, speedMul: 0.4, parryWindow: 0.25, parryStun: 1.2 },
  pistolDmg: 50, pistolReload: 1.4, aimTime: 0.14, bulletSpeed: 46, autoAimCone: 0.6, autoAimRange: 16
},
boarders: { merchant: 3, pirate: 4, navy: 5, treasure: 6 },   // +1 on frigates, +2 on galleons (max 7)
arms: {   // market-stall weapons; swords multiply slash/thrust, guns replace the pistol
  swords: { cutlass, rapier, sabre, broadsword },        // { price, dmg, reach, speed, len }
  guns:   { pistol, duelling, rifle, blunderbuss }       // { price, dmg, reload, range, pellets, spread, long }
},
medicine: { price: 30, heal: 60, max: 5 },
enemy: {
  guard:    { hp: 75, dmg: 13, speed: 3.7 },
  civ:      { hp: 32, dmg: 7,  speed: 3.3 },
  merchant: { hp: 40, dmg: 9,  speed: 3.0 },
  pirate:   { hp: 55, dmg: 12, speed: 3.6 },
  duelist:  { hp: 160, dmg: 15, speed: 3.9 },
  navy:     { hp: 65, dmg: 13, speed: 3.3 },
  treasure: { hp: 70, dmg: 14, speed: 3.2 },
  gunnerChance: 0.3, windup: 0.45, recover: 0.55, reach: 1.9, shotDmg: 14, shotCooldown: 3.2
},

Missions

src/config.js
missions: {
  maxActive: 3, offersPerPort: 3,
  cargo: { goods: ['sugar', 'tobacco', 'spice', 'food', 'rum'], qty: [6, 16], goldPerUnitPerDeg: 9, base: 80, daysSlack: 2 },
  hunt:  { hulls: { sloop: 0.35, brig: 0.45, frigate: 0.2 }, dist: [800, 2200], goldPerHp: 3, base: 200, searchRadius: 320 },
  duel:  { reward: [300, 650] },
  escort: { base: 120, goldPerDeg: 55, offers: 2 }   // refugee convoys from the priest
},
privateer: { perStar: 10, maxStars: 5, discount: 0.5 },

Towns, homes and luxuries

src/config.js
nations: { english, spanish, dutch, french },   // { name, color, pants, trim, hat, ink } — guard uniforms and UI ink
town: {
  civilians: 9, guards: 4, viewRange: 15, viewHalf: 0.6, civView: 15, civHalf: 0.9, hearRange: 46,
  giveUp: 9, calmDist: 24,
  walkSpeed: 1.7, patrolSpeed: 2.1, fleeSpeed: 5.4, braveChance: 0.35, robGold: [12, 70], purse: [4, 30],
  maxWanted: 5, attackOnSight: 3, wantedDecayDays: 1, bribePerStar: 150,
  drink: 4, coffee: 3, drunkDecay: 40, passOut: 5
},
homes: { price: 2500, rent: 25, resell: 0.5, holdMs: 650, furniture: { bed, table, chair, bench, chest, wardrobe, shelf, desk, rug } },
lux: {
  slots: 8, roseStack: 20, medsStack: 10, roses: [10, 20], specialChance: 0.3, strangerChance: 0.1,
  buy: [0.9, 1.2], sell: [0.65, 1.4],
  items: { box, meds, rose, chocolates, shell, locket, goldneck, silverband, ring, jade, ruby }
},
clothes: { dyeFee: 25, colors: { … }, slots: { hat, coat, shirt, pants, dress }, items: { … } },
avatars: { captain, bull, rafael, anne, mei, zahra },   // { name, style, blurb, moves, pal }
marriage: { dmgMul: 0.75, moraleMul: 0.5 },

Cargo pay = base + qty × distance-in-degrees × goldPerUnitPerDeg; the deadline is about one day per 6° plus daysSlack. Bounty ship names and duelist names are lists at the top of src/missions.js.

range is in world units, arc is the half-angle of the hit cone in radians, time is the whole move and hitAt the fraction of it where the blade connects. Poses (keyframe angles for each limb) are the IDLE, SL_WIND, SL_HIT, TH_*, BLOCK and JUMP tables in src/combat.js; colours are in PAL_PLAYER / PALS.

Prices

Each good has a base price; every port multiplies it. Selling pays sellFactor of the buy price.

src/config.js
prices: {
  base: { food: 10, rum: 22, balls: 3, wood: 16, sugar: 55, tobacco: 85, spice: 150 },
  sellFactor: 0.8,
  hireCrew: 25, tavernRound: 40, rumor: 60
},
src/ports2d.js — per-port multipliers
{ id: 'havana', name: 'Havana', x: -3950, z: -1560, dir: [0, -1], flag: 'navy',
  prices: { food: 0.9, rum: 1.1, balls: 1.0, wood: 1.1, sugar: 0.7, tobacco: 0.6, spice: 1.2 },
  blurb: 'Jewel of the Spanish Main. Tobacco is cheap, but the garrison is watchful.' },

dir is the direction from the town centre toward open water; the pier is built along it.

Crew, food and rum

src/config.js
crew: {
  start: 18,
  foodPerCrewPerMin: 0.03,
  rumPerCrewPerMin: 0.02,
  perGun: 0.75            // hands per gun for full reload speed (min 6)
},
player: {
  startGold: 400, startPort: 'portroyal', startHull: 'sloop',
  start: { food: 12, rum: 8, balls: 60, wood: 4, sugar: 0, tobacco: 0, spice: 0 },
  deathGoldPenalty: 0.3,
  walkSpeed: 4.6, runSpeed: 8.5, jumpSpeed: 6.4, gravity: 16
},

Controls

Keyboard bindings use KeyboardEvent.code values, so they follow physical key positions on any layout. Gamepad entries are Standard Gamepad button indices. Mouse buttons (left slash, middle thrust, right block) are built into src/input.js.

src/config.js
controls: {
  keyboard: {
    forward: ['KeyW', 'ArrowUp'], back: ['KeyS', 'ArrowDown'],
    left: ['KeyA', 'ArrowLeft'], right: ['KeyD', 'ArrowRight'],
    firePort: ['KeyQ'], fireStarboard: ['KeyE'],
    interact: ['KeyF', 'Enter'], wheel: ['KeyG'], map: ['KeyM', 'Tab'],
    pause: ['Escape', 'KeyP'], jump: ['Space'], run: ['ShiftLeft', 'ShiftRight'], repair: ['KeyR'],
    slash: ['KeyJ'], thrust: ['KeyK'], block: ['KeyL'], shoot: ['KeyI'],
    trade: ['KeyY'], heal: ['KeyH'], punch: ['KeyU', 'KeyX'], stance: ['KeyV']
  },
  gamepad: {   // several actions may share a button (LT/RT: sails at sea, block/thrust on foot)
    jump: 0, run: 10, interact: 2, wheel: 3, firePort: 4, fireStarboard: 5,
    back: 6, forward: 7, block: 6, thrust: 7, map: 8, pause: 9, repair: 1, punch: 11, dUp: 12, dDown: 13
  },
  deadzone: 0.18
},

Graphics quality

Pick Low / Medium / High in Pause → Settings. Pixel ratio, wave count, effect budget, night lights and NPC count change live; vegetation density applies on the next reload. chunks caps cached terrain chunks, reliefImages the cached relief images, and decor the ambient ground-cover sprites (src/ambient.js).

src/config.js
graphics: {
  low:    { pixelRatio: 1,   npcMax: 5, vegetation: 0.4,  waves: 120, effects: 180, lights: false, chunks: 48,  reliefImages: 20, decor: 500 },
  medium: { pixelRatio: 1.5, npcMax: 7, vegetation: 0.75, waves: 220, effects: 300, lights: true,  chunks: 80,  reliefImages: 26, decor: 1200 },
  high:   { pixelRatio: 2,   npcMax: 9, vegetation: 1.0,  waves: 340, effects: 420, lights: true,  chunks: 160, reliefImages: 36, decor: 2600 }
},
defaultSettings: { volume: 0.7, quality: 'medium', invertY: false, invertX: false },

Save data

Older saves load fine: missing ship data defaults to a sloop, and the old cargo upgrade is dropped.

The save is one JSON object under the key caribbean-plunder-2d-save-v1; settings live under caribbean-plunder-2d-settings-v1 (set by saveKey / settingsKey in config.js). Example shape:

localStorage["caribbean-plunder-2d-save-v1"]
{
  "v": 1,
  "G": {
    "gold": 757, "crew": 18, "morale": 82, "health": 100,
    "hull": "brig", "guns": 14,
    "missions": [{ "id": "m42", "type": "cargo", "to": "nassau", "good": "sugar", "qty": 10, "reward": 190, "due": 3.9 }],
    "cargo": { "food": 12, "rum": 8, "balls": 66, "wood": 5, "sugar": 9, "tobacco": 4, "spice": 1 },
    "up": { "hull": 1, "sails": 0 },
    "lastPort": "portroyal", "time": 1.42,
    "rumors": [{ "x": -900, "z": 1300, "heading": 2.1, "hp": 240 }],
    "visited": ["portroyal", "tortuga"], "shipName": "The Black Gull",
    "stats": { "sunk": 3, "looted": 2, "boarded": 2, "foes": 8 }
  },
  "hp": 118, "mode": "town", "port": "portroyal",
  "x": -1712.4, "z": 553.1, "heading": 0, "sail": 0, "savedAt": 1790000000000
}

To wipe a save, run this in the browser console on the game page:

console
localStorage.removeItem('caribbean-plunder-2d-save-v1');

Online world (Firebase)

Single Player needs nothing. Online World uses the Firebase project gamedata-e4388, which it shares with the games Hekable and Battleground. The config is already built into src/online.js; it's shown here for reference.

1 · Firebase config

firebaseConfig (already in src/online.js)
export const firebaseConfig = {
  apiKey: "AIzaSyClt9NmeC2JkFGpRGMH6UJuV1-N1g4kqWA",
  authDomain: "gamedata-e4388.firebaseapp.com",
  databaseURL: "https://gamedata-e4388-default-rtdb.firebaseio.com",
  projectId: "gamedata-e4388",
  storageBucket: "gamedata-e4388.firebasestorage.app",
  messagingSenderId: "997094349472",
  appId: "1:997094349472:web:3cad098dbdfa1aff8747c5",
  measurementId: "G-HSPN22E0F2"
};

2 · Console setup

3 · Realtime Database rules

Paste into Realtime Database → Rules and click Publish. This replaces the whole rules document, so it includes the hekable and battleground1 rules alongside this game's pirates section.

Rules sync (Oct 2026): pirates section unchanged. hekable replaced — the single lobby/rooms nodes are now per-code lobbies/$code and matches/$id. New battleground1 section (signed-in, non-anonymous users only). Publishing the full document below is safe for Pirates.
Realtime Database rules
{
  "rules": {
    "pirates": {
      "usernames": {
        ".read": "auth != null && root.child('pirates/admins/' + auth.uid).val() === true",
        "$name": {
          ".read": true,
          ".write": "auth != null && !data.exists() && !root.child('pirates/users/' + auth.uid + '/profile').exists()",
          ".validate": "newData.isString() && newData.val() === auth.uid && $name.matches(/^[a-z0-9_]{3,20}$/)"
        }
      },
      "private": {
        ".read": false,
        ".write": false
      },
      "admins": {
        ".read": false,
        ".write": false,
        "$uid": {
          ".read": "auth != null && auth.uid === $uid"
        }
      },
      "users": {
        "$uid": {
          ".read": "auth != null && (auth.uid === $uid || root.child('pirates/admins/' + auth.uid).val() === true)",
          ".write": "auth != null && ((auth.uid === $uid && (newData.child('profile').exists() || !data.child('profile').exists())) || root.child('pirates/admins/' + auth.uid).val() === true)",
          "profile": {
            ".validate": "newData.hasChildren(['username', 'displayName', 'avatar']) && newData.parent().parent().parent().child('usernames/' + newData.child('username').val().toLowerCase()).val() === $uid",
            "username": {
              ".validate": "newData.isString() && (!data.exists() || newData.val() === data.val())"
            },
            "displayName": {
              ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 32"
            },
            "avatar": {
              ".validate": "newData.isString() && newData.val().length <= 24"
            },
            "created": {
              ".validate": "newData.isNumber()"
            },
            "$other": {
              ".validate": "false"
            }
          },
          "save": {
            ".validate": "newData.isString() && newData.val().length <= 500000"
          },
          "$other": {
            ".validate": "false"
          }
        }
      },
      "leaderboard": {
        ".read": "auth != null",
        "$uid": {
          ".write": "auth != null && auth.uid === $uid",
          ".validate": "newData.hasChildren(['n', 'p', 'r', 's', 'c', 'h'])",
          "n": { ".validate": "newData.isString() && newData.val().length <= 32" },
          "a": { ".validate": "newData.isString() && newData.val().length <= 24" },
          "p": { ".validate": "newData.isNumber() && newData.val() >= 0" },
          "r": { ".validate": "newData.isNumber() && newData.val() >= 0" },
          "s": { ".validate": "newData.isNumber() && newData.val() >= 0" },
          "c": { ".validate": "newData.isNumber() && newData.val() >= 0" },
          "h": { ".validate": "newData.isNumber() && newData.val() >= 0" },
          "t": { ".validate": "newData.isNumber()" },
          "$other": { ".validate": "false" }
        }
      },
      "world": {
        "players": {
          ".read": "auth != null",
          "$uid": {
            ".write": "auth != null && auth.uid === $uid",
            ".validate": "newData.hasChildren(['n', 'a', 'x', 'z', 'h', 'm', 't'])",
            "n": {
              ".validate": "newData.isString() && newData.val().length <= 32"
            },
            "a": {
              ".validate": "newData.isString() && newData.val().length <= 24"
            },
            "x": {
              ".validate": "newData.isNumber()"
            },
            "z": {
              ".validate": "newData.isNumber()"
            },
            "h": {
              ".validate": "newData.isNumber()"
            },
            "v": {
              ".validate": "newData.isNumber()"
            },
            "s": {
              ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 2"
            },
            "hp": {
              ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 1"
            },
            "hull": {
              ".validate": "newData.isString() && newData.val().length <= 16"
            },
            "m": {
              ".validate": "newData.val() === 'sea' || newData.val() === 'town'"
            },
            "port": {
              ".validate": "newData.isString() && newData.val().length <= 32"
            },
            "dead": {
              ".validate": "newData.isBoolean()"
            },
            "px": {
              ".validate": "newData.isNumber()"
            },
            "pz": {
              ".validate": "newData.isNumber()"
            },
            "fx": {
              ".validate": "newData.isNumber()"
            },
            "fz": {
              ".validate": "newData.isNumber()"
            },
            "mv": {
              ".validate": "newData.isNumber()"
            },
            "in": {
              ".validate": "newData.isBoolean()"
            },
            "rm": {
              ".validate": "newData.isString() && newData.val().length <= 16"
            },
            "ring": {
              ".validate": "newData.isBoolean()"
            },
            "hr": {
              ".validate": "newData.isNumber() && newData.val() >= -1 && newData.val() <= 1"
            },
            "hs": {
              ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 2"
            },
            "hw": {
              ".validate": "newData.isString() && newData.val().length <= 40"
            },
            "sn": {
              ".validate": "newData.isString() && newData.val().length <= 28"
            },
            "sp": {
              ".validate": "newData.isString() && newData.val().length <= 40"
            },
            "on": {
              ".validate": "newData.isString() && newData.val().length <= 40"
            },
            "fh": {
              ".validate": "newData.isBoolean()"
            },
            "th": {
              ".validate": "newData.isBoolean()"
            },
            "ph": {
              ".validate": "newData.isString() && newData.val().length <= 16"
            },
            "ps": {
              ".validate": "newData.isString() && newData.val().length <= 16"
            },
            "b": {
              ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 15"
            },
            "c": {
              ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 120"
            },
            "ct": {
              ".validate": "newData.isNumber() && newData.val() <= now + 10000"
            },
            "t": {
              ".validate": "newData.isNumber() && newData.val() <= now"
            },
            "$other": {
              ".validate": "false"
            }
          }
        },
        "acts": {
          ".read": "auth != null",
          ".indexOn": [
            "t"
          ],
          "$act": {
            ".write": "auth != null && (newData.exists() ? (!data.exists() && newData.child('u').val() === auth.uid) : (data.child('u').val() === auth.uid || data.child('t').val() < now - 30000))",
            ".validate": "newData.hasChildren(['u', 'k', 't']) && newData.child('t').val() === now",
            "k": {
              ".validate": "newData.val() === 'fire' || newData.val() === 'melee' || newData.val() === 'shot'"
            },
            "kind": {
              ".validate": "newData.isString() && newData.val().length <= 12"
            },
            "port": {
              ".validate": "newData.isString() && newData.val().length <= 32"
            },
            "hull": {
              ".validate": "newData.isString() && newData.val().length <= 16"
            },
            "on": {
              ".validate": "newData.isString() && newData.val().length <= 40"
            },
            "rm": {
              ".validate": "newData.isString() && newData.val().length <= 16"
            },
            "u": {
              ".validate": "newData.isString()"
            },
            "t": {
              ".validate": "newData.isNumber()"
            },
            "$num": {
              ".validate": "newData.isNumber()"
            }
          }
        },
        "fleets": {
          ".read": "auth != null",
          "$uid": {
            ".write": "auth != null && auth.uid === $uid",
            ".validate": "newData.hasChildren(['s', 't'])",
            "s": {
              ".validate": "newData.isString() && newData.val().length <= 8000"
            },
            "t": {
              ".validate": "newData.isNumber() && newData.val() <= now"
            },
            "$other": {
              ".validate": "false"
            }
          }
        },
        "crews": {
          ".read": "auth != null",
          "$uid": {
            ".write": "auth != null && auth.uid === $uid",
            ".validate": "newData.hasChildren(['s', 't'])",
            "s": {
              ".validate": "newData.isString() && newData.val().length <= 6000"
            },
            "t": {
              ".validate": "newData.isNumber() && newData.val() <= now"
            },
            "$other": {
              ".validate": "false"
            }
          }
        },
        "homes": {
          ".read": "auth != null",
          "$key": {
            ".write": "auth != null && (!data.exists() || data.child('u').val() === auth.uid || (data.child('k').val() === 'rent' && data.child('t').val() < now - 259200000)) && (!newData.exists() || newData.child('u').val() === auth.uid)",
            ".validate": "newData.hasChildren(['u', 'n', 'k', 't']) && $key.length <= 40",
            "u": { ".validate": "newData.isString()" },
            "n": { ".validate": "newData.isString() && newData.val().length <= 32" },
            "k": { ".validate": "newData.val() === 'own' || newData.val() === 'rent'" },
            "f": { ".validate": "newData.isString() && newData.val().length <= 4000" },
            "t": { ".validate": "newData.isNumber() && newData.val() <= now" },
            "$other": { ".validate": "false" }
          }
        },
        "drops": {
          ".read": "auth != null",
          "$id": {
            ".write": "auth != null && (data.exists() || newData.child('u').val() === auth.uid)",
            ".validate": "!newData.exists() || (newData.hasChildren(['u', 'k', 'n', 'sp', 'x', 'z', 't']) && (!data.exists() || (newData.child('u').val() === data.child('u').val() && newData.child('n').val() < data.child('n').val())))",
            "k": { ".validate": "newData.isString() && newData.val().length <= 16" },
            "n": { ".validate": "newData.isNumber() && newData.val() >= 1 && (newData.val() <= 20 || (newData.parent().child('k').val() === 'gold' && newData.val() <= 10000000))" },
            "sp": { ".validate": "newData.isString() && newData.val().length <= 48" },
            "x": { ".validate": "newData.isNumber()" },
            "z": { ".validate": "newData.isNumber()" },
            "u": { ".validate": "newData.isString()" },
            "t": { ".validate": "newData.isNumber() && newData.val() <= now" },
            "$other": { ".validate": "false" }
          }
        }
      },
      "inbox": {
        "$uid": {
          ".read": "auth != null && auth.uid === $uid",
          "$msg": {
            ".write": "auth != null && ((!data.exists() && newData.child('from').val() === auth.uid) || (auth.uid === $uid && !newData.exists()))",
            ".validate": "newData.hasChildren(['k', 'from', 't']) && newData.child('t').val() === now && newData.child('k').val().matches(/^(offer|accept|decline|cancel|done|fail|plunder|raft|raftok|raftno|raftset|raftend|crew|crewok|crewno|crewend|crewfire|nhit|nloot|tclaim|wed|wedyes|wedno|pvpdis|pvpgrab|pvplost|pvptake|chit|shipuse|shipuseok|shipuseno|cofshift|cofask|cofserve|cofno)$/)",
            "from": {
              ".validate": "newData.isString()"
            },
            "name": {
              ".validate": "newData.isString() && newData.val().length <= 32"
            },
            "k": {
              ".validate": "newData.isString()"
            },
            "id": {
              ".validate": "newData.isString() && newData.val().length <= 32"
            },
            "how": {
              ".validate": "newData.val() === 'sea' || newData.val() === 'land'"
            },
            "ring": {
              ".validate": "newData.isBoolean()"
            },
            "gold": {
              ".validate": "newData.isNumber() && newData.val() >= 0"
            },
            "nid": {
              ".validate": "newData.isString() && newData.val().length <= 24"
            },
            "dmg": {
              ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 1000"
            },
            "give": {
              "$g": {
                ".validate": "newData.isNumber() && newData.val() >= 0"
              }
            },
            "want": {
              "$g": {
                ".validate": "newData.isNumber() && newData.val() >= 0"
              }
            },
            "t": {
              ".validate": "newData.isNumber()"
            },
            "$other": {
              ".validate": "false"
            }
          }
        }
      }
    },
    "hekable": {
      "lobbies": {
        ".read": "auth != null && query.orderByChild === 'meta/hb' && query.endAt <= now - 3600000 && query.limitToFirst <= 25",
        ".indexOn": ["meta/hb"],
        "$code": {
          ".read": "auth != null",
          ".write": "auth != null && !newData.exists() && (data.child('meta/hostUid').val() === auth.uid || data.child('meta/hb').val() < now - 3600000)",
          ".validate": "$code.matches(/^[A-Z0-9]{6}$/)",
          "meta": {
            ".write": "auth != null && (data.child('hostUid').val() === auth.uid || (!data.exists() && newData.child('hostUid').val() === auth.uid))",
            ".validate": "newData.hasChildren(['hostUid', 'state', 'mode', 'created', 'hb'])",
            "hostUid": {
              ".write": "auth != null && newData.val() === auth.uid && root.child('hekable/lobbies/' + $code + '/players/' + auth.uid).exists() && (!data.exists() || root.child('hekable/lobbies/' + $code + '/meta/hb').val() < now - 10000)",
              ".validate": "newData.isString() && newData.val().length <= 128 && newData.parent().parent().child('players/' + newData.val() + '/guest').val() === false"
            },
            "hb": {
              ".write": "auth != null && newData.parent().child('hostUid').val() === auth.uid && root.child('hekable/lobbies/' + $code + '/players/' + auth.uid).exists()",
              ".validate": "newData.isNumber() && newData.val() <= now"
            },
            "state": { ".validate": "newData.isString() && newData.val().matches(/^(lobby|team-decision|role-pick|ai-fill|ready-check|countdown|in-match|results|disbanded)$/)" },
            "mode": { ".validate": "newData.isString() && newData.val().matches(/^(solo|coop|versus|mixed)$/)" },
            "created": { ".validate": "newData.isNumber() && newData.val() <= now" },
            "countdownAt": { ".validate": "newData.isNumber()" },
            "round": { ".validate": "newData.isNumber() && newData.val() >= 0" },
            "settings": {
              "teamSizes": {
                ".validate": "newData.hasChildren(['atk', 'def', 'spec']) && newData.child('atk').val() + newData.child('def').val() + newData.child('spec').val() <= 10",
                "atk": { ".validate": "newData.isNumber() && newData.val() >= 1 && newData.val() <= 5" },
                "def": { ".validate": "newData.isNumber() && newData.val() >= 1 && newData.val() <= 4" },
                "spec": { ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 8" },
                "$other": { ".validate": "false" }
              },
              "teamMethod": { ".validate": "newData.isString() && newData.val().matches(/^(host|choose|random|balanced)$/)" },
              "aiDifficulty": {
                "atk": { ".validate": "newData.isString() && newData.val().matches(/^(easy|normal|hard)$/)" },
                "def": { ".validate": "newData.isString() && newData.val().matches(/^(easy|normal|hard)$/)" },
                "$other": { ".validate": "false" }
              },
              "targetPool": { ".validate": "newData.isString() && newData.val().length <= 200" },
              "modifier": { ".validate": "newData.isString() && newData.val().length <= 32" },
              "midJoin": { ".validate": "newData.isBoolean()" },
              "ranked": { ".validate": "newData.isBoolean()" },
              "hybridRule": { ".validate": "newData.isString() && newData.val().matches(/^(either|both)$/)" },
              "humanSide": { ".validate": "newData.isString() && newData.val().matches(/^(atk|def)$/)" },
              "$other": { ".validate": "false" }
            },
            "result": { ".validate": "newData.isString() && newData.val().length <= 32" },
            "endedAt": { ".validate": "newData.isNumber() && newData.val() <= now" },
            "$other": { ".validate": "false" }
          },
          "slots": {
            "$i": {
              ".write": "auth != null && ((root.child('hekable/lobbies/' + $code + '/meta/hostUid').val() === auth.uid || (!root.child('hekable/lobbies/' + $code + '/meta').exists() && newData.parent().parent().child('meta/hostUid').val() === auth.uid)) || (newData.exists() && data.exists() && newData.child('team').val() === data.child('team').val() && ((!data.child('uid').exists() && newData.child('uid').val() === auth.uid && newData.child('ai').val() === false && newData.parent().parent().child('players/' + auth.uid + '/slot').val() === $i && (data.child('ai').val() === false ? (root.child('hekable/lobbies/' + $code + '/meta/state').val() !== 'in-match' || root.child('hekable/lobbies/' + $code + '/meta/settings/midJoin').val() === true) : (root.child('hekable/lobbies/' + $code + '/meta/state').val() === 'in-match' && root.child('hekable/lobbies/' + $code + '/meta/settings/midJoin').val() === true))) || (data.child('uid').val() === auth.uid && newData.child('ai').val() === data.child('ai').val()))))",
              ".validate": "$i.matches(/^[0-9]$/) && newData.hasChildren(['team', 'ai'])",
              "team": { ".validate": "newData.isString() && newData.val().matches(/^(atk|def|spec)$/)" },
              "role": { ".validate": "newData.isString() && newData.val().matches(/^(infiltrator|social|remote|scout|driver|guard|soc|itadmin|coordinator)?$/)" },
              "uid": { ".validate": "newData.isString() && newData.val().length <= 128" },
              "ai": { ".validate": "newData.isBoolean()" },
              "name": { ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 24" },
              "ready": { ".validate": "newData.isBoolean()" },
              "lk": { ".validate": "newData.isString() && newData.val().length <= 16" },
              "sk": { ".validate": "newData.isString() && newData.val().length <= 8" },
              "$other": { ".validate": "false" }
            }
          },
          "players": {
            "$uid": {
              ".write": "auth != null && (auth.uid === $uid || (root.child('hekable/lobbies/' + $code + '/meta/hostUid').val() === auth.uid || (!root.child('hekable/lobbies/' + $code + '/meta').exists() && newData.parent().parent().child('meta/hostUid').val() === auth.uid)))",
              ".validate": "newData.hasChildren(['name', 'joinOrder', 'slot', 'guest'])",
              "name": { ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 24" },
              "joinOrder": { ".validate": "newData.isNumber() && (data.exists() ? newData.val() === data.val() : newData.val() === now)" },
              "slot": { ".validate": "newData.isString() && newData.val().matches(/^[0-9]$/) && newData.parent().parent().parent().child('slots/' + newData.val() + '/uid').val() === $uid" },
              "guest": { ".validate": "newData.isBoolean() && (auth.uid === $uid ? newData.val() === (auth.token.firebase.sign_in_provider === 'anonymous') : newData.val() === data.val())" },
              "device": { ".validate": "newData.isString() && newData.val().matches(/^(desktop|mobile)$/)" },
              "online": { ".validate": "newData.isBoolean()" },
              "$other": { ".validate": "false" }
            }
          },
          "chat": {
            "$msg": {
              ".write": "auth != null && ((!data.exists() && newData.child('u').val() === auth.uid && root.child('hekable/lobbies/' + $code + '/players/' + auth.uid).exists()) || (!newData.exists() && root.child('hekable/lobbies/' + $code + '/meta/hostUid').val() === auth.uid))",
              ".validate": "newData.hasChildren(['u', 'n', 'm', 't'])",
              "u": { ".validate": "newData.isString() && newData.val().length <= 128" },
              "n": { ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 24" },
              "m": { ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 200" },
              "t": { ".validate": "newData.val() === now" },
              "$other": { ".validate": "false" }
            }
          },
          "$other": { ".validate": "false" }
        }
      },
      "matches": {
        "$id": {
          ".validate": "$id.matches(/^[A-Z0-9]{6}$/)",
          ".write": "auth != null && !newData.exists() && (root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid || !root.child('hekable/lobbies/' + $id).exists() || root.child('hekable/lobbies/' + $id + '/meta/hb').val() < now - 3600000)",
          "members": {
            ".read": "auth != null",
            ".write": "auth != null && root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid",
            "$uid": { ".validate": "newData.isString() && newData.val().matches(/^(atk|def|spec)$/)" }
          },
          "seed": {
            ".read": "auth != null && root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid",
            ".write": "auth != null && root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid"
          },
          "startTime": {
            ".read": "auth != null && (root.child('hekable/matches/' + $id + '/members/' + auth.uid).exists() || root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid)",
            ".write": "auth != null && root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid",
            ".validate": "newData.isNumber() && newData.val() <= now + 60000"
          },
          "inbox": {
            "$uid": {
              ".read": "auth != null && (auth.uid === $uid || root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid)",
              ".write": "auth != null && root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid",
              "$cmd": {
                ".write": "auth != null && auth.uid === $uid && ((!data.exists() && root.child('hekable/matches/' + $id + '/members/' + auth.uid).exists()) || !newData.exists())",
                ".validate": "newData.hasChildren(['k', 'seq', 't'])",
                "k": { ".validate": "newData.isString() && newData.val().matches(/^[a-z][a-zA-Z0-9_.]{0,31}$/)" },
                "seq": { ".validate": "newData.isNumber() && newData.val() >= 0" },
                "t": { ".validate": "newData.val() === now" },
                "slot": { ".validate": "newData.isString() && newData.val().matches(/^[0-9]$/)" },
                "p": { ".validate": "newData.isString() && newData.val().length <= 1000" },
                "$other": { ".validate": "false" }
              }
            }
          },
          "public": {
            ".read": "auth != null && (root.child('hekable/matches/' + $id + '/members/' + auth.uid).exists() || root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid)",
            ".write": "auth != null && root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid"
          },
          "team": {
            "$side": {
              ".read": "auth != null && (root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid || root.child('hekable/matches/' + $id + '/members/' + auth.uid).val() === $side)",
              ".write": "auth != null && root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid",
              ".validate": "$side.matches(/^(atk|def)$/)"
            }
          },
          "checkpoint": {
            ".read": "auth != null && (root.child('hekable/matches/' + $id + '/members/' + auth.uid).exists() || root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid)",
            ".write": "auth != null && root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid"
          },
          "log": {
            ".read": "auth != null && (root.child('hekable/matches/' + $id + '/members/' + auth.uid).exists() || root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid)",
            "$e": { ".write": "auth != null && !data.exists() && root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid" }
          },
          "rooms": {
            "$room": {
              ".read": "auth != null && (root.child('hekable/matches/' + $id + '/members/' + auth.uid).exists() || root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid)",
              ".validate": "$room.matches(/^[a-zA-Z]{2,16}$/)",
              "$uid": {
                ".write": "auth != null && (auth.uid === $uid || ($uid.matches(/^ai-[0-9]$/) && (!newData.exists() || root.child('hekable/lobbies/' + $id + '/meta/hostUid').val() === auth.uid)))",
                ".validate": "newData.hasChildren(['n', 'tm', 'lk', 'sk', 'x', 'y', 'st', 't'])",
                "n": { ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 24" },
                "tm": { ".validate": "newData.val() === 'atk' || newData.val() === 'def'" },
                "lk": { ".validate": "newData.isString() && newData.val().length <= 16" },
                "sk": { ".validate": "newData.isString() && newData.val().length <= 8" },
                "dg": { ".validate": "newData.isString() && newData.val().length <= 16 && newData.parent().child('tm').val() === 'atk'" },
                "x": { ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 64" },
                "y": { ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 64" },
                "st": { ".validate": "newData.isString() && newData.val().matches(/^(idle|walk|run|sit|desk)$/)" },
                "f": { ".validate": "newData.val() === 'front' || newData.val() === 'back'" },
                "fl": { ".validate": "newData.isBoolean()" },
                "d": { ".validate": "newData.isNumber() && newData.val() >= -180 && newData.val() <= 180" },
                "sz": { ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 100" },
                "ty": { ".validate": "newData.isBoolean()" },
                "t": { ".validate": "newData.isNumber() && newData.val() <= now" },
                "$other": { ".validate": "false" }
              }
            }
          },
          "$other": { ".validate": "false" }
        }
      },
      "$other": { ".validate": "false" }
    },
    "battleground1": {
      "users": {
        "$uid": {
          ".read": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous' && auth.uid === $uid",
          ".write": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous' && auth.uid === $uid",
          "profile": {
            ".validate": "newData.hasChildren(['name', 'email', 'provider', 't'])",
            "name": { ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 40" },
            "email": { ".validate": "newData.isString() && newData.val().length <= 120" },
            "provider": { ".validate": "newData.val() === 'google' || newData.val() === 'password'" },
            "t": { ".validate": "newData.isNumber() && newData.val() <= now" },
            "$other": { ".validate": "false" }
          },
          "stats": {
            ".validate": "newData.hasChildren(['kills', 'seconds'])",
            "kills": { ".validate": "newData.isNumber() && newData.val() >= 0 && (!data.exists() || newData.val() >= data.val())" },
            "seconds": { ".validate": "newData.isNumber() && newData.val() >= 0 && (!data.exists() || newData.val() >= data.val())" },
            "deaths": { ".validate": "newData.isNumber() && newData.val() >= 0 && (!data.exists() || newData.val() >= data.val())" },
            "games": { ".validate": "newData.isNumber() && newData.val() >= 0 && (!data.exists() || newData.val() >= data.val())" },
            "best": { ".validate": "newData.isNumber() && newData.val() >= 0 && (!data.exists() || newData.val() >= data.val())" },
            "t": { ".validate": "newData.isNumber() && newData.val() <= now" },
            "$other": { ".validate": "false" }
          },
          "$other": { ".validate": "false" }
        }
      },
      "lobbies": {
        ".read": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous'",
        ".indexOn": ["t"],
        "$code": {
          ".write": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous' && (!data.exists() || data.child('h').val() === auth.uid || data.child('t').val() < now - 120000)",
          ".validate": "$code.matches(/^[A-Z0-9]{5}$/) && newData.hasChildren(['h', 'n', 'c', 'm', 's', 't'])",
          "h": { ".validate": "newData.val() === auth.uid" },
          "n": { ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 40" },
          "c": { ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 10" },
          "m": { ".validate": "newData.isNumber() && newData.val() >= 1 && newData.val() <= 10" },
          "s": { ".validate": "newData.isString() && newData.val().length <= 40" },
          "t": { ".validate": "newData.isNumber() && newData.val() <= now" },
          "$other": { ".validate": "false" }
        }
      },
      "rooms": {
        "$code": {
          ".write": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous' && !newData.exists() && data.child('meta/host').val() === auth.uid",
          ".validate": "$code.matches(/^[A-Z0-9]{5}$/)",
          "meta": {
            ".read": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous'",
            ".write": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous' && (data.exists() ? data.child('host').val() === auth.uid : newData.child('host').val() === auth.uid)",
            ".validate": "newData.hasChildren(['host', 't'])",
            "host": { ".validate": "newData.isString() && newData.val().length <= 128" },
            "t": { ".validate": "newData.isNumber() && newData.val() <= now" },
            "$other": { ".validate": "false" }
          },
          "state": {
            ".read": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous'",
            ".write": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous' && root.child('battleground1/rooms/' + $code + '/meta/host').val() === auth.uid",
            ".validate": "newData.hasChildren(['d', 't'])",
            "d": { ".validate": "newData.isString() && newData.val().length <= 120000" },
            "t": { ".validate": "newData.isNumber() && newData.val() <= now" },
            "$other": { ".validate": "false" }
          },
          "players": {
            ".read": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous'",
            "$uid": {
              ".write": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous' && (auth.uid === $uid || root.child('battleground1/rooms/' + $code + '/meta/host').val() === auth.uid)",
              ".validate": "newData.hasChildren(['n', 'p', 'r', 't'])",
              "n": { ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 24" },
              "p": { ".validate": "newData.isString() && newData.val().matches(/^(brit|us|ru),[01],(assault|medic|engineer|support)$/)" },
              "r": { ".validate": "newData.isNumber() && newData.val() >= 0" },
              "t": { ".validate": "newData.isNumber() && newData.val() <= now" },
              "$other": { ".validate": "false" }
            }
          },
          "inputs": {
            "$uid": {
              ".read": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous' && (auth.uid === $uid || root.child('battleground1/rooms/' + $code + '/meta/host').val() === auth.uid)",
              ".write": "auth != null && auth.token.firebase.sign_in_provider != 'anonymous' && auth.uid === $uid",
              ".validate": "newData.hasChildren(['d', 't'])",
              "d": { ".validate": "newData.isString() && newData.val().length <= 4000" },
              "t": { ".validate": "newData.isNumber() && newData.val() <= now" },
              "$other": { ".validate": "false" }
            }
          },
          "$other": { ".validate": "false" }
        }
      },
      "$other": { ".validate": "false" }
    }
  }
}
Latest build (ship crews, battle stations, pirate raids): no rule changes — crews and musketry are simulated on each captain's own machine and nothing new is written to the database. The rules above are current.
Coffee house build: inbox kinds cofshift, cofask, cofserve and cofno were added to the inbox k regex above. Republish the rules, or ordering from another captain will be rejected.
Leaderboard build: new pirates/leaderboard/$uid node (above) — any signed-in captain can read it, each captain writes only their own row: n name, a avatar, p infamy, r raids, s ships defeated, c cargo runs, h religious missions, t server time. Rows are written when a profile is created and on every online save. Publish the rules or the leaderboard shows only your own row.
Admin console build: one optional addition — pirates/admins/$uid now has ".read": "auth != null && auth.uid === $uid" so the game can check your own admin flag directly. Nobody can read anyone else's flag, and the node stays write-protected. Re-publish the rules above to pick it up.
Rules last changed: new pirates/world/fleets node; inbox kinds nhit, nloot and tclaim; inbox fields nid and dmg; presence fields fh and b (world/players). new pirates/admins node, and pirates/users/$uid read/write now also allow admins (used by src/god.html). Re-publish the rules above.

Admin console (in-game, and src/god.html)

Admins get an Admin button in the pause menu (between Controls and Settings) while signed in to the Online World. It opens a full-screen console with the same tools as src/god.html. Captains who aren't admins never see the button. The standalone page still works the same way:

A private page for editing any captain's save: set gold, supplies and trade goods, add or remove luxury items (including rare ones), and teleport a captain to any port with the ship moored. Open src/god.html, sign in, and pick a registered account. Setup, once:

Ship name and paint (sail colour, hull timber) are stored in the same save (G.shipName, G.sailPaint, G.hullPaint). Paint also goes out in your presence record as ph (hull) and ps (sails), so other captains see your colours — the rules above allow both fields. Re-publish the rules after updating: the old rules reject presence records with these fields, and your captain would vanish for everyone else.

Shared sea: seeing the same ships as nearby captains

Every client normally runs its own world: NPC ships spawn and despawn around you. That's cheap and needs no server, but two captains sailing together would otherwise see different ships. The shared sea fixes that without a game server:

  1. Alone or far apart — nothing changes. Each client simulates its own NPCs; no extra network traffic.
  2. Grouping — when another captain at sea comes within sharedSea.merge (1500 units) you form a group. You only leave it once they're beyond sharedSea.split (2500), so captains on the edge don't flicker in and out.
  3. Picking the host — a captain who is already hosting sets fh: true in their presence record and keeps the job, so a newcomer joins their world rather than replacing it. If nobody is hosting yet, or two groups meet, the lowest user id among the hosts (or among everyone) wins. Every client works this out on its own and reaches the same answer.
  4. The host keeps simulating as normal, and its pirates now also hunt grouped guests. Every sendMs (250 ms) it writes up to maxShips nearby ships to pirates/world/fleets/<hostUid> as one JSON-packed string: id, type, hull, position, heading, speed, sail, hull %, struck/sinking/looted flags, nation, name and a volley counter per side. Firebase deletes the node if the host disconnects.
  5. Guests stop spawning their own traffic. Idle local ships fade out; ships already fighting you, struck, or tied to a contract stay yours. The host's ships appear as proxies: they have no AI, and their position is eased toward each snapshot and extrapolated along their heading in between.
  6. Damage — each client still decides the damage it takes. When a proxy's volley counter goes up, the guest fires that broadside locally, so its own hits on the guest are real. When a guest's shot or ram hits a proxy, the damage is batched every hitFlushMs and sent to the host's inbox as nhit. The host applies it to the real ship, which then turns on that guest.
  7. Boarding a proxy — the guest grapples, boards and plunders locally, then sends nloot. The host marks its copy looted and it sinks for everyone.
  8. Traffic around guests — the host spawns ships around a random group member and despawns them by distance to the nearest member, with 3 extra ship slots per guest. Guests far from the host still have busy water.
  9. Handover: a guest sails off — once they're past split, the guest turns the proxies it's closest to into its own ships, keeping their hull damage and struck state. The host deletes those same ships, so nothing is duplicated. Both sides decide who is closest the same way.
  10. Handover: the host leaves or disconnects — the guests adopt the host's ships. The next host (whoever is already hosting, or else the lowest id) keeps all of them and sends them to the remaining guests. A guest left on its own keeps the ones within range.
  11. Stale feed — if no snapshot arrives for staleMs (5 s), the guest takes over the ships as above and leaves that host out of grouping for 10 s.
src/config.js
sharedSea: { merge: 1500, split: 2500, sendMs: 250, range: 3000, maxShips: 24, staleMs: 5000, hitFlushMs: 200, townIdleMs: 2000 }

Where the code lives: grouping, host choice, publish/apply and hit relay are in the shared sea section of src/multiplayer.js. The Firebase read/write is fleetPut/fleetWatch in src/online.js. NPC.spawnProxy and the volley counter are in src/ships2d.js. onHit in index.html forwards proxy hits, and npcDamage applies relayed ones.

Shared towns

Captains ashore in the same port see the same townsfolk, stall keepers and guards on the streets, and walk into the same tavern, store, shipwright, governor's house, church and cabinetmaker — with the same staff inside. Only homes (and their balconies) stay private.

Crew in PvE battles and sharing the helm

World clock (Online World)

Every online captain sees the same time of day and the same wind. Nothing extra is sent over the network:

Network usage and the free quota

The game uses the Realtime Database (not Firestore). What counts is data downloaded: 10 GB a month at no cost (Blaze then charges about $1/GB). Storage (1 GB) is no concern: the database only holds profiles, saves and short-lived live data. Dominion shares the same project and quota.

StreamRateDownloaded per other captain watching
Presence (position, chat, paint)every 200 ms ashore, 400 ms at sea≈ 1.5 KB/s ashore, ≈ 0.8 KB/s at sea
Town feed (street crowd + occupied shops)every 250 ms, while 2+ captains share a port≈ 8–10 KB/s per guest
Sea feed (NPC ships)every 250 ms, while captains sail together≈ 7 KB/s per guest
World clock, wind—0 (computed locally)

Rough budget: two captains together for an hour use about 40 MB, so 10 GB covers roughly 250 hours of paired play a month. Presence grows with the square of the number of captains online, since everyone watches everyone. Ten captains in one port use about 700–800 MB an hour, which is only about 13 hours a month. To stretch the quota, raise sharedSea.sendMs (e.g. 400) and the presence gap in tick() in src/online.js. Watch usage under Realtime Database → Usage and set a budget alert in Google Cloud Billing.

4 · Cloud Functions (username sign-in, keeps emails private)

Signing in or resetting a password by username runs on the server (server/index.js), so no player's email is ever exposed. Email and Google sign-in work without it. Requires the Blaze plan.

  1. Install the CLI: npm i -g firebase-tools, then firebase login.
  2. In the project folder, create firebase.json with the contents below (only needed for deploying — the game never reads it).
  3. cd server && npm install && cd ..
  4. firebase deploy --only functions:pirates --project gamedata-e4388 — the pirates codebase keeps the other game's functions untouched.
  5. In Google Cloud → IAM, give the functions' service account (…-compute@developer.gserviceaccount.com) the Service Account Token Creator role so it can mint sign-in tokens.
  6. If your web API key has HTTP-referrer restrictions, allow the Identity Toolkit API for server calls (or remove the referrer restriction).
firebase.json (deploy only)
{
  "functions": [
    { "source": "server", "codebase": "pirates", "ignore": ["node_modules", ".git"] }
  ]
}

Playing online

Install as an app (PWA)

When the game is served over https (or http://localhost) it can be installed like a native app — its own icon, full-screen, no browser bars — and Single Player works with no connection once it's been opened online once.

How it's wired: index.html links the favicon (assets/icon.svg + PNG fallback), the Apple touch icon and manifest.webmanifest, and registers sw.js. The service worker pre-caches the game files and icons, serves pages and scripts network-first (so updates arrive) and images/fonts cache-first. Firebase traffic is never cached. Opening index.html straight from disk still works; it just can't be installed.

After editing any file, bump that file's ?v= number on its tag in index.html, and bump VERSION at the top of sw.js so installed copies update. The service worker reads the script list (with versions) straight from index.html, so new scripts are cached automatically. Only new non-script files (images, CSS, pages) need adding to its CORE list.

Troubleshooting

"O.on is not a function" (or another "is not a function") on launch
Not a rules problem — the browser mixed a cached older copy of one script with newer ones. Every script tag carries its own version (?v=) so this can't recur; hard-reload once (Ctrl/Cmd+Shift+R). Bump the version in index.html whenever you edit a script.
Online: "permission denied" or nothing syncs
Publish the rules in Online world step 3, and check Email/Password and Google are enabled.
Online: "Username sign-in isn't available right now"
The Cloud Functions aren't deployed yet (step 4). Sign in with your email meanwhile.
Blank or black screen
Open the developer console (F12, or Safari → Develop → Show JavaScript Console). If a parchment box says "The ship would not launch", read its message. Make sure the folder structure is intact — index.html must sit next to src/ and assets/.
Problems opening from file://
The game uses no modules and no fetch(), so it runs from disk in Chrome, Edge, Firefox and Safari. If your browser or a corporate policy blocks local files, serve the folder instead, e.g. python3 -m http.server and open http://localhost:8000. On iOS, host it on any static server.
Low FPS
Pause → Settings → Graphics quality → Low (pixel ratio 1, fewer waves and effects, no night lights, fewer ships), then reload to also reduce palm density. You can lower waves, effects, vegetation or npcMax further in config.js.
No sound on iPhone / iPad
iOS only allows audio after a user gesture — tap the screen or a button once. Also check the ring/silent switch and the in-game volume in Settings.
Save data not persisting
Private/Incognito windows discard localStorage when closed, and Safari may block storage for file:// pages or clear it after 7 days of inactivity. Firefox stores file:// data per-folder, so moving the game folder "loses" the save. Serve the game over http://localhost for stable storage.
The game feels cramped on my phone
Turn the phone sideways — landscape gives the sea and the buttons the most room. In Safari, Share → Add to Home Screen launches it full-screen without the browser bars.
The installed app shows an old version
Close and reopen it once — the service worker fetches the new files in the background and uses them on the next launch. Make sure you bumped VERSION in sw.js.
Touch controls not appearing
They show automatically on coarse-pointer devices and on the first touch. On iPad with a keyboard/trackpad attached, tap the screen once. They are hidden on the title screen.
Gamepad not detected
Browsers expose a controller only after you press a button while the page is focused. Use a controller with the standard mapping (Xbox, PlayStation, most Bluetooth pads).