How I Built Pixel Realms: A Multiplayer Pixel World Run by a Web Worker
By Naga Sai Bommu · · 7 min read
A multiplayer pixel world where the whole game runs in a web worker, and nobody has to type a word.
Between job-hunting tools, I wanted to build something purely for fun that also taught me something. The result is Pixel Realms: six large pixel-art lands joined by storybook doors, with weather, fireflies at night, wandering bunnies and frogs, and other people walking around in the same world.
There's a short loop of it on the home page. This post explains how it works, what surprised me, and what I'd change.
The idea: keep the page out of the game's way
A browser tab has one main thread. It runs React, handles clicks and scrolling, and paints the page. A game that also runs its loop, draws a screen of pixels sixty times a second, and talks to a server on that same thread will eventually make the page stutter, or the other way round.
So the game does not run on the main thread at all. The page creates a <canvas>, gives control of it to a worker, and from then on only forwards input:
const canvas = document.createElement('canvas')
const offscreen = canvas.transferControlToOffscreen()
worker.postMessage({ type: 'init', canvas: offscreen /* ... */ }, [offscreen])
Inside the worker lives everything else: the simulation, the camera, the drawing, the weather and the WebSocket. React's job is small: a join form, a side panel with who is here, and a few buttons. In an 8-second run at the widest zoom I measured no main-thread stall over 50 ms, and the worker's draw loop ran at 120 frames a second on my screen.
One detail I'm happy with: the simulation steps on a timer in fixed 1/60-second steps, while drawing waits for the browser's next frame. Movement is the same at any refresh rate, and the world keeps moving even if the tab isn't being drawn.
A huge map that is never stored
Each of the six worlds is 2,048 by 2,048 tiles. Stored as one picture, that would be 33,000 pixels across. Instead, nothing is stored and nothing is downloaded: a world is a function.
Every tile is computed from a seed and its coordinates with a little value noise: water where the noise is low, a sandy shore around it, forests where a second noise layer is high, and scattered rocks and flowers from a hash. The same seed gives the same world on every machine, so there is nothing to sync.
The world is cut into 16 by 16 tile chunks. A chunk is generated when first needed, drawn once onto a small canvas, and kept in a least-recently-used cache. Each frame draws only the chunks in view. That means the cost of a frame follows the size of your screen, not the size of the world. Building and drawing one chunk, with scenery, took about 1.4 ms on average in my test.
I wanted to be sure the generated worlds were actually playable, so there's a test: every door in every world must be reachable from the spawn point by road. Roads and a clearing round each door are carved into the terrain, and scenery is never placed beside a road or a door. That test caught two real bugs while I was building it, including a road that ran through a door.
Making it feel like a storybook
Early on it was a flat green field with grey blocks. Whimsy took more work than I expected, and most of it is small:
- Doors, not gates. The doors between worlds became a treehouse door, a rainbow, a wardrobe, a moon door, a rabbit hole and a toadstool, each drawn from a few dozen rectangles in code. There are no image files in the project at all.
- Scenery. Mushroom houses, giant flowers, lanterns and signposts with names like "Closed for Cloud Watching" are placed from the seed, at most one per small cell, so a tile can always tell whether it is blocked by looking at its own cell.
- Night. A day lasts ten minutes. At night a dark sheet is drawn over the world with holes cut in it wherever there is a light: lanterns, the doors, other travellers, fireflies.
- Weather and animals. Rain showers in the meadow, snow in the snowfield, leaves in the forest, drifting petals, neon drizzle in the city.
The best trick, and the one I'd recommend to anyone, is that none of this needs the network. The time of day, the weather and every wandering animal are pure functions of the clock. A bunny picks a new spot near its home every couple of seconds, and which spot it picks depends only on the bunny's id and how many periods have passed since 1970. Two strangers on opposite sides of the world see the same dusk and the same bunny hop to the same place, and the server never hears about any of it.
The WebSocket server
My first version connected browser tabs with BroadcastChannel, which is lovely because it needs no server, but only works between tabs on one device. A shared world needs a server.
The Job Fit Studio backend already runs FastAPI, so the realm server is one more endpoint and one small class that holds the rooms in memory. The whole design fits in a few ideas:
- One room per world. You only hear about the world you are in. Walking through a door sends the server a new
joinon the same socket. - The browser says where it is, about 15 times a second. The server doesn't simulate anything. It validates the numbers and passes them on. That's all a social world needs, and it keeps the server tiny.
- Interest management. Sending every move to everyone grows with the square of the crowd. The server sends full-rate updates only to players within about 1,500 pixels, and every tenth update to everyone else, which keeps the roster and mini-map roughly right for a fraction of the traffic.
- A queue per connection. One slow client must not hold up the others, so each connection has a bounded queue and a sender task. A client that stops reading is dropped.
In an in-process test, the room logic handled 80 players all within range of each other, each sending 15 updates a second (about 95,000 outgoing messages a second), using about 4% of one core. That excludes the cost of the network itself, so it isn't a capacity claim for the whole system. It does tell me the room logic won't be the first thing to give.
The browser side reconnects with backoff, and sends its current position again each time it joins, because the server forgets a player the moment their socket closes. If the world is full (80 players) or the server is unreachable, you simply wander alone and it keeps trying.
Opening it to the internet without moderating it
Anyone can open the page, so I had to think about what strangers could do to each other. My answer was to remove the ability altogether.
- There is no free text. The only things a player sends are numbers: a position, a direction, an emote.
- Names are generated. You get something like "Sleepy Otter" and can shuffle until you like it. The server also strips anything but letters, digits, spaces and a couple of marks, in case someone sends a message by hand.
- Everything is validated and capped: 80 players a world, 400 in all, 6 connections an address, about 40 messages a second each, 256 bytes a message, and pages from other sites are refused by checking the
Originheader.
It isn't perfect (someone could still stand in a doorway), but there is nothing to say wrong, and I like that trade.
Showing it on the home page without slowing it down
My first idea was to make the picture on the home page come alive when you pointed at it: a second copy of the game, running quietly in a worker. It worked, but a marketing page should be fast above all else, and even a game that waits for a hover is more machinery than a landing page needs.
So the home page now shows a 600 KB GIF I recorded from the game, and nothing else. No script, no worker, no network request beyond the image. People who ask their browser for reduced motion get a still picture instead. The game itself only loads when someone chooses to open it.
What I'd do differently
- Tell the camera what you're looking at. Zoom stays centred on your character. Zooming towards the cursor would feel nicer on a big map, but conflicts with a camera that follows you.
- Don't trust positions so much. Each browser is the authority on its own character. That's fine for a place to wander, but it isn't a design for a game you could win.
- Use more than one process, eventually. Rooms live in memory in one process. To scale out I'd need shared state, or to pin each world to a process.
- Hand-draw a few landmarks. The worlds are generated, so they're big and varied but have few memorable places. A handful of hand-placed spots would help.
What I took from it
Putting the page and the game on different threads is a different way of thinking: the worker owns the state and the page sends it messages. Once that clicked, a lot of decisions fell out of it. The simplest, most satisfying win came from the smallest idea: if something can be a function of the clock, it never needs the network.
If you want to see it, wander in. Say hi to the frog.