Sunday, October 9, 2022

Galactic Distances in Warhammer 40k

I've been trying to figure out the galactic distances between planets in Warhammer 40,000. We know the Eye of Terror corresponds to Cygnus X-1 (approximately 7,300 ± 200 light years away from Earth). The book The Horus Heresy Book III - Extermination gives a map of the galaxy with a hex grid background. We can reproduce the fragment involving the Eye of Terror and Holy Terra below:

I have computed the center of mass for the Eye of Terror (assuming uniform density) and drawn a straight line connecting Terra to the center of the Eye of Terror. Along this line, I have marked distances which are multiples of the edge for a hexagon. Since the Eye of Terror is approximately 8.4 hex-sides away from Holy Terra, it follows that a hex grid side length is 869 ± 23.8 light years.

Result: The side of a hexagon is 869 ± 23.8 light years.

Now, for the interesting systems to the "East" of Terra:

Again, we use circles to mark "milestones" whose distance is 1 hex-side length.

We find that Prospero is sqrt(57) ≈ 7.55 hex-sides away from Terra which would be 6560.80 ± 179.686 light years away from Holy Terra.

The Davin system is about sqrt(156) ≈ 12.489996 hex-sides away from Terra, which would be 10853.80652 ± 297.262 light years away from Holy Terra.

If this is accurate, then the distance between Prospero and Davin is approximately sqrt(27) ≈ 5.196 hex-sides, which would be 4515.45645 ± 123.668 light years.

Anyways, I'm interested in Davin's distance from Terra because Guilliman (and friends) fought the Second Battle of Davin before rushing to Terra to relieve Dorn, Sanguinius, and the Khan. I've been curious about the distances and time intervals, mostly as an excuse to generate exercises in special relativity. Assuming the distances measured are radar distances, the proper speed for Guilliman's relief force would be about 3618c (i.e., 3618 times the speed of light) and relative to an inertial observer on Terra Guilliman's speed would be about 3618/sqrt(36182 + 1) ≈ 0.9999999618026812 times the speed of light.

Objection: These calculations all work in flat geometry, which we know is false due to General Relativity.

Response: While this is true, the curvature due to general relativity is so slight, the corrections would be negligible. One more compelling reason to use general relativity would be to observe the galaxy is rotating, which means we'd need to use a non-inertial reference frame. But this is so small as to be negligible.

A better objection would be the location of these planets are not in the direct center of the hexagons. Assuming a uniform distribution of offset within the hexagon, we obtain an uncertainty of 16*sqrt(2)*(1/3 - sqrt(3)/8)/(4 + ln(27)) hex-sides ≈ 314.864 ± 8.623 light years in the distances between any two planets.

(The math behind this is simple, just take M = \int^{1/2}_{0}\sqrt{y^{2} + \frac{3}{4}}\,\mathrm{d}y = (4 + \ln(27))/16 as the normalization constant for the probability distribution Pr(y) = \sqrt{y^{2} + \frac{3}{4}}/M, then we find E[y] = \int^{1/2}_{0}y Pr(y)\,\mathrm{d}y = \frac{16}{4 + \ln(27)}\left(\frac{1}{3} - \frac{\sqrt{3}}{8}\right) as the expected offset. Another approach would be to consider a uniform distribution over the hexagon, then find the variance. I believe this would give an uncertainty of 1.01958 side lengths ≈ 886.015 ± 24.2660, but I should work through this more carefully. For the uniform distribution on the unit circle, we would have the variance of the radius be 5/18, corresponding to 458.003 ± 12.544 light years.)

Objection 2: In Angel Exterminatus, Perturabo notes that Cygnus-X was a name "re-used" on a different celestial body than it was originally named, so all these calculations are wrong.

Response 2: True, Perturabo made that "observation", but it makes no sense. Cygnus-X is literally the first confirmed black hole that humans have discovered, and that would not be easily changed. It would be as if "Mars" nows designates Alpha Centauri.

Again, a better objection would be that I have confused Cygnus X with Cygnus X-1, which would just rescale the distance of a hex edge by about 46/73 ≈ 63%, or 547.59 ± 15 light years.

Another way to estimate distances is to first identify the center of the galaxy, then find Earth (holy Terra). This will be approximately 27,000 light years. (Our current best estimate is that the Solar system is a distance of 8.33 ± 0.12 kpc ≈ 27168.83 ± 391.3877 light years, see Eq (2) of arXiv:1611.09144.) As a consistency check, it appears that Terra is about hex edges away from Sag A*, which would make Terra about 22 hex edges away from (what I think is) Sag A*, which would be an estimated 19118 ± 523.6 light years away...which means we'd need to increase each edge length by about 42% to 1235 ± 17.8 light years. [Using this estimate: The Eye of Terra is 10,374 ± 149.52 light years from Terra, Prospero is 9324 ± 134.4 light years from Terra, Davin is 15425.15 ± 222.32 light years from Terra, and Guilliman would have traveled at a proper speed of 5141 ± 74 times the speed of light. This also fits the claim "Armageddon is 10,000 light years from Terra" better, I believe.]

It would be interesting to compare the various maps from the different books, to check if they are all mildly consistent with distances, and specifically to examine the locations of various "known" bodies (e.g., Armageddon is supposedly 10,000 light years from Terra — is this just poetic hyperbole, or an accurate order-of-magnitude estimate?).

Thursday, September 22, 2022

Miniature Heights in Warhammer 40k

I've been thinking about miniature heights and scales in Warhammer 40k, because the game uses an idealized representation of distance (rather than an actual scale). This is because, if we tried using a realistic scale, the height of a human being 2 meters but represented by a 1 inch model...well, we end up with Bolters having an effective range of 550 meters, which would be 275 inches (compared to, what, 24 inches in the game).

Working the other way around, suppose the 24 inch range is the correct scaled distance. Then a 2 meter tall human would be represented by an approximately 2.2 millimeter tall figure.

Suppose we accept the idealized distances for weapons, but want more realistically scaled figures. How tall should they be? First let us try to consolidate what we know about various heights.

  • Adeptus Custodes are 9 feet tall, without their helmet on.
    • This is straight from the 7th edition Codex, They tower over mortal men; each has the statuesque physique of an ancient hero, close to nine feet in height even without his scarlet-crested helm.
    • Repeatedly in the book The Gate of Bones, the Custodes with helmet on is described as 10 feet tall and the helmet gives an extra foot of height.
    • Primaris Space Marines: First Impressions measures the Custodes miniature to be approximately 1.25 inches without a head, comparable to a Primaris miniature, but the Custodes has a wider stance.
  • Space Marines are between 7 feet tall and 7.5 feet tall. (It seems to have settled on using 7 feet as their height.)
  • Primaris Space Marines are 8 feet tall
    • Repeatedly in the book The Gate of Bones, the Primaris marines are referred to as standing 8 feet tall.
  • Primarchs seem to be around 3 meters tall, give or take "a head".
    • Lion El'Johnson is described as slightly less than three meters tall in Descent of Angels: The Lion was a truly imposing physical specimen. A giant, standing at a little under three metres tall, it was impossible to escape the suspicion that he had been cut from a broader canvas than the majority of men. His body was perfectly proportioned and entirely in scale with his height. He was powerfully built, lithe yet muscular. (Emphasis added)
    • Ferrus Manus stood a head taller than his brothers, as stated in Fulgrim: Ferrus Manus, clad in his shimmering fuliginous armour, stood a head taller than his brothers, pacing like a caged Medusan snow lion as he awaited news of the rest of his Legion. (Emphasis added)
  • The Emperor, people claim online, is 14 feet tall...which I find hard to believe, but whatever
  • Warhound Scout Titan (apparently the model is 250mm tall)
    • 14 meters tall, at rest

Of course, these are fantastical sizes. I'm not sure if 1 foot in 40k corresponds to our notion of a foot, because people are apparently shorter (around 5 feet tall for the average human). If we scale things appropriately, one "40k-foot" is then 5/6 of a "normal foot", or "1 40k-foot = 10 inches". Then a space marine is about "6 normal feet" tall, but Custodes are about "7.5 normal feet" tall (slightly taller than Shaquille O'Neal). This may also be just my own rationalization.

HO Scale

If we stick to the prescribed heights using "normal feet", and if were using HO scale, where 3.5 millimeters represents 1 foot, then we would have figures of the following sizes:

  • Adeptus Custodes would be 31.5mm tall figure without the helmet (and 35.0345mm with the helmet)
  • Space Marine would be between 24.5mm and 26.25mm tall figure (we could round to make it an even 1 inch figure)
  • Primarchs would be (3.5mm/foot) × 9.84252 feet = 34.44882mm tall figure, Ferrus Manus would be (9/8)×34.44882mm = 38.7549225mm; a primarch who is a head shorter than the Lion would be represented by a (3.5mm/foot) × (7/8) × 9.83252 feet = 30.1427175mm tall figure

The 10.3 meter long Land Raider would be represented by a 118.274mm long miniature (or approximately 4.65646 inches).

1:60.96 Scale

Continuing with the "normal feet" assumption, the scale Games Workshop appears to use is roughly 1:60.96 scale (5mm per foot, or 1cm per 2 feet). We can verify this by examining a Land Raider which is supposed to be 10.3m long, but the model is about 17cm long, gives us a scale of 1:60.5882 [if the model is 16.8963cm long, then it is indeed 1:60.96 scale].

  • Adeptus Custodes would be 45mm tall figure without the helmet
  • Space Marine would be about 35mm tall figure
  • Primarchs would be (5mm/foot) × 9.84252 feet = 49.2126mm tall figure, Ferrus Manus would be (9/8)×49.2126mm = 55.364175mm; a primarch who is a head shorter than the Lion would be represented by a (5mm/foot) × (7/8) × 9.83252 feet = 43.061025mm tall figure

S Scale

If we use the S Scale (i.e., the 1:64 scale), then we would have 4.7625mm model 1 foot. The 10.3 meter long Land Raider would be represented by a 16.0938cm-long model.

  • Adeptus Custodes would be 42.8625mm tall figure without the helmet
  • Space Marine would be about 33.3375mm tall figure
  • Primarchs would be (4.7625mm/foot) × 9.84252 feet = 46.875mm tall figure, Ferrus Manus would be (9/8)×46.875mm = 52.73mm; a primarch who is a head shorter than the Lion would be represented by a (4.7625mm/foot) × (7/8) × 9.83252 feet = 41.015mm tall figure

Tuesday, August 30, 2022

Imperial Palace Dimensions

While reading through the Siege of Terra book series, I wondered what were the dimensions of the Imperial Palace. It has a rougly Motte and Bailey design, where the bailey is called the "outer palace" (bounded by the Eternity Wall) and the keep is called the "inner palace" (bounded by the Ultimate Wall).

Puzzle: What are the dimensions of the Imperial Palace?

Understandably, they are seldom discussed, because people would complain about its various dimensions being unrealistic. However, in the fifth volume in the series, Mortis, in chapter 4 of part I (pg.107 in the hardback edition):

Now, they would simply make the whole circuit of the Ultimate Wall, all thirteen hundred kilometers of it.

From this, we can get bounds on the dimensions of the inner palace. The largest area enclosed within a given permiter is a circle (we know this from the Isoperimetric problem, since ancient Greece). That is to say, we would have the circumference equal to 1300 kilometers, giving us a radius of approximately 206.9 kilometers and diameter of approximately 413.8 kilometers; these are the lower upper bounds. (The area enclosed would be 134,485.95691 square kilometers.)

The official map makes the inner palace look more like a square, which would then give a side-length of approximately 325 kilometers. The area enclosed would be 105,625 square kilometers.

Addendum: There are ways to elongate the shape of the Inner Palace to produce inflated length. This is a pathological approach which, although possible, does not faithfully reflect the maps produced of the Imperial Palace. I thought it worth explicitly mentioning, that it has been considered and dismissed.

Objection: Earth is Curved. One may object the Earth is curved, but this negligibly affects the calculations involved at this scale. If we used the latitude/longitude coordinates as points in the Cartesian plane for the nation of China, then our error would be on the order of 1%. The Imperial Palace is on a slightly smaller scale. Our estimates would be off by a fraction of a percent, which is an acceptable error range (for me).

Observation of an inconsistency. We also read in Mortis, in chapter 6 of part I (pg.136 in the hardback edition):

Mercury wall, two hundred kilometres of defences that stood almost intact.

This makes the map associated with the Imperial Palace problematic, if taken to scale. Why? Because the inner palace is approximately a rectangle of scaled proportions 11-by-9. If we remove the portion of the wall for the Ultimate Gate, we would find a perimeter of 2084 kilometers. (See, this is why distances are seldom given as exactly as the quoted portions.)

Or, if the map is to scale, then the Mercury wall should be approximately 121.33 kilometers long.

Solutions. In my demented mind, it makes most sense to approximate the perimeter as a square, and make the Eternity gate a little bit smaller on the map drawn. That is to say, the Eternity gate is enlarged on the map for emphasis and clarity, but the map is roughly "to scale". This makes the Sanctus wall and the gap for the Eternity gate together 125 kilometers or so.

Or we could take the map drawn to scale, which would make the gap for the Eternity gate approximately 114 kilometers. Then the perimeter for the region (not just the wall, but also the gap) 1414 kilometers, and the inner palace would be approximately circular with radius 225 kilometers (bigger by nearly 16 kilometers) and diameter 450 kilometers. Its area would be about 159,106.8783 square kilometers (compared to our earlier result of 134,485.95691 square kilometers).

Estimate of Outer Palace. The area of the Outer Palace appears to be twice that of the inner palace. Again, a circle would maximize the area bounded by the perimeter. This would give us a radius bigger than our estimates for the inner palace by a factor of the squareroot of 2 (about 40% larger). Concretely, this would be roughly a circle of radius 320 kilometers, diameter 640 kilometers, and area of about 318,000 square kilometers.

Neglecting the region taken up by the Eternity Gate, this would be 1090 kilometers long [677.3 miles long]. To get some sense of this, I saunter slowly at 2 miles per hour (a very leisurely pace). It would take me 338.6473 hours to walk that distance; if I were walking 8 hours a day, that's 42 days plus a few hours. Most people walk at 3 miles per hour, which would require 225.76 hours to walk the distance [at 8 hours per day, that's 28 days plus change].

Estimate of the Eternity Gate region. The map makes it look like a rectangle approximately 4.5-units wide, 5-units long. It is approximately as wide as the Sanctus wall and the gap (which we estimated as 228 kilometers combined). This would make it approximately 253 kilometers long.

Taken together, this means the Imperial Palace is approximately 1,343 kilometers long. Notice this is also the length of the Eternity wall (curiously enough!).

Reality Check. The Himalayas, we are told, are approximately 2,400 kilometers long. Thus the Imperial Palace would take up half the Himalayas (approximately).

Exercise for Reader. If we want to preserve the proportions given and estimated, but wanted to make the Imperial Palace 2,400 kilometers long, then what changes must be made to the lengths reported by the books?

Friday, July 29, 2022

Warhammer Campaign and Mission Ideas

When I was in secondary school, I played Warhammer (both fantasy and 40k). I've been dabbling in it again — this time using wooden cubes instead of expensive miniatures. Since this is my "gaming blog" (I guess), I thought I'd write down some thoughts about campaigns and missions.

Narratives and Campaigns

Some time after 6th edition of 40k, Games Workshop introduced strategems and "narrative campaigns". I don't fully understand what these mean, so I will ignore them. Instead I will discuss different ways to structure campaigns I've enjoyed.

Path to Glory

Back around White Dwarf issue 275 or so, there was a free supplement called Path to Glory. You started with a Chaos warlord, and you built your war band from scratch using dice rolls and tables. The exact initial setup was the same for everyone, you start off with 35 "favor points" and then:

  • Step 1: your warlord. Your warlord starts off with basic gear, but you can use 1 favor point to get gear (you roll 1d6 and use a table of possible gear)
  • Step 2: your gods. You pick a Chaos God to follow (or you can worship them all equally); this is done once and cannot be undone.
  • Step 3: Form a war band. You need at least two groups [squads] of followers. You get followers by spending favor points to roll a die and use particular tables. If you use 1 favor point, you use the "more common follower" table; if you use 3 favor points, you can use the "awesome follower" table.
  • Step 4: Play a game! You play against others, and accumulate favor points by accomplishing various goals. You then use favor points to build up your war band further.

I really liked the feeling of building up an army from scratch. This guided my approach to structuring game play; for example,

  • Orkz: you are a nob trying to become a warlord. Or you're a Mek, trying to become a Big Mek.
  • Space Marines: you are a sargeant working his way up to higher rank; or a tech-marine trying to gather artifacts (or whatever they do); or an apothecary doing...apothecary-stuff.
  • Adeptus Mechanicus: you are a lowly tech priest trying to find artifacts and research sufficient to win favor and your own fabulous new car Martian forge.
  • Imperial Guard: you are a second-lieutenant given command of a platoon, rising through the ranks.
  • Inquisition: you're a paper/button pusher (or whatever they have in the 40th millenium) given a field job. (That's how inquisitors start out, right? Or is this like the Freelance Police where anyone with a gun can claim to be apart of it?) In either case, you start off with nearly nothing, and working your way up to Space Pope CEO of the Inquisition.
  • Sisters of Battle: you're a sister superior, working to fight Chaos.
  • Adeptus Custodes: ...wait, that's a "thing" now?
  • Chaos Space Marines: this is pretty much the same as Path to Glory, isn't it? You could be a "goodie two shoes" space marine who has fallen to evil ways, or a "vintage" 30k traitor.
  • Necron: you are some minor dignatary of your dynasty, trying to accumulate more power to guide your dynasty to power.
  • Dark Eldar: you're a space elf pirate "captain" of a pathetic vessel, or you're a petty officer of one, trying to accumulate enough to form your own mighty pirate fleet.
  • Eldar: are you an exodite? Or a corsair? Or a craft world? Perhaps you aspire to join the Harlequins? You hate chaos [or Necrons, or...] and you're forming a gang ranking up in the military to fight it (or whatever).
  • Tyrannids: you're a bug.
  • Tau: pick a caste, get some followers, and find out the real empire is the friends you make along the way.

In many cases (e.g., Imperial Guard, Sisters of Battle, Tau, probably also Eldar, etc.), for this approach to campaign building to work, then you need a "Game Master" who will set up an over-arching narrative. Why? Because the player is literally working at the "tactical level", and someone needs to fit it into an overarching strategy.

For others (e.g., Orkz, Chaos Space Marines, Adeptus Mechanicus, Dark Eldar, etc.), it's pretty self-sufficient for motivation: you're trying to smash other players (or, for Adeptus Mechanicus, accumulate artifacts).

I was always intrigued with the Orkz. You could be following the footsteps of Ghazghkull, trying to unite a planet to then lead a WAAAAAGH somewhere. Or you could be following the footsteps of Orkimedes (I love that name), trying to become a better Mek. (Or you could be a Dok trying to gather the resources and skills to become a better Dok.) Or you could be a speed racer trying to get parts to make his truk go faster.

(My favorite backstory for an Ork Mek: a tech-priest got hit on the head, and when he came to, he awoke amidst orks. The Tech-Priest then believes he is an Ork. Thus we got some fascinating backstory for a Mek. Disclaimer: I stole this from some guy, who posted it back 15 years ago or so, as a backstory to Orkimedes...I just can't find where it went on the internet.)

If you just look around, you can find inspiration for campaigns all around you.

Black Library Ideas

You can "take a page" from Black Library books: their plots literally consist of missions and campaigns.

The Infinite and the Divine revolved around stealing one artifact, and stealing it back, then transporting it to some location. (It's a great book, by the way, I'm just "gutting it" for meat.) This idea could easily be adopted for an Adeptus Mechanicus and Ork Mek pairing, or Inquisitor and Chaos pairing, or...

Belisarius Cawl was about escorting a tech-priest to study ruins, while another squad of Space Marines fought tyrannid bugs (or joined a cult, or whatever).

Priests of Mars is a rescue expedition, and an opportunity to find lost artifacts. On the flip side, it appears the Eldar are keen to defend their territory from pesky hew-mans.

Horus Rising is about violently suppressing innocent civilians, and terrorizing advanced civilizations. There's also some chapters involving space marines bullying giant spiders (finally something we can all relate to).

Example: Exploring a Planet

The computer game Mechanicus centers its plot around an Ark Mechanicus exploring a Necron tomb world. Each level boils down to [procedurally generating] some number of rooms, of which a few have Necron enemies. But each room has a decision to make: explore the room, analyze some obvious artifact, or leave as quickly and quietly as possible.

This could easily be turned into a game: represent a room by a card, shuffle your deck of "room cards", roll several six-sided die to determine how many rooms to place, and randomly generate a map using them. Be sure to make the outcomes of the choices depend on dice rolls, consider whether you want the results visible or hidden in a sleeve [e.g., an envelop contains a folded slip of outcomes, and an unfolded slip of choices], and so on.

In short, you start with an existing game for inspiration, but keep modifying it to work on the tabletop. If there are multiple players, for example, this could turn into a Hunt the Wumpus-type game: no one knows the location of other players until they run into each other, then it's a skirmish on the tabletop using 40k rules.

This works for Adeptus Mechanicus and Necron players, but it could include other Xenos players as well (Eldar could be trying to recover an artifact, as well; etc.). But it works with only a subset of factions. For example, I wouldn't know how to add fluff to explain a Space Marine player (or any other Imperium faction).

Missions follow from Narratives

If you have a strong narrative setup to your campaign, the missions follow quite naturally. Usually. For some (e.g., Imperial Guard), it's rather "exogeneous" [i.e., you need a Game Master]. Here history helps. For example:

  • You need to escort engineers to form a bridge to cross a river; this requires protecting the engineering squad for N turns, then rush the bridge to secure a bridgehead foot-hold. (Conversely, hold off an attacker from crossing a bridge.)
  • Escort character [pilot, VIP, POW, whatever] from the North-East corner to the South-West corner of the board. (Conversely: kill character before they escape.)
  • Search for MacGuffin [holy artifacts, secret battle plans, munitions/supplies] and return with it.
  • And so on...

These can be composed in larger narrative arcs. Let me show you what I mean:

  • Sieging a foritifaction, which requires/allows...
    • Helping sappers dig under the fortress walls, which requires a distraction
    • Intelligence reports enemy forces are hours away, so you need to spike the emplaced guns and the enemy army is arriving!
    • Escort engineers around the fortress's exterior to help determine where to place guns, or where sappers should dig, etc.
    • A messenger has escaped the fort, you must stop (or protect) him
    • Commandos from the fort must destroy certain munition depots, at night, so visibility is limited until the alarm is raised. (Conversely, the besieging army has commandos infiltrate to open the gates, or assassinate some character.)
    • For defenders, someone left the front gate open! Get as many defenders as possible to the landing pad for aerial evacuation.
    • Etc.
  • Preparing for a pitched battle
    • Protect engineers as they build a bridge crossing (happened a lot to Napoleon's army)
    • Capture and hold [building]; consequences could vary. For example, it could be a Lehman Russ factory, or it could just be a forward location which will end the battle faster.
    • Deliver a package [supplies, ammunition, fuel, whatever] to a location. No explanation: it's needed by other parts of the army, soldier!
    • Escort a messenger with updated plans, otherwise an entire Corps will be out of place. (Again, this happened a lot to Napoleon's armies.)
    • Forage for food for the corps, which requires going to fruit orchards and supply depots.
    • Blow up [building] before a battle takes place, which will affect deployment area (or delay part of the army until turn 3, or whatever).
    • Etc.

You need to weave these together to form a coherent arc for each army. These can be independent arcs: the Imperial Guard is trying to defend against an Ork invasion. The Orkz are just looking for scrap to launch their space hulk, so they can invade another planet (or whatever).

The same mission can have different objectives for each side. The Ork Mek vaguely recalls storing important stuff in the mines. The increased Ork presence in the mines motivates a reciprocal mission: the Imperial Guard needs to protect and escort the miners out of the mines.

Missions have Consequences, too

Failing a mission should have minor consequences. If the Imperial Guard fails to protect enough miners, there are long-term (but minor) consequences. If the Ork player fails to recover the Mek's parts, then the Mek needs to look elsewhere to parts to make [some class of vehicles] and the Ork player cannot use [class of vehicles] until they are found.

Failure should have consequences, but not render the game unplayable or impossible to win/progress. For example, the Mek's spare parts could be red paint, and no Ork vehicle can have red paint until some could be found. Minor, slightly inconvenient, but narratively interesting.

Settings Can Create Twists

You're on an ice planet. Using flame throwers will create water, which freeze again next turn (reducing movement). Also there's no friction, so vehicles slip and slide every which way. But the human body can survive the cold for three hours before freezing to death, which makes "Rescue [character]"-type missions now more time sensitive.

Or a desert planet, which requires careful water rationing. Without adequate water supplies, every stat decreases by 1. This motivates a new mission to resupply the water cisterns. The human body can survive 3 days without water...but it's not fun.

These are just a couple superficial examples which I give without knowing anything about the factions involved. We can imagine Forge World specific missions for an Adeptus Mechanicus player (or Ork Mek player), or Holy/Daemon world specific missions for Chaos Space Marines (or Inquisitors).

Where this is lacking

You could write down tables for followers and gear, true to form following Path to Glory, and use it to build your army up in a semi-random manner. When combined with a narrative campaign/mission, it is surprisingly compelling.

First problem: Craftworld Eldar and Harlequins are particularly difficult to work into this framework. That's because I don't know their lore well enough to "make it work".

Second problem: like Dungeons and Dragons after level 7 or so, it starts to lose something after some "initial army" has been established. I've thought about ways around this problem; for example, recursion (pick some lieutenant and build him up as a "reboot"). Or bigger rank means bigger problems (e.g., once you have reached "captain" rank, now you need to sort out which campaign arc to follow, you can be given a ship...which you must now maintain, etc.).

I don't think anyone has solved this second problem, in any game (otherwise everyone would've copied its solution).

On the other hand, at this point you will have a decent army set up. You could pivot to a map-based campaign, similar to one of the Total War video games (or Dark Crusade, or Soulstorm). This can easily be extended in any number of directions, depending on how much detail you want to include, or what region you want to fight over. (Fighting over a country is long, hard work; fighting for an entire planet would be quite another thing.)

Wednesday, October 28, 2020

Programming Exercise: Dice

A short exercise for the reader: come up with a domain specific language for rolling dice. This is a recurring mechanic in Rogue-likes.

Exercise 1. The conventional notation in Dungeons and Dragons is to write "mdn + k" (where "+ k" is optional) to roll m separate n-sided dice, sum them together, then add k to the result and return it. Write a function to accept a string of this form.

What happens when m is not a positive integer? When n is not a positive integer?

Exercise 2. In Dungeons and Dragons, when creating a character, you roll 4d6 but take the highest 3 values. How would you extend the domain language to include this situation?

The source for these exercises are the original Rogue-likes had a function which rolled dice based on a domain specific language, and this idea was picked up by Troll.

Thursday, October 8, 2020

One scheme to world-building

What makes this game fun? That's the question I want to ask when I've finished a game (or as I'm playing it). I recently re-played Fallout 2, and I noticed there's a lot of small quests which piece together to form a tapestry. Individually, the elements are not complex (deliver this item to so-and-so, talk to [person] about [subject]), but they compose together like lego blocks.

This post will discuss one way to world-building, which is necessary to coming up with quests and a game-plot. This is more a "review article" than anything innovative on my part.

Levine's "Stars" and "Passions"

Ken Levine has a great talk on "Narrative Legos". Basically, each location (village, fort, etc.) has around a half-dozen named characters ("Stars"), where each character has three "Passions". A "Passion" is what a character cares about relative to what the player can impact upon; it is transparent to the character, and responsive to the player's action. Effectively a "Passion" is a "bank account" for a Star (or a number between -10 and +10, starting at 0); helping a Star with their Passion results in that Star's invest positive points into their "account", thereby improve the Star's opinion of the player.

When a Star's opinion of the player (formed by combining the three Passion scores together somehow, e.g., adding them together, taking their geometric or harmonic mean, or whatever) reaches a certain high point, it unlocks certain bonuses. Blacksmiths offer additional bonus gear, Clerics offer additional services, etc. Conversely, if a Star's opinion diminishes, services cost more or are outrightly refused.

But two characters could have conflicting passions. This is a goal for writing a plot, because conflicting Passions for Stars means the player is thrust into a zero-sum game...which is fun for the player, and encourages the author to say, "Yes, and I can work this into another story arc!"

The number of characters should be around 5 or 6 to avoid over-burdening the player, and the number of passions should be 3 to avoid accidentally conflicting with too many other character passions (rendering the game unplayable accidentally).

There's a lot to digest here, and how we implement varies considerably. If we formalize a "passion" using a data structure (a few counters) and functions, we could [should] test the rewards and punishments are triggered properly upon shifting an NPC's opinion of the player. But this is just the observer pattern.

Exercise. Look at Fallout 1 and Fallout 2 (or any RPG you enjoy). For each town, write down who are the Stars and what are their Passions.

Begin with a Map and Needs

I've been playing a lot of post-apocalyptic games recently. I found it helps to begin with a map and asking myself, "How does society reproduce itself? Who produces what goods, and how are those exchanged among the cities producing them?" Looking at a real-world map, I can pick out a few cities that survived the apocalypse, think about trade routes, goods produced [at least food, water, armor, weapons, clothing], and this organizes and frames the thought-process about factions, their aims and beliefs.

These questions lead to more interesting power dynamics: multiple factions within a city disagree with how to distribute the goods, who to trade with, what to prioritize. How far are these factions willing to go to enact their policies?

A town that produces nothing except coordinates trading (like the Hub in Fallout) has its own unique concerns. Just to rattle off a few:

  • If a single partner (call it McGuffinsburg) is its sole source of McGuffins, then the internal politics of McGuffinsburg is a concern of the trading hub.
  • Raiders are a perpetual problem.
  • Power dynamics among competing traders; when there's little or no law, it gets quite cut-throat.
  • Arms dealers in particular encourage secret agents to incite war between two neighboring powers, to profit from selling arms to both sides.
  • Any of these could be reversed (McGuffinsburg exerting power over the trade hub, raiders as sympathetic figures, lawkeepers trying to maintain order, etc.)
  • Any two or more of these could be combined.

One bit of advice: just as each Star has 3 Passions (for the sake of foregiving the player for acting unfavorably against one Passion without alienating the Star, thereby cutting off a potential quest-giver), we should take care to have several sources for each commodity. This is a rule-of-thumb, not a Law: sometimes, it's fun to have a single provider for a good, which causes tension and drives the plot ("We need to finish the [apparatus] to provide [goods] to save the world").

Note: although I have been thinking about a game in a post-apocalyptic setting, there's nothing preventing us from applying it to any setting. It's just a little harder if we have no map. (Post-apocalyptic settings let me be lazy, and use existing maps.)

Recap. So far, we have considered using the economy as a way to organize towns and factions. Each town produces some goods, and need to trade with each other to survive. This leads to identifying factions within towns, tensions between towns, and problems to be sorted out. It also leads naturally to using Levine's "Stars" and "Passions" to further refine the game. Both provide natural motivations for quests.

The map gives us a way to visually organize factions, consider how society sustains itself, the relationships between different towns and factions. Such considerations naturally give rise to Stars and their Passions. Altogether we have not formed a plot, but the fertile grounds for a plot as carried out through quests.

We have thus the basic process of world-building naturally give us ideas for quests and plot-lines. The "bottom up" approach with Levine's Stars and Passions combines well with the "top down" approach of drawing a map, determining the villages and towns, coming up with economies, inserting Stars and their Passions within each town, generating factions, and so on.

How real is the economy?

We need to decide how much detail the economy needs. This can serve a variety of purposes: just fluff, determine the actual value of goods, or as grounds for certain quests. Let's consider this last point in particular.

As for modeling the value of commodities using economics, this has problems in the real world using textbook economics. As far as world building cares: value matters for trade routes, and for player bartering with merchants. For trade routes, we only need them to feel "about right" (e.g., goods expensive in one town is imported from a town where those goods are cheap, don't import goods when "domestically produced" versions are cheaper than the imported version, etc.).

Suggestion: Update the world map to reflect trade, specifically roads and ports are built (and improved) over time to better facilitate trade between partners. The quality of roads and ports reflect the trade power between partners.

For the player, accuracy can conflict with fun. When this happens, always side with fun (unless we want to create a constraint for quest lines, e.g., iron shortage causes more expensive equipment...motivating the player to, y'know, fix that shortage). The real concern is that the player has access to equipment matching the challenge. We don't want to give the player overpowered gear too early, nor do we want to force the player to have access only to mediocre equipment.

Economy for lore, well, this provides the grounds for quests. Town A wants to open trade with town B since B produces silk cloth. This isn't reflected in the goods sold in either town, but provides a new quest-line. Alternatively, if B were instead the sole source of iron, then town A could supply only, say, bronze equipment. This combines lore and player experience (which is good and desired: the player should experience consequences of their choices).

In short, put yourself in the world, and ask yourself, "What goods would I have access to? How would I get food? Water? Who produces them? How would I get them? What about luxury goods? Or equipment?" Answering these questions require us to consider the towns further, and increases the realism. It's not enough to have farms randomly placed around towns (Fallout 4 tried to do that): we must also consider the infrastructure, the shortages, needs, scarcities and abundances. This leads us to consider how towns interact, how factions within a town interact, and helps us build a world.

Generating History and Culture

History, Myth, State formation. If we consider how these Stars and villages interact, we can generate a history from conflict. Items of our Stars become revered artifacts. Music and art memorialize these events. Myths emerge from misunderstanding or deliberate lies. Rivalries build up, grudges between Stars and factions emerge over time. Villages band together, forming quasi-states, which dissolve under stress and strain.

Governments. It's worth noting that we could borrow liberally from history. For example, the Polish–Lithuanian Commonwealth had a unique form of government that is seldom discussed...it could easily generate problems to be remedied for plot-line. The ducy of Venice picked its leader through a lottery (well, a lottery picked an electorate, who then picked another electorate, and so on — the convoluted process of lotteries and indirect elections resulted in a new duke).

Religion. I don't have much to comment on here. Post-apocalyptic games tend to seldom discuss religion, and the fantasy games I play have similar pantheons. One thing worth considering, the original Rogue had "daemons" responsible for updating the health, etc., for players. I don't think anyone has made these daemons the Pantheon for the game, which could lead to interesting gameplay: praying to daemons leads to temporary buffs, destroying temples related to a daemon results in temporary negative buffs, etc. Or it could have the same effect as praying to the laws of physics (i.e., nothing noticeable).

Communication. And the most underappreciated point of consideration: it takes time to communicate these events. When an event occurs, news of it spreads through caravans and travelers. Spreading information takes time, and plans revolve around information. This is a challenge to code up, because we no longer have a simple observer pattern to update dialog and quest lines.

Friday, October 2, 2020

Testing the Game

I've come to the opinion, when writing software, you should test it...usually unit testing suffices. But a game is a special kind of software. So special, one naturally faces the question, "Should we still unit test a game?"

To be clear, there are varying degrees and different notions of "testing" a game. We could test the software (make it "bug free", or at least have fewer bugs), test the enjoyability of the game (e.g., make sure it's fun, winnable, etc.), test the UI behaves as desired, "integration tests", end-to-end testing (some sort of "autmated player" searching for specific bugs). I'll discuss a few of these notions.

Testing the Code

If we have adopted a model-view-controller architecture of some flavor, then we can unit test the models. I contend we should unit test the models, and use contracts to enforce the assumptions of the model methods. What would this look like?

We can encode assumptions like Actor::dies() should demand the actor's health is non-positive (i.e., either zero or negative). This could be encoded with an assertion ("precondition"). Then we could write a unit test to create an actor, give the actor some amount of health points, cause damage, then try to call actor.dies(). There are three test cases (when actor.health() is positive, zero, and negative) which should result in the death of the actor in two cases.

Organizing Unit Tests

For object oriented languages, I'm inclined to follow some kind of xUnit testing framework or JUnit: each class we write (say class Thinger) should have some corresponding test class (e.g., class ThingerTest) where each method of the class is tested several times...so Object Thinger::methodOne() should have several corresponding methods void ThingerTest::methodOneShouldDoXTest(), and so on.

For Lisp, there's usually a framework given (Clojure has clojure.test, Common Lisp has several frameworks, etc.). The organization is analogous as for object-oriented languages (functions in module.lisp like (defun thinger-method (...)) should have several test cases handled in module_tests.lisp).

Terminology: JUnit organizes test cases as methods using assertions on a Test class, which are organized into test suites (analogous to how files are organized into directories). A test runner then iterates through the test suites and executes each test case, recording results (both successes and failures) for later use. The exact terminology varies (some xUnit systems, e.g. in smalltalk, have test case classes), but the intuition remains the same: test cases organized into test suites, and a test runner that executes the test cases and records the results.

We organize code by modules, which contain classes, which contain methods. These terms are used loosely: C programmers lack any module system, but use structs instead of classes, and functions instead of methods; Haskell programmers use modules, data types, and functions; etc. Whatever the terminology, we have some kind of ersatz class and ersatz method. Each "class" should have a corresponding test suite, each method should have several tests. Depending on how we organize classes, we should have a corresponding organization of tests: if we have one file per class, we should have an analogous file per test suite. The motivation for this scheme is to make it obvious where to place tests for code (all the tests for /game/src/models/my_module.code is placed in /game/tests/models/my_module_tests.code for example). It's more important to be consistent in whatever scheme you choose.

What to Unit Test

Test only code you have written. There's no need to write tests for third-party libraries. We trust ncurses works as expected, the GNU Scientific Library functions, and so on. It's only the code we wrote that we want to test.

We should unit test all public functions. While aiming for 100% coverage is ideal, if we get to "a lot" (I dunno, say, ~90% or whatever), we can say it's "good enough". The rationale here is that public functions are used to build our game, so if we have tested them thoroughly enough, then we can have greater confidence in their correctness (they do what we think they should).

Test all code paths. Has each statement in the method been tested? Has each edge in the control-flow graph been tested? Has each branch of every if-else statement been tested? (Or every case in a switch statement been tested?) Has every boolean subexpression of each conditional been tested? Complicated conditional tests could be refactored into predicate functions, which can be independently tested.

Each function should do one thing, and unit tests make sure the function does what we expect/hope. For example, the Actor::dies() method does one thing; once it is called, we should have Actor::isAlive() return false. This gives us two cases to consider: one where Actor::dies() fails (e.g., when Actor::health() is positive), the other when Actor::dies() succeeds. The former case should have Actor::isAlive() return the same result as Actor::health() > 0, the latter should have Actor::isAlive() == false.

Tests should be atomic. Each test case will test exactly one thing. If a test case is testing more than one thing, we should refactor it into multiple test cases.

Tests should be independent of each other. They should not rely on each other (in the sense that they don't call each other). A unit test should test exactly one thing.

Tests should be readable. Think of them as not just testing the behavior of the function, but also as an example of how to use the function. This gives us a name for the test (e.g., Actor::diesShouldNotBeAliveTest() or Actor::healthy_should_not_be_dead_test(), etc.).

Tests should be repeatable/deterministic. We should test the mechanical parts of the game (e.g., marking an Actor with zero health as "dead") where the same inputs produce the same outputs. If we are testing randomness ("rolling a die"), we should have some way to "mock out" that randomness with something deterministic ("load the die", "use a two-headed coin", etc.) to make sure the methods do what we expect.

Tests should be fast. Since each test case tests exactly one thing, we should make them small and fast.

Tests should be automated and tracked. We should be able to run the tests with a single command (e.g., "make test" or whatever), and we should include the test code in our git repository. Best practices suggest running the tests and make sure they pass before pushing code out to the repository's master branch ("don't break master").

Testing the Game

"Testing the game" has several distinct meanings: make sure the game is playable, make sure the game is fun, etc. In some sense, unit testing is like checking to make sure each square of the board is flat: but if we glue the edges badly, we could actually end up with a curved board. Unit testing checks locally each function does what we hope, but it doesn't check the game does what we hope. This motivates integration testing and end-to-end testing.

Integration testing can be useful. If we want to make sure dialog options trigger quests and completes quests, we need integration testing. This amounts to setting up a mock game, simulating dialog, then checking the game state matches what we expect. Since multiple "units" are being tested in conjunction (dialog, quests, etc.), we're really testing that they're "integrated" correctly. For people trying to create an old-school Fallout or Wasteland-type game, this can be very useful.

Testing from the Player's Perspective

I would suggest testing the game from the user's perspective. This is harder to do, and varies depending on the type of game you're making. In my mind, I assume you are programming something like a Baldur's Gate, Fallout, or Wasteland-type game: a mixture of quests, dialog, combat, and possibly more.

What do we hope to test? We'd like the game to be playable (quests "fit together" in a way that the player can get to the end of the game), but we'd also like the game to be fun. This is where design decisions are needed: how do we specify a game to be "fun"? Is there sufficient choice architecture?

Test the game is playable (quests sequence properly). For example: quest A occurs before quest B, wherein quest A requires killing actor X, but actor X issues quest B after completing quest A, rendering quest B un-triggerable. (More concretely: if the king gives us a quest after completing his minister's quest, and the minister asks us to assassinate the king, then there better be some mechanism for us to continue after killing the king...like the minister takes over. Otherwise, if we are waiting on the deceased king to give us our next quest, we'll be stuck.)

If we have a domain specific language for quests, actors, items (and if we store these in .info files), then we could have a simple helper program which runs through the quests, makes certain the quest items are fetchable, the quest-issuing actors are alive, and there are chains of dialog/quests which start with a specified initial quest and end at the specified final quest.

The helper script should record sequences of quests which are unwinnable, or when there are disconnected components (e.g., killing actor X early in the game prevents quests B, C, and D). At the end, it will print out to the screen a summary (along the lines of "M paths succeed, N paths tried with K character builds") and a more verbose explanation to a file ("Character build C played the quest chain Q1, ..., Qm then got stuck at quest X") possibly with the trajectory of events for reconstruction. We could automate this script to try all variations of skills and stats, too.

I've discussed this idea in passing a few times, I'll probably make it the subject of a future post...maybe have a minimal working example for people to play with, we'll see. It'll involve a variation of depth-first search along a few distinct play-styles...we'll see, friends, we'll see.

Test you aren't a jerk to the player. Suppose our game has factions and the player has a reputation (loved, liked, undecided, disliked, hated). If our game penalizes the player's reputation when the player kills a member of the faction, then we should beware of the situation when the player witnesses the death of a faction's member: will this tarnish the player's reputation or not? This is a prime candidate for sticking away into a unit test, for regression testing.

If this is part of the plot (the player, witnessing a murder, is then falsely charged with the murder), then it should be written into the game manually. The last thing a player wants is to find the police are after them for...apparently doing nothing. That may be amusing to the programmer (I certainly chuckled), but it's no fun to the player.

There are other similar cases which, when programming, do not immediately sound consequential. But for the player, it feels like the game is designed by a vindictive jerk. It may not be easy to discern when this happens, but once discovered we should try to create unit tests to ensure we aren't jerks.

Heuristic "Tests"

These are measurements of symptoms which boring games exhibit. Alas, there's no way to automate the underlying "boring-ness" away.

Test the game has choice and consequences. Does dialog change to reflect the player's actions? Are new quests opened up specific to the player's choices? Do new interactions [dialog, NPC encounters, quests offered] occur after the player chooses particular outcomes?

Is it possible to have a playthrough where the player kills everyone before talking to them? This forces us to design the quests with constraints that force the game to have consequences and the player to have freedom. Chris Sawyer noted this design decision in an interview with IGN as key to game reactivity and player choice. We can enforce this check with a particular playthrough in our helper script.

Test the game takes you to all the locations. What locations are visited by the play-throughs? We could dump the trajectory of locations visited for further analysis. Sometimes a location is visited more frequently than intended, other times a location is never visited. This is a symptom of possibly less fun games, which can't be automated to enforce: it's an aid to help revise quest considerations.

In general, test for symptoms of fun. Depending on what your game is trying to accomplish, the criteria for "having fun" varies. Each criteria has different symptoms, and we should figure out how to automate ways to check these symptoms are present in our game. On the flip side, there are certainly symptoms of anti-fun: fun-killing elements we want to avoid. We should also automate ways to check these anti-fun elements are not present in our game.

In some sense, this is the best we can do with automated testing: test for proxies of what we want, and regression-checks against what we dislike. There's no way to properly "test for fun", but we can test the game can be played in different playstyles and for the "kill everyone before you even interact with them" heuristic Chris Sawyer noted.

Concluding Remarks

Game developers tend not to test their games, at least not in the same way that software engineers test their programs. Unit testing is generally discouraged among game developers, for good reason (having unit tests give false sense of being "correct", whereas games seek fun not correctness).

But we can test for an RPG "being playable". We can further make such testing automated. Insofar as we can make such testing scripts, I think we should...at least, I should. Such automated testing checks the quests are ordered correctly and unlockable, speakers are referenced properly, and so on. Again, this doesn't test gameplay, but it tests the game can be played.

As for what this looks like, I'm working on a minimal RPG I've decided to refer to as "project Delaware". (Why Delaware? Nothing special: I've just opted to use the names of states in the U.S. by order of admission to the union. And Delaware is the first state admitted to the union.) I hope to have something to share soon-ish.

Chronicling a Roguelike

Bread crumbs and notes on designing a roguelike from scratch.

Table of Contents