You are browsing as a guest. Sign up (or log in) to start making projects!

Hadronize

  • 26 Devlogs
  • 118 Total hours

Quark-themed set collection game you can play in your browser

Ship #1

Hadronize: a quark-themed set collection game.

It has a web UI with a custom SvelteKit virtual layout engine, a polyglot CLI that runs across Node, Deno, Bun, and the browser console, a QuickJS bot sandbox, a comprehensive test suite, and more.

I’m really proud of Hadronize and hope that you enjoy it.

  • 26 devlogs
  • 118h
Try project → See source code →
Open comments for this post

26m 14s logged

Shipping

I did a few miscellaneous things like make the remote script endpoint production-ready, fix some typos across the project, and create a favicon in Inkscape.

After I write this devlog, I’m going to press the big “Ship your project!” button. If you’re a reviewer reading this: I hope you enjoy Hadronize. It’s one of my biggest projects ever, and I’m really proud of how it’s turned out.

1
0
8
Open comments for this post

5h 8m 13s logged

Revised Readme (again)

Still working on the README. I think that Hadronize is more or less ready to ship now, but there’s probably still a bit more polishing I can do.


In my other Stardance projects, I’ve gotten really positive feedback on my READMEs, so apparently my writing style and README format of choice is a winning combination. I’ve been referencing my past READMEs and the Stardance README guide a lot while writing this one.


The bulk of what I added was the How it Works section, which explains some of the technical details and design choices that I made. It’s a dense topic so it’s obviously a long section. At first it was just a wall of text, even when I tried to break it up with lists and subheadings. So I spent about half an hour taking screenshots and editing them in GIMP until I had decorative images that I was satisfied with for each subsection. I think that drop shadows on transparent backgrounds look really cool in README images, so I used GIMP’s drop shadow filter to add them to my screenshots (in addition to cropping, rounding corners, et cetera). I kept fiddling with the drop shadow settings and I didn’t want to go back and redo the images that I’d already done, so the shadows are kind of inconsistent, which really irks me but I don’t think is very noticeable.

I also added a Running Locally section and fixed a few typos throughout the README.


Lastly, I did a bit of work on the home page. I added a big screenshot below the intro paragraph, thanks to feedback from the awesome @Luksus, whose project you should totally check out.

0
0
14
Open comments for this post

2h 44m 15s logged

Revised README

I worked on updating and basically completely rewriting the README to something more polished. I still need to add more sections and revise what I have, but I think that it’s alright. I’m trying to strike a balance between not having enough content and being a wall of text. It’s also surprisingly difficult to come up with bullet points for the features list.

After I finish up the README, I’m going to redesign the home page a bit. After that, I think I might be ready to ship.

0
0
14
Open comments for this post

6h 27m 50s logged

How to play page

I wrote a page that explains how to play, assuming zero knowledge. I think that this’ll be helpful for onboarding, because this way they learn the rules at the same time as they learn how to use the UI, rather than reading the abstract and theoretical rules and then trial-and-erroring their way through the UI.


The actual writing part took a few hours, and most of it was revision and trying to find better ways to phrase things. It’s nearly 1000 words, meaning I could turn it in for an essay assignment and not fail the word count, which is funny.

But what also took a lot of time was making the visual aid. I had to record myself performing the same action in the UI many times to get a perfect take, and then I had to craft an ffmpeg command to crop and trim it because I refuse to use graphical video editors. Also my recording software kept stuffing H.264 video data in a webm container, which made ffmpeg freak out because that file is technically corrupted. I also had to figure out how to screen record on my phone to get a tap indicator, which I’d never done before.

You can read the page here: https://ethmarks.github.io/hadronize/how

0
0
15
Open comments for this post

3h 36m 50s logged

Discontinuing the ranking arena

I’ve decided to stop working on the driver ranking arena. I already have an MVP that works well enough to kinda sorta determine which drivers are good and which are bad, but it’s not robust and it just sums up rankings rather than implementing an actual Elo algorithm. The reason I’m not going to continue working on it is that it seems like a lot of work, and I don’t think that it’ll provide any value. Like, at all.

The root of the problem is that Hadronize just isn’t a strategic-enough game. There’s certainly some strategy, of course, and probabilistic modeling, but luck plays just as much of a factor. The cleverest Hadronize driver can still routinely lose to the dumbest one just due to slightly bad luck. So it doesn’t really make sense to build tooling for strategic bots if the strategy is not a very big aspect of the game.

Thinking back, I’m not really sure why I decided to start working on the driver arena in the first place. It just seemed like the right thing to do at the time even though I now realize that it would be kind of useless.


Anyways, I also created two new drivers.

  • The first is called Kingslayer, and it just tries to steal from the player who’s currently winning. It’s not very good at actually winning, but it does make things more challenging for the other players.
  • The second is called Gentleman (aka charm). It’s obsessed with trying to collect charm quarks, because its a charming gentleman. I made it as a joke because I thought it was funny, but to my complete surprise it turns out to be a pretty good strategy? Not charm quarks in particular, but trying to collect a specific flavor of quark at all costs turns out to be surprisingly effective. It consistently wins more often than EVan, the driver that I specifically built to be a good strategy and that actually does probabilistic expected value calculations.

I think that next I’ll start working on the README and documentation, because I haven’t updated the README in like 3 weeks and it’s extremely outdated.

0
0
8
Open comments for this post

1h 48m 34s logged

Benchmark

Before I started working on the bot ranking arena, I did a quick sidequest to figure out how many games per second I could simulate. So I wrote this script to execute a bunch of games sequentially, then print the elapsed time and calculate the games per second rate.

I ran the benchmark in Node 24.15.0 on my 4.40 GHz Intel i5-12450H using Bogo drivers:

Simulated 82157 turns across 1000 games
Took 109048ms (109.048s). Speed is 9.170273640965446 games per second

So that was surprising. I was expecting a speed in the low thousands, but instead it was less than 10.

I had a suspicion what was causing the slowdowns. To make sure, I swapped out the Bogo driver (which uses QuickJS) with a non-QuickJS driver that I made for testing, and reran the same benchmark:

Simulated 53854 turns across 1000 games.
Took 130ms (0.13s). Speed is 7692.307692307692 games per second

(the turn count is smaller because the drivers used a different strategy which made games end faster)

So, obviously, the slowdown is caused entirely by QuickJS. Which makes sense. Every time a QuickJS driver is invoked, it spins up a brand new QuickJS VM, configures it, executes the actual code, extracts the return value from the VM, disposes of the VM to avoid memory leaks, and then finally returns the value. Non-QuickJS drivers can just execute the code directly, and the code can be optimized very well by the JIT compiler that Node uses.

So the solution seems simple, right? Just don’t use QuickJS for the drivers. Whatever the advantages of using QuickJS are, surely they aren’t worth an 839x decrease in performance. Well, unfortunately that’s not an option. More specifically, dynamically running strings of JS (like the driver code that users write at runtime) as native code is not possible, so I have to use a JS VM. And QuickJS is by far the best embeddable JS VM that I know of. So I just have to accept the slowness.

This means that I’ll have to be clever about the bot arena, though. I can’t just brute-force a ranking with thousands of games if I can only run 10 games per second.


btw, if you’d like to see how your PC does on my benchmark, just run these commands:

git clone https://github.com/ethmarks/hadronize.git
cd hadronize
pnpm install
pnpm bench --count 1000 --driver prng

If your time is faster than mine, leave a comment to gloat.

0
0
8
Open comments for this post

6h 44m 53s logged

Bot editor

I integrated the QuickJS driver code that I made last devlog into the rest of the site. Things I did:

  • I made the QuickJS VM override the default Math.random function and replace it with a mulberry32 prng seeded by stringifying the game state and hashing it through djbs2. So now drivers can still use Math.random without making the rng predictable or sacrificing perfect determinism.
  • I gave the drivers names and descriptions. The prng driver is named “Bogo” (after Bogosort) and the expected value driver is named “EVan” (because it’s a normal name that starts with the abbreviation of “Expected Value”).
  • I moved the code for the existing drivers into a centralized array, rather than in multiple different files that had to be imported individually. I’m calling this array the “stock drivers”.
  • I added a bot editor page. You can check it out at https://ethmarks.github.io/hadronize/bots. I used contenteditable and Svelte’s bind:textContent to let users edit the title, ID, and description. I used Prism code editor as the embedded IDE for editing the actual driver code.
  • I made the play page fetch the list of drivers from localstorage on page load, defaulting to the stock drivers. I also made the bot editor automatically sync the drivers to localstorage.
  • I added a new driver strategy: tit for tat. As expected, it plays pretty terribly because that strategy just isn’t very good in Hadronize. I mostly made it so that users looking at the stock drivers can learn how to reference the timeline from the state.

I think that next I’ll work on a driver ranking system so that when I make more drivers, I’ll know whether they’re better or worse than the others. I might research how chess ranking systems work and copy concepts from those.

0
0
10
Open comments for this post

1h 19m 50s logged

QuickJS drivers

I can now store driver strategy code as strings, execute the strings as JS code using QuickJS, read the quickjs output, and use it as driver output.


This might not sound like much of a difference, but it completely changes how I can run drivers. Before, all driver strategies had to be present in the actual source code. Now, they just have to be strings. Because we can manipulate strings at runtime, this means that we can create new drivers while the site is running without modifying the source code. In other words: this lays the groundwork for letting you create and play against your own drivers without making a PR to the repo.

To make sure that my implementation works, I converted the expected value driver to use quickjs. I enclosed all of the actual logic in backticks, making it a giant string, and then passed the string through my quickjs driver factory function. I ran the expected value driver test suite, and it failed immediately because I forgot to remove the type annotations (quickjs can only execute plain JS, not TS). But once I fixed that, all 19 tests passed, and it seems to work perfectly from my playtests.

I eventually plan on adding a page that uses Prism code editor to let users edit driver strategies and save them to localStorage. But first I’m going to add more features to the quickjs runtime. For example, I want to have it swap all Math.random() calls with a deterministic psuedorandom generator, so that way developers can use randomness without making it non-deterministic.

0
0
9
Open comments for this post

1h 5m 16s logged

New quark style

I made new quark graphics, like I promised last devlog. I’m not really sure if it fits the aesthetic I’m going for, but it’s something, and I tried to make it extensible so that I can experiment with more styles later.

I also added a dropdown menu in the setup flow so that you can select which style you want to use, though I might remove that in the future if I decide on one style to be the definitive one.

The new style is just patterns masked onto the same flat color circles as before. Each flavor has a different pattern:

  • up: vertical lines
  • down: horizontal lines
  • charm: checkerboard
  • strange: square grid with irregular shading
  • top: light dot grid
  • bottom: dark rhombus grid
  • hadron: solid (unchanged)

I don’t know if this makes the quarks look nicer or not, but it definitely makes them more accessible. If the abbreviation text isn’t visible for whatever reason (e.g. because the chamber is in count layout mode), quark flavors used to be distinguished solely by color. But the new patterns make them distinguishable without color, which is important for colorblind accessibility.

0
0
9
Open comments for this post

2h 21m 28s logged

Minor graphics improvements

This is a smaller devlog. Stuff I did since last devlog:

  • Fixed the winning animation to work with the new layout planner
  • Added transitions to the quark text. Whenever a quark changes its display text (e.g. from a ‘?’ to a flavor abbreviation like ‘s’), rather than instantly snapping to the new text, it’ll do a quick crossfade.
  • Changing the font used for the quark text from the default to a font called Degheest that I think looks nice.
  • Merging the layout refactor into prod because I’ve decided that it seems stable enough.

Next, I’m going to work on improving the quark graphics. I’m trying to go for an aesthetic that looks like it’s from a physics textbook (hence the dot grid backdrop I’ve had for a while), so it’s already pretty close, but imo it looks a bit too plain right now. I don’t have a precise vision for exactly what I want the quarks to look like, so I’ll need to figure that out.

0
0
4
Open comments for this post

29m 3s logged

Touchscreen support

Idk why I was worried that this would be difficult. Less than 20 lines of code later, Hadronize now automatically detects whether you’re using a fine pointer (e.g. a mouse) or a coarse pointer (e.g. a touchscreen), and changes its behavior accordingly.

So now you can select chambers on touchscreen just by tapping on them. You don’t have to drag the superposed quark, you just tap.

I recorded a video showcasing this in action using Firefox’s mobile device simulator (aka RDM). As you can see, when I disable touch simulation, the chambers respond to hovering and I have to drag the quark around. But when I enable touch, the chambers don’t react at all until I click one, and then the superposed quark gets added to that chamber like normal.

I’ve also tested this on an actual phone and it works perfectly, but it’s more difficult to record on there which is why I used Firefox’s simulator for the video.

0
0
10
Open comments for this post

8h 16m 45s logged

Layout optimization algorithm

It took an entire day, but I did it. Hadronize will now automatically adjust 5 different layout variables in order of priority to make everything fit on screen.

I think that the algorithm is probably the most complicated part of this entire project. I’m going to try to explain it really simply in this devlog, but if you want to see how it actually works, I wrote a bunch of comments that explain the priority pipeline in this file.

So basically, every time a new layout update is triggered, the layout manager calculates a brand new layout plan from scratch. Once it’s finished calculating, it applies the layout plan onto the actual layout variables that are used to move the quarks on the screen. If I modified the layout variables directly, the rapid-fire modifications while calculating would trigger a bajillion reactive updates from Svelte which would slow the page down.

Anyways, the way that the layout plan is calculated is that it starts by assuming ideal conditions: there is more than enough room for everything to fit comfortably. So it does the calculations using the preferred ideal variables, it modifies the plan, and then it actually checks to see if anything is overlapping. If there is any overlap, it tries to resolve it using the least-disruptive adjustment it can make. If that doesn’t work, it tries the next least-disruptive adjustment. And so on. Also, each time it moves up the chain of disruptiveness, it tries to use the ideal variables for all of the less-disruptive adjustments. If that makes sense.

Here are the adjustments that it can make, in ascending order of disruptiveness:

  1. Increasing the radius of the ring of quarks of a single chamber
  2. Adjusting the radius of the ring of chambers around the center of the screen
  3. Switching chambers to use count mode, which is when it only displays the number of quarks of each flavor rather than displaying each quark individually.
  4. Switching the global layout from ring mode to grid mode. This is the thing that I built last devlog.
  5. Decreasing the size of all quarks

I’m pleased to report that when I tested it on my phone, everything worked perfectly. I still haven’t implemented mobile input yet, but I started a 6-player game of all bots, and the layout planner managed to keep all of the quarks visible all of the time, even when a single chamber had more than 20 quarks. Never once did I see two chambers overlap with each other or go partially offscreen, which used to happen 100% of the time on small mobile screens. It just changed layout modes and decreased the quark size whenever it started to run out of room.

Anyways, I’m not going to merge the new layout planner just yet because I’m not 100% sure how stable it is, but I’ll do that soon. Next up is mobile input.

1
0
50
Open comments for this post

1h 42m 40s logged

So the first step to mobile support is making the all of the quarks in all of the chambers actually fit on a phone screen. Right now they just overlap a bunch and you can’t tell which quarks belong to who. I have some ideas for an algorithm that can automatically adjust layout variables until everything fits, but first I need to give the algorithm things that it can adjust.

The crux of the problem is that there’s simply no way to fit 6 chambers in a circular ring around the center of the screen on mobile. There’s just not enough screen space. So I made a new layout that places chambers in a grid instead of a ring. It works on desktop in addition to mobile. I don’t think it looks quite as nice, but it’s much more space efficient.

I attached some side-by-side comparison screenshots. As you can see, the quarks still don’t quite fit on mobile even with the grid layout, but it’s much closer.

Next step is either writing the automatic layout algorithm, or making input work on mobile.

0
0
7
Open comments for this post

3h 11m 51s logged

Sound effects!

I added sound effects to the game UI. A unique sound plays for each of these:

  • Starting a game
  • Dragging a quark over a chamber
  • Dropping a quark onto a chamber
  • A quark hadronizing
  • A quark tunneling
  • Winning a game
  • Closing a game

I sourced them all from https://freesound.org/, and I left attribution for each one in sounds.svelte.ts. I also modified a few in Audacity to trim them or apply simple effects.

I’m not sure that I’m 100% satisfied with the sounds. I sourced almost all of the effects from different freesound sounds because I couldn’t find a sound pack that I liked, so the sounds don’t quite match tonally. Some of them are generic UI sounds while others are clearly scifi-ey. I may change some of the sounds later if I find more cohesive ones.

I’d never done audio in HTML/JS before, so this was new for me. I originally just used the Audio() constructor because that was the most obvious way to play, but when I realized the many issues with it (though it did work!), I rewrote my code to use AudioContext. I also made a multi-step preloading and decoding pipeline that fetches all sound effects on page load, but doesn’t decode them until the user presses a button because otherwise JS throws a warning in the console and suspends the audio context.

I think that the sound effects make Hadronize feel a lot more polished and nicer to play.

Next up on my list is mobile support. I’m not looking forward to it.

(Make sure to turn on sound for the video below)

0
0
6
Open comments for this post

1h 39m 56s logged

Mouse handler refactor

https://github.com/ethmarks/hadronize/commit/3a5adcb

I started working on writing audio code and looking through sound effect libraries, but when I tried to hook my WIP sound-playing function into the mouse handler, I realized what an awful mess my mouse handler code was.

So I spent over an hour refactoring it. While I was at it, I optimized it a tiny bit and fixed the hover thrashing bug that had been bugging me for nearly 2 weeks now.

0
0
5
Open comments for this post

2h 39m 33s logged

Style improvements and new pages

So, funny story about the site styles. When I first made the CLI page 3 weeks ago (has it really been that long?! wow), I added holiday.css to make it look nice as a stopgap measure until I made the real styles. However, as the old saying goes, there’s nothing more permanent than a temporary solution. I’ve decided to just embrace using holiday.css for the entire site because it looks much nicer than anything I could make. The styles in the actual game component are entirely my own, of course, but the homepage, rule page, and rewritten CLI page all use holiday.css.

“what rule page and rewritten CLI page?”, you ask? That’s the other thing that I did this devlog. I created a dedicated page on the site for the rules, and I rewrote the CLI page to only contain instructions on how to use the CLI rather than a playable browser CLI. Don’t worry, you can still play Hadronize via the browser console. The main UI has had that functionality since the beginning. I just didn’t see a reason to maintain two different game UIs, especially because the main UI can do everything that the playable CLI page could (and much more).

I think that next I’ll start polishing the game UI. It’s long overdue. I’ll add sound effects, add mobile support, and maybe (don’t hold me to this) improve the graphics.

0
0
4
Open comments for this post

8h 22m 22s logged

UI Setup Flow

diff from last devlog to this one

I added a setup flow to the main UI page, and did a lot of refactoring.

I also removed support for setting up the game via browser console. I didn’t make this choice lightly because it was a fun feature, but the tradeoffs were just too much and I decided that it wasn’t worth it, especially because the console setup is much clunkier than just using the HTML form, so I doubt anyone would even use it.

But anyways, the main focus of this devlog is the setup flow on the main UI page (aka the play page). I also added some pretty sleek animations when activating and deactivating the game overlay.

0
0
3
Open comments for this post

3h 42m 24s logged

UI Refactor

diff from last devlog to this one

I refactored the Hadronize UI code. Rather than one giant 570-line file that handled the quark positioning, state tracking, mouse movement, and game loop, I split the code into four different files, each dedicated to one specific thing, with an average line count of ~154 (191, 184, 111, and 132, respectively). This makes the codebase way more maintainable and easy to work in.

I also deduplicated most of the main game loop code. Before, I had just copied the entire content of the executeTurn() function, pasted it into the UI code, and customized it until the logic code correctly interfaced with the UI. Maintaining two separate functions that do basically the same thing is bad practice, so today I came up with an alternative solution: adding a bunch of “hooks” as optional parameters, which are just functions that the executeTurn() function runs at specific stages. In a CLI game, the hooks are never provided to the function, so they’re never run and nothing changes. But the UI code does provide hooks, to do things like trigger re-renders. This way, the same code can be reused for two different use cases (CLI and UI).

Next Steps

There’s still more refactoring to do, but I don’t think that I’ll do any more major restructuring.

0
0
3
Open comments for this post

14h 47m 44s logged

Huge UI Progress

diff from last devlog to this one

I’ve been working a lot on the Hadronize UI. Last devlog, all that it could do was render all of the quarks into a big overlapping heap and you could drag around one specific quark. Now, you can play a full game in the UI from start to finish, and it’s reasonably polished.

How to play the UI prototype

  1. Visit https://ethmarks.github.io/hadronize/play.
  2. Make sure that you’ve read the game rules in the README.
  3. I haven’t implemented a setup flow in the main UI yet, so right now it’s pre-configured with two human players named Arthur and Ford, one bot player named Marvin, and seed 42.
  4. On each human player’s turn (their name will be highlighted in yellow), click and drag the superposed quark to the chamber of the player who you want to observe it.
  5. The superposed quark will collapse, get added to the chamber you selected, possibly react with existing quarks, and then play will proceed to the next player.
  6. Continue this until someone wins. It will probably be Marvin. Refresh the page to play again.

Playtest

I also conducted the first playtest with a few friends. Nothing broke during the playtest and they all liked it and gave positive feedback, which was really encouraging. We all got absolutely crushed by the expected value driver I built last devlog.

Next Steps

It sounds hyperbolic to say that this UI is the messiest code I’ve ever written, but I legitimately can’t think of any other contenders. Of the 800+ lines of code in the UI, about 570 of them are in one massive Game.svelte component. This component handles state tracking, mouse movement, the main game loop, and most of the geometry to position the quarks. The very next thing that I need to do is massively refactor the UI code.

After that, I have a few ideas:

  • A setup flow that lets the user choose the seed to use and configure the players.
  • Sound effects, UI indicators (e.g. “you formed a baryon!”), and other game juice.
  • Proper mobile support. Right now it kind of works on mobile, but the layout gets really cramped.
    I’ve been working a lot on the Hadronize UI. Last devlog, all that it could do was render all of the quarks into a big overlapping heap and you could drag around one specific quark. Now, you can play a full game in the UI from start to finish, and it’s reasonably polished.
0
0
1
Open comments for this post

3h 18m 40s logged

Drivers

Each player in Hadronize is controlled by a Driver, which is basically just a function that takes the current game state as an input and outputs a player. I implemented drivers on like day #2, but I don’t think I’ve talked about them in a devlog yet.

  • The first driver I made is the dogpile driver. It’s logic is extremely simple: it just selects the player who goes first. It doesn’t even reference the game state at all. If every player is a dogpile driver, this means that everyone just dogpiles onto the first player and ends up stealing basically all of its quarks before it can use them. This is obviously a terrible strategy because it’s not even capable of trying to score, but it was very simple to implement and I use it as a placeholder.
  • The second driver I made is the rng driver. It just makes random decisions. However, because I insist on everything being deterministic, it can’t just use Math.random. Instead, it stringifies the game state, converts that string into a 32-bit integer via a djb2 hash, then uses that integer to seed a mulberry32 pseudorandom number generator, then uses the output of the mulberry to make its player selection.
  • The newest driver that I just finished developing is the expected value driver. It does actual strategic calculations to determine what the expected value of choosing each player would be based on the information it has available, then selects the player that maximizes that value.

Next Steps

I’ve started building the UI, but I’ve still been procrastinating on actually working on it in earnest. I should probably do that.

0
0
5
Open comments for this post

5h 10m 41s logged

Tests and CLI Args

You can now add arguments to the Hadronize CLI in the terminal, which lets you avoid having to use the setup flow. Here’s an example.

pnpm run cli --seed 12345 --player Alice:human --player Bob:bot

It also works if you run the CLI as a remote script.

deno run -A http://ethmarks.github.io/hadronize/cli.ts -s 8 -p a:bot -p b:bot -p c:bot

This was pretty easy to implement. I just used Node’s parseArgs utility for the main arg parsing and wrote a bunch of validation logic that converts the raw arguments (which are always strings) into the data types that my code uses.

Tests

Over the past couple days, I’ve made a little test suite for the game logic using Vitest. I’ve written 19 individual tests, but some of them repeat multiple times with different game seeds and whatnot to ensure that it works with a variety of inputs, so Vitest actually runs 101 tests in total.

All of the tests pass, and I didn’t discover any bugs, which either means that I managed to get all the game logic correct on the first try, or that there’s something wrong with my tests.

Next Steps

I think that I’ve probably spent too much time on the CLI. I don’t think that it was time wasted, but I probably ought to get started on the main game UI.

0
0
3
Open comments for this post

6h 23m 50s logged

CLI Remote Script

You can now run Hadronize CLI in a terminal without cloning the repo. If you run the command below, Deno will automatically fetch all the dependencies.

deno run -A http://ethmarks.github.io/hadronize/cli.ts

Node doesn’t support remote scripts because it lacks Deno’s awesomeness, but because of the Deno binary on npm, you can run Deno (and therefore Hadronize) through any of the other package managers!

npx deno run -A http://ethmarks.github.io/hadronize/cli.ts
pnpm dlx deno run -A http://ethmarks.github.io/hadronize/cli.ts
bunx deno run -A http://ethmarks.github.io/hadronize/cli.ts

For example, in the attached screenshot, I SSH-ed into one of my home servers that hadn’t cloned the Hadronize repo nor installed Deno, and tried to run Hadronize as a remote script via pnpm. After resolving dependencies for a few seconds, it ran flawlessly.

How it works

I first encountered Deno remote scripts in Lume’s init command, and my implementation is heavily inspired by it. Basically, all that the cli.ts file does is fetch the CLI code from JSDelivr, which fetches it directly from the GitHub repo. From there, Deno is smart enough to resolve all of the CLI code’s dependencies and run it.

Compatibility

Before today’s changes, running Hadronize via Deno worked perfectly fine. deno task cli behaved identically to pnpm run cli. However, that’s because Deno has an automatic Node compatibility layer, not because Deno can actually run the code natively. That compatibility layer doesn’t really work with remote scripts (because Deno can’t find the package.json), so when I first tried to run the remote script while developing it, it crashed and burned immediately. This was because, without the compatibility layer, Deno and Node handle things fundamentally differently. There were several differences, some of which I expected and some of which I didn’t, but the easiest one to understand is NPM imports.

NPM imports

My CLI code relies on the picocolors library for getting ANSI escape codes. When I was first writing the code, I added the picocolors package via NPM and imported it in the normal Node way:

import pc from "picocolors";

The problem is that Deno can’t parse bare imports like that. Deno expects this format, which Node cannot parse:

import pc from "npm:picocolors";

I tried configuring an import map in deno.json, but it didn’t work. I considered just hardcoding the ANSI escape sequences, but I decided that I would need to figure out how to polyglottally import NPM packages in both Node and Deno at some point, so I might as well figure it out now.

My solution was to create a deps/picocolors.ts file to proxy the picocolors import by dynamically importing it based on whether it’s being run in Deno or not:

const { default: pc } =
  "Deno" in globalThis
    ? await import("npm:picocolors")
    : await import("picocolors");

export default pc;

NPM imports were only one of the issues that sprung up. Frustratingly, the only way to test whether or not a solution worked was to commit, push to main, and test on production. The whole Deno compatibility saga required 12 commits in total.

Next Steps

I’m still working on writing unit tests for the game logic. I already have a few tests, but they’re definitely not comprehensive. I’ll write a devlog about the tests once I’m finished with them.

0
0
1
Open comments for this post

5h 49m 13s logged

Setup Flow

diff from last devlog to this one

Since my last devlog, I added a flow that lets users set up each game before starting it. The setup includes specifying the seed, player count, the names of each player, and whether each player should be a human or a bot. I made it work in three different formats, each of which had to be implemented individually:

  • The terminal: at its core, this format is just a normal TUI. It prints input prompts, awaits the user’s input using the abstracted NbrInputFunc I mentioned last time, and repeats this until the user provides an input that passes the validation function. Pretty standard stuff.
  • The browser console: I used the same trick that I described last time to allow users to enter their input via the browser console. It creates a custom window property that resumes execution, then halts execution with a Promise<void> until the window property is called. Unfortunately, it wasn’t possible to use the anonymous getter trick that I used last time. If I did that, I would have to create custom window properties for every possible 32-bit number to allow user to enter the seed, and create custom properties for every possible string to allow users to enter player names. That obviously wasn’t possible, so instead I just created a window.r function that takes any input type. The “r” stands for “respond”. To set the seed to 42, you type r(42) into the console, which is a reasonably clean UX, I think, though not as clean as just typing 42 like you can in the terminal.
  • The webpage: this uses HTML <input>s and SvelteKit’s reactivity. The trickiest part was navigating the fact that the value of one of the inputs (player count) controls the structure of some of the other inputs (player configs). At first I tried writing code to dynamically construct a variable-length Array, but that was a nightmare of complexity. Then I tried making all 6 possible player configs visible all the time and just adding the “Disabled” type, but that made the UI look ugly and was also kind of complicated to implement. The solution I settled on was to internally use an Array with a fixed length, automatically hide the player config UI elements with an index less than the player count value, and slice the player config Array before passing it into the main game function. I think that this solution is the best of both worlds while also being fairly simple to implement.

Next Steps

I know that I’ve been saying this for the past 4 days, but I need to write some internal docs for my game logic code and write tests. I haven’t noticed any bugs during my playtests while building the CLI, but I’d like the peace of mind to be fairly confident that I’ve implemented my game rules correctly.

0
0
4
Open comments for this post

10h 19m 54s logged

Browser CLI

Since my last devlog, I implemented a CLI for Hadronize that works across Node, Deno, Bun, and browsers. You can try it out by visiting https://ethmarks.github.io/hadronize/cli or running the following commands (you only have to run one of the Node/Deno/Bun commands):

# Clone the repo
git clone https://github.com/ethmarks/hadronize.git
cd hadronize

# Run with Node (via npm or pnpm)
npm install
npm run cli

# Run with Deno
deno task cli

# Run with Bun
bun install
bun run cli

Link to the diff between last devlog and this one

Abstraction

In case you’re not familiar with the JS ecosystem, a cross-runtime CLI like this is not normal. My CLI uses styled text, but the different runtimes have different ways of logging styled text. Node, Deno, and Bun all use ANSI escape characters, but browsers use %c placeholders (Deno also supports %c because Deno is awesome, but none of the others do). Node uses the readline API to get user input, but Deno and Bun both use prompt(), and browsers don’t even have a way to get user input without clever tricks (as you’ll see later).

My solution to the styled text problem was to create a custom micro-library which I call styledLog.ts (or sl for short) which invents an easy-to-use syntax for rich-text logging called slChunk, then automatically detects if it’s running in a browser and renders slChunks with either ANSI escapes or %c placeholders accordingly.

Cross-runtime user input

My solution to the user input problem was a little less elegant, but in my opinion it’s much cleverer. Node, Deno, and Bun were the low-hanging fruit. All I had to do was create an abstracted NbrInputFunc() function that automatically detects which runtime is running the code, then switches out the method it internally uses to fetch input accordingly. Easy.

But implementing a CLI in the browser was a lot more tricky. I could have just used the window.prompt() method, but that opens a disruptive pop-up window that looks terrible. Instead, my code dynamically adds custom properties to the window object, then halts the script execution via a Promise<void>. Each custom property is named after a player name and has an anonymous getter function. When you type a player’s name (e.g. alice) in the console, it automatically evaluates window.alice, which triggers the getter. The getter sets the userInput variable then resolves the frozen Promise to resume execution.

I hope that made sense. It’s a really hacky solution, but it does work, and it provides an elegant input syntax that resembles that of terminal CLIs. My first idea (which is still used as the fallback) was to just define a window.turn() function, so you would enter your input with turn("alice"). The current solution is much more elegant, in my opinion, because the user doesn’t need to type parenthesis or quotes.

Here’s a link to the code if you want to check it out for yourself.

Beginnings of the UI

I also started working on the UI the tiniest bit. Not anything that’ll make it into the final version, mind you, but I added a page that demos the Hadronize CLI. It seemed wrong to make the demo page blank and not include instructions, so I wrote some. It seemed wrong to use unstyled bare HTML, so I added holidaycss.

Next Steps

I think that there’s still some work I need to do in the game logic and CLI before I start working on the UI. The CLI demo currently doesn’t have any way to customize the game settings (e.g. how many players there are and what deterministic seed to use), so I’ll probably work on that next.

Thanks for reading!

0
0
4
Open comments for this post

6h 28m 9s logged

Core Game Logic

Today I implemented most of the core game logic in TypeScript. My code is pretty messy, probably has some bugs, and definitely has some idiosyncrasies that I should add docs for, but it does work correctly. Mostly. Here are a few highlights from today:

Determinism

The rules specify that quarks are created on-the-fly at the start of each turn, and that it’s impossible to predict what flavor a superposition will collapse into. Nondeterministic code makes me uncomfortable, so I decided to cheat a bit behind the scenes to make the whole thing pseudorandom and fully deterministic. In the game constructor, every quark that will ever be used during the game is pre-generated based on values from a mulberry32 function, then the collapsed flavor is predetermined ahead of time. Those two things: the list of future quarks that will be “created” on subsequent turns, and the flavor that each superposition will collapse into, are secret information that the players aren’t allowed to know, which means I have to be careful to sanitize the game state before it’s given to players.

I hate references

So, one of the first things that I did was create the Quark class. It has a few methods, but mainly it’s just a DTO for a flavor and a superposition. So my original plan was involved doing normal OOP and having each quark be owned by a Player class or the Game class itself. But once I actually started coding it, I remembered that I hate having to remember what’s stored as a value and what’s stored as a reference in JS. This is especially annoying when moving quarks between containers. So instead, I decided to just store an array of every extant quark, including not only a flavor and superposition but also an index. When a player class “owns” a quark, it really just owns that quark’s index number which corresponds to a quark in the game class’s SSoT. Crucially, the index number is a simple integer that doesn’t have any of JS’s object reference silliness.

Timeline

I decided that the game class should save every past state that it’s been in for some reason. I might use it in the UI to let users scroll back in time to see how the game played out, or maybe use it to make neat statistics at the end of the game, or something like that. It might also be useful for bots (more on that in a future devlog). But anyways, actually implementing the timeline was extremely frustrating, mainly due to Typescript. The final implementation that I settled on is pretty clean, but it was not my first thought, and I went through maybe a dozen different iterations over the course of an hour.

Next Steps

I’m probably going to spent a bit more time in the game logic before starting work on the UI. As I mentioned, I need to write docs for the idiosyncrasies of my code because otherwise I’ll forget how it works and that’s how bugs happen. Speaking of bugs, I’m sure that there are a few in my code, so I’ll probably write some tests to try to find them.

Thanks for reading!

0
0
2
Open comments for this post

3h 38m 56s logged

Hadronize

This is my first devlog for this project. It’s a multiplayer strategy game that you can play in your browser.

https://github.com/ethmarks/hadronize


Basically the only things that I’ve done so far are write the rules in the README and brainstorm a bunch. The rules are pretty important, so I’ll write them in this devlog. Because there’s a 4000-character limit to Stardance devlogs, I’m going to try to keep the rules shorter and less thorough than I did in the README.

Rules

Hadronize is a 2-6 player game which will probably take about ~10 minutes per game.

  • The goal is to be the first player to hadronize 10 or more quarks.
  • Quarks are basically the cards. There are 6 different flavors of quark: up, down, strange, charm, bottom, and top. By the way, I’m not making that part up.
  • Quarks start out as Superposed Quarks, which are quarks in a state of superposition between three different flavors. Once the superposition collapses (more on that later), it chooses one of the three flavors in its superposition and becomes a normal quark with a single flavor.
  • Each player starts with four collapsed quarks with randomly-chosen flavors in their respective cloud chamber.
  • On each turn, a new superposed quark appears. The players know that the quark will be one of the three flavors in its superposition, but they don’t know which one. The player whose turn it is (aka the active player) will choose any player (including themselves) to be the observing player. The observing player observes the superposed quark, which collapses it and adds it to their cloud chamber.
    • If the observing player has none of that flavor (e.g. the new quark collapsed into charm and the player only has down quarks), then nothing else happens and the turn ends.
    • But if the observing player does have at least one quark of the same flavor, something does happen.
      • If the active player chose themselves to be the observing player, the new quark reacts with all existing quarks of the same flavor, and they all hadronize together.
      • If the active player chose a different player to be the observing player, the new quark reacts with all existing quarks of the same flavor, and they all quantum tunnel from the observing player’s chamber into the active player’s chamber. In other words, the active player steals some of the observing player’s quarks.

If my explanation is unclear, check out the README because I probably explained it better there. If the README is unclear too, feel free to let me know by commenting on this devlog or opening an issue or whatever.

Mantis

If the rules sound familiar, it’s because I mostly just stole them from the card game Mantis by Exploding Kittens. My original idea was to just create a digital version of Mantis, but I was concerned about running into copyright trouble if I called it “Mantis” and used the same terminology and whatnot. Game mechanics can’t be copyrighted, but names and terminology absolutely can. I considered just making my game about abstract colors, but then I suddenly realized that making it about quarks would fit really well, so I did that instead. I did make a few changes to the core mechanics (e.g. using 6 flavors instead of 7 colors, and combining “scoring” and “stealing” into “observing”), but it’s still basically just a reskin of Mantis.

Next Steps

The next thing I’m going to work on is actually implementing the rules in TypeScript. After that I’ll probably work on the UI.


P.S. I also spent like an hour making a terrible-looking banner for Hadronize to use as the Stardance project image.

0
0
6

Delete project?

Are you sure you want to permanently delete this project? This action cannot be undone.

All devlogs, followers, and associated data will be removed.

Followers

Loading…