A top-down pirate game in plain HTML, CSS and JavaScript. Project guide.
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.
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.combat.chainCost, 2000g). It reaches chainRange (75%) as far and does chainDmg (50%) damage, but it only disables — it never sinks a ship.combat.ramMinSpeed and she takes speed × ramDmg × hull scale damage; your ship takes ramSelf (25%) of that. There's a 1.5 s cooldown per ship.boarders), led by her captain. Ropes and plank are stowed when it ends.assets/sfx/ and list them in sfx in config.js, e.g. sfx: { cannon: 'assets/sfx/cannon.mp3' }. Anything you don't list keeps the built-in sound.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.
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:
homes.price, 2500g, with stairs and a balcony over the street) or rent a room (homes.rent, 25g a day) in any port. Furniture (bed, table, chairs, bench, sea chest, wardrobe, bookshelf, writing desk, rug) comes boxed from the cabinetmaker; carry it home, unpack, turn and place it, or pack it up again. Selling a house back pays resell (50%). Logic in src/homes.js.clothes.dyeFee to dye one of six colours) and luxuries.paint.cost (40g), and fits chain shot. If you came ashore as another captain's crew and your ship is moored elsewhere, the shipwright ferries you back to her for free. Otherwise: repair the hull, add or sell guns in pairs (up to your ship's maximum), fit hull and sail upgrades (three levels each), and buy a new ship. Your current ship is worth half its price in trade.medicine: 30g, heals 60, carry up to 5; drink with H or the Tonic button on the HUD).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 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):
bridgeOf in src/world2d.js), so the town joins its own island and never bridges open sea to a neighbour.b, and other captains see your ship moored there.localStorage.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.
Buy ships at any Shipwright. Each class has its own mast count, speed, gun deck and hold:
| Class | Masts | Speed | Guns (max) | Hold | Hull | Crew | Price |
|---|---|---|---|---|---|---|---|
| Sloop | 1 (midships) | Fastest (27) | 8 (16) | 60 | 110 | 30 | 1,200g |
| Brig | 2 | Slow (20) | 12 (24) | 100 | 170 | 50 | 3,500g |
| Frigate | 3 | Fast (23) | 16 (32) | 80 | 240 | 80 | 7,500g |
| Galleon | 3 | Slowest (16) | 20 (40) | 120 | 340 | 110 | 13,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.
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).
melee.koTime (15 s), then gets up. With the blade sheathed you alternate jab and cross.melee.sheathAfter (8 s) without a swing or a shot, your blade goes back in its scabbard and you walk bare-handed. Other captains see it too (a bit in the mv presence field).arms). Swords scale the base slash and thrust; guns replace the pistol.
| Weapon | Price | Character |
|---|---|---|
| Cutlass | free | Short, sturdy, reliable |
| Rapier | 450g | ×0.8 damage, ×1.3 reach, ×1.35 speed — built for thrusts |
| Cavalry Sabre | 750g | ×1.2 damage, slightly longer and faster |
| Broadsword | 1,200g | ×1.6 damage, ×0.75 speed |
| Flintlock Pistol | free | 50 damage, 1.4 s reload |
| Duelling Pistol | 500g | 64 damage, 1.1 s reload, longer range |
| Long Rifle | 950g | 110 damage, 3.4 s reload, nearly double range; carried on the back |
| Blunderbuss | 800g | 7 pellets × 22, wide spread, short range; carried at the hip |
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).
missions.escort, 2 offers a day). A friendly refugee sloop or brig follows you; you're paid base + distance × goldPerDeg when both ships make the named port.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.
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.
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.
src/forts.js)src/diplomacy.js, saved in G.diplo): every pair of nations is at war or at peace. A state holds for at least 7 days; after that, each day a war ends with 30% odds and a peace breaks with 10%. News arrives as a toast. Governors report their crown's wars.privateer): a governor makes you his nation's privateer (G.privateer). Every 10 enemy-nation ships taken or sunk earns a star (max 5); at five stars that nation's shipwrights charge half price. Resign the letter at any governor of that nation.src/town.js, town in config): civilians witness crimes inside an unseen view cone; guards patrol with visible vision cones and hear pistol shots up to hearRange. Attacking townsfolk raises your wanted level in that nation (max 5 stars; guards attack on sight from 3). Laying a hand on a governor makes you most wanted. Stars fade one per in-game day, or bribe the governor.lux.strangerChance, 10% per item per day) who alone sells the Jade Necklace (7000g) and the Red Ruby Ring (6000g, also a wedding ring).| Action | Keyboard + mouse | Gamepad (standard layout) | Touch (iPhone / iPad) |
|---|---|---|---|
| Raise sail | W / ↑ | RT, D-pad ↑, flick left stick up | Sail +, or flick joystick up |
| Lower sail | S / ↓ | LT, D-pad ↓, flick left stick down | Sail −, or flick joystick down |
| Steer | A / D | Left stick ←→ | Joystick ←→ (left side of screen) |
| Fire port broadside | Q | LB | Port |
| Fire starboard broadside | E | RB | Stbd |
| Slash — tap up to 3× to chain (on foot) | J · left-click · E | RB | Slash |
| Thrust (on foot) | K · middle-click | RT | Thrust |
| Block — hold (on foot) | L · hold right-click | Hold LT | Hold Block |
| Gun — pistol, rifle or blunderbuss (on foot) | Q · I | LB | Shoot |
| Aim (on foot) | Mouse cursor | Facing + auto-aim | Facing + auto-aim |
| Punch (on foot) | U · X | R3 (click right stick) | Punch |
| Drink a healing tonic | H | — | 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 |
| Inventory | Click the ship & captain card | — | Tap the status card to flip it |
| Interact (dock, board, shop, set sail) | F / Enter | X | F |
| Leave / take the wheel | G | Y | Centre interact button |
| Walk | WASD | Left stick | Joystick |
| Run | Shift | L3 (click left stick) | Push joystick to the edge |
| Jump | Space | A | Jump |
| Repair with wood | R | B | Fix |
| Zoom | Mouse wheel / trackpad scroll | Right stick up/down | Drag 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 / Tab | Back / View | Map |
| Pause | Esc / P | Start / Menu | II |
| Menus | Mouse, Esc closes | D-pad moves focus, A selects, B closes | Tap |
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.
/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):
<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.
PG.CONFIG. Pure data; edit this first.PG.Audio. Creates the AudioContext on the first key/tap (required by iOS), then synthesises sounds from filtered noise and oscillators.PG.Input. Maps key codes to actions, tracks mouse clicks and cursor position for aiming, runs the virtual joystick and touch buttons via Pointer Events, and polls the first connected gamepad every frame.PG.PORTS (data), PG.PORT_BY_ID and PG.Ports. Builds each town (pre-rendered ground canvas, buildings, pier, props), stores colliders and shop doors, and animates townsfolk.PG.World. Islands are unions of noisy ellipses; heightAt(x, z) is the single source of truth for terrain, collision, vegetation and the map. Terrain is rasterised into cached pixel chunks around the camera; also waves, palms and the minimap/chart canvases.PG.Ships. The Ship class (setHull(), physics, bobbing, hit-test), 3/4-view hull, gun-deck and rig drawing, pooled cannonballs and particle effects, NPC AI and the spawn/despawn manager.PG.Combat. A jointed pixel-art rig (legs, arms, torso, head, hat, sword, pistol) posed every frame from keyframes (idle, walk, run, jump, slash, thrust, block, aim, long-gun draw and aim, sit, crew work poses, hurt), rendered at low resolution and scaled up for crisp pixels. Also melee/gun logic and boarding enemies.PG.Cabins. Builds the below-deck and captain's-quarters interiors for the current hull (drawn through PG.Rooms), handles the hatch/door, eating, drinking, resting and sitting, and runs your shipboard crew: task picking, talk/threaten, fighting back, and losing crew when one is killed.PG.ShipCrew. Puts a visible crew (scaled to hull and role, in national colours or pirate black and brown) and a tough captain aboard every NPC ship within ~320 units. In battle it sends everyone to stations — muskets at the rail firing across at the other ship's crew, our gun crews below — runs boarding defence, and lets pirate ships grapple alongside and send boarders across a plank onto your deck.PG.Missions. Generates notice-board offers per port and day, tracks active contracts in the save, spawns bounty ships and duelists, and pays out on delivery, capture or victory.PG.UI. All DOM work: HUD, minimap/compass (a town plan while in port), chart and town map, shop and loot panels, pause/settings, title and game-over.title, sail, deck, town, board, dead), sailing as another captain's crew (away), resource consumption, save/load, day/night lighting, and the requestAnimationFrame loop with delta time.All values below live in src/config.js. Save the file and reload the page.
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]:
{ name: 'Jamaica', blobs: [[-1920, 360, 400, 150, 70, 0.05]] },
{ name: 'My Island', blobs: [[1200, 1500, 180, 120, 30, 0]] },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: {
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
},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: {
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: {
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 },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.
Each good has a base price; every port multiplies it. Selling pays sellFactor of the buy price.
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
},{ 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: {
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
},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.
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
},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).
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 },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:
{
"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:
localStorage.removeItem('caribbean-plunder-2d-save-v1');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.
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"
};yourname.github.io). localhost is there by default.pirates/logins node in the Realtime Database if it exists (earlier builds stored emails there).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.
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.{
"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" }
}
}
}cofshift, cofask, cofserve and cofno were added to the inbox k regex above. Republish the rules, or ordering from another captain will be rejected.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.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.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.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:
admins node and the admin read/write on users/$uid). The admins/$uid read line lets each captain read only their own flag, which the game uses to decide whether to show the Admin button. Without it the game falls back to a permission test, which still works but is slower.pirates/admins/<your user id> with the value true. Find your id under Authentication → Users. Clients cannot write this node, so only you can grant admin.god.html publicly if you can avoid it; it's gated by the rules, but there's no reason to expose it.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.
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:
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.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.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.hitFlushMs and sent to the host's inbox as nhit. The host applies it to the real ship, which then turns on that guest.nloot. The host marks its copy looted and it sinks for everyone.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.range.staleMs (5 s), the guest takes over the ships as above and leaves that host out of grouping for 10 s.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.
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.
seed. Their clothes and colours are built from it with a seeded random generator (seeded() in town.js), so every client draws them identically from one number.th: true in their presence record), otherwise the lowest user id among captains in that port. th is separate from the shared sea's fh: a guest who claims one townsperson also publishes a feed, and if that counted as hosting, two captains could each decide the other was host and both drop their crowds — that's what used to make captains see different people. It publishes a compact row per person (id, seed, position, facing, walk state, mode, pose, dead, hp, flags, stall) to its world/fleets node, tagged {k:'town', port}. That's the same node the shared sea uses, since you can't be at sea and ashore at once.tclaim message and turns its copy into a proxy. There's still exactly one live copy, so fights, robberies and bodies look the same to everyone.KSLOT in rooms.js), so coordinates line up. Inside, your presence keeps sending px/pz plus in and rm (the shop kind), and captains in the same shop see, chat with, trade with and fight each other. Melee and pistol events carry rm too.r-tavern-3). The town host adds rows for the staff of any shop a captain is standing in (the feed's rooms list). Guests match those rows to their own copies and turn them into proxies. Claiming works as on the street, so a sailor hired by one captain walks out for everyone, and a bartender who's been killed stays dead for everyone until the town empties and resets.shot action with kind: 'npc' goes out, so other captains see the same aim, muzzle flash and ball (visual only — each game still owns the damage it takes). Town rows also carry the combat state, so sword swings and the aim line show for everyone.sharedSea.townIdleMs (2 s), to save bandwidth.on: 'n:<ship id>' there, so the host's defenders target them and everyone sees them. If they fall over there, they're dragged back aboard.Every online captain sees the same time of day and the same wind. Nothing extra is sent over the network:
.info/serverTimeOffset. PG.Online.serverNow() adds it to the local clock, so every device gets the same number even if its own clock is wrong.PG.Clock (bottom of src/online.js) works it out from that number: (serverSeconds / world.dayLengthSec + world.worldOffset) mod 1. The sky, night lights and the HUD clock use it. Small corrections ease in over about half a second; a big one (just signed in) snaps.updateWind in src/game-render.js). Online, that time is server seconds, so every captain gets identical wind, still drifting at wind.changeRate.world.startTime.G.time), so existing saves and contracts aren't disturbed. Passing out in the tavern still costs you hours on that calendar, but it can't move the shared sky.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.
| Stream | Rate | Downloaded 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.
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.
npm i -g firebase-tools, then firebase login.firebase.json with the contents below (only needed for deploying — the game never reads it).cd server && npm install && cd ..firebase deploy --only functions:pirates --project gamedata-e4388 — the pirates codebase keeps the other game's functions untouched.…-compute@developer.gserviceaccount.com) the Service Account Token Creator role so it can mint sign-in tokens.{
"functions": [
{ "source": "server", "codebase": "pirates", "ignore": ["node_modules", ".git"] }
]
}src/deckshare.js and world/crews); the first captain to fall loses. The winner takes what they want of the loser's gold and cargo, then sinks or returns the ship (loser back at 5% captain and hull). It works both ways.world/homes).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.
?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.?v=) so this can't recur; hard-reload once (Ctrl/Cmd+Shift+R). Bump the version in index.html whenever you edit a script.index.html must sit next to src/ and assets/.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.waves, effects, vegetation or npcMax further in config.js.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.VERSION in sw.js.