JEG2
How Best to Use TDD for Random Generation
There is some code that I’m still not good at building out with a process of Test-driven Development. One of those challenges is random content generators.
For example, I used to play a great BBS game called TradeWars. A lot of what made it fun was the way it generated interesting maps. Here’s an image of one:
Some neat features of what has been generated are:
- The dense cluster of interconnected sectors 1-7
- Rings like 52, 66, 76, 77, 67, and 53
- Choke points like 153
I might choose to force some features into every map, like the dense center. Then it makes sense to test for them. But what about things like chokepoints and rings? It’s possible that they wouldn’t randomly form. I guess I could randomly generate maps up to some selected cutoff, until I either find one or give up, but that feels like a super annoying Selenium test that just times out sometimes due to dumb luck.
I could lock a random seed, but that feels like it’s not exercising the generator very much. What if there are some random events that cause it not to reach the configured number of desired sectors? I wouldn’t find bugs like that I only ever checked known good inputs.
My instincts are to build a visualizer and just look at what it spits out until I have what I like. However, I’m really interested in challenging myself to see if I could use TDD to construct the code without this cheat.
Any thoughts are appreciated. Thanks in advance!
Most Liked
stefanchrobot
Not an expert, but I think this might get easier if you switch from “a map has a 1/N chance of having X” to “at least 1 map out of N will have X”. So you’d generate a sequence of expected predicates (1 * “has X” + (N - 1) * “does not have X”) and then do a random shuffle. You’d need some state to keep track of when you need to generate a new sequence.








