<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Mahjong Bay Dev Notes]]></title><description><![CDATA[Mahjong Bay Dev Notes]]></description><link>https://mahjongbay.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6afcd28bfcf9b4f33517722f/e01a01db-bdb0-4684-bf88-073a50b9d61b.png</url><title>Mahjong Bay Dev Notes</title><link>https://mahjongbay.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 25 Nov 2026 11:35:47 GMT</lastBuildDate><atom:link href="https://mahjongbay.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[My Shisen-Sho dealer hit a dead end 99.9% of the time, and nothing told me]]></title><description><![CDATA[A Shisen-Sho (Mahjong Connect) board generator that filled an empty grid dead-ended on 99.9% of attempts and silently fell back to a shuffle.]]></description><link>https://mahjongbay.hashnode.dev/my-shisen-sho-dealer-hit-a-dead-end-99-9-of-the-time-and-nothing-told-me</link><guid isPermaLink="true">https://mahjongbay.hashnode.dev/my-shisen-sho-dealer-hit-a-dead-end-99-9-of-the-time-and-nothing-told-me</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Game Development]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[debugging]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Mahjong Bay]]></dc:creator><pubDate>Thu, 19 Nov 2026 15:28:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6afcd28bfcf9b4f33517722f/6d6f8193-bd2b-49d6-99dc-7fbd68227dcc.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The evening before Mahjong Connect went live on <a href="https://mahjongbay.com/mahjong-connect/">Mahjong Bay</a>, the page I was about to publish said "every deal solvable" and the code behind it was dealing plain shuffles. No error, no warning, a board on the screen that looked fine. The generator I had written was failing on practically every attempt and a polite fallback was covering for it.</p>
<p>This is the write-up: what the game needs, the generator I wrote first, how I found out it was not doing its job, and the twenty lines that replaced it.</p>
<h2>The game in one paragraph</h2>
<p>Mahjong Connect is known in Japan as Shisen-Sho. Tiles lie flat in a grid, nothing is stacked. Two tiles with the same face can be removed when a line of at most three straight segments joins them without crossing another tile. Three segments means two turns. The line is allowed to leave the grid and run along the outside. My version has no gravity: when a pair goes, the rest stays where it is.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6afcd28bfcf9b4f33517722f/0002094c-c88a-41f8-905f-9ca4e6dd3d68.png" alt="Four small grids showing a straight connection, a one-turn connection, a two-turn connection through a gap, and a two-turn connection around the outside" style="display:block;margin:0 auto" />

<h2>Finding a path with two turns</h2>
<p>Everything else is built on one question: can cell <code>a</code> see cell <code>b</code>? There are only three shapes to check, and I check them in order of cost.</p>
<p>A straight line, if the cells share a row or a column. An L, through either of the two corner cells. And a U or a Z: pick a row, walk from both tiles to that row, and see whether the stretch between them is clear. Then the same with columns.</p>
<pre><code class="language-js">function empty(x, y) {
  return x &lt; 0 || y &lt; 0 || x &gt;= W || y &gt;= H || g[y * W + x] &lt; 0;
}

for (y = -1; y &lt;= H; y++) {
  if (y === ay || y === by) continue;
  if (!empty(ax, y) || !empty(bx, y)) continue;
  if (clearV(ax, y &lt; ay ? y : ay + 1, y &lt; ay ? ay - 1 : y) &amp;&amp;
      clearV(bx, y &lt; by ? y : by + 1, y &lt; by ? by - 1 : y) &amp;&amp;
      clearH(y, Math.min(ax, bx), Math.max(ax, bx)))
    return [[ax, ay], [ax, y], [bx, y], [bx, by]];
}
</code></pre>
<p>Two details carry most of the weight. <code>empty</code> answers <code>true</code> for anything off the grid, so the outside border is ordinary free space and needs no special case. And the loop runs from <code>-1</code> to <code>H</code> inclusive, one row above the grid and one below, which is how the line gets to go around.</p>
<p>The function returns the corner points, not a boolean. The game draws that polyline for a moment when a pair is taken, so a player can see why a move that looked impossible was legal.</p>
<p>The rule cuts both ways. Here are two tiles one cell apart that cannot be joined, and the same two after the row above them has opened:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6afcd28bfcf9b4f33517722f/e03b1729-05fb-43d6-84a7-f2949dbf097d.png" alt="Left: two Red Dragons with one tile between them and full rows above and below, not joinable. Right: the row above is empty and a two-turn line joins them" style="display:block;margin:0 auto" />

<h2>The dealer I wrote first</h2>
<p>I already had a dealer for the stacked solitaire on the same site. It builds a board by playing backwards, and its boards are solvable by construction. For Connect I reasoned the same way and wrote this:</p>
<ol>
<li>Start with an empty grid.</li>
<li>Take the next pair of faces.</li>
<li>Find two empty cells that can see each other. Put the pair there.</li>
<li>Repeat until the grid is full.</li>
</ol>
<p>The logic holds. Each pair was joinable at the moment it was placed, with only the earlier pairs on the board. Remove the pairs in the opposite order and every one of them is joinable again, because the board looks exactly as it did when that pair went down. A full grid built this way has a solution.</p>
<p>The catch is step 3.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6afcd28bfcf9b4f33517722f/850823b3-cc2b-4965-a0ac-2b6bda309154.png" alt="Top row: filling an empty grid, the last two holes end up walled off from each other. Bottom row: emptying a full grid, each lifted pair opens more routes" style="display:block;margin:0 auto" />

<p>On an empty grid any two cells can see each other. On a nearly full grid, two random holes almost never can: each is boxed in by tiles, and unless they are neighbours or happen to face each other along the border, no line with two turns reaches from one to the other. The dealer cruises through the first 90% of the board and then finds that the last few holes are strangers.</p>
<p>When step 3 found nothing, the function gave up on that attempt and tried again from scratch. After enough failures it did the sensible defensive thing:</p>
<pre><code class="language-js">var flat = [];
pairs.forEach(function (p) { flat.push(p[0], p[1]); });
return shuffle(flat, rnd);
</code></pre>
<p>A board has to come out of the function, after all.</p>
<h2>How I found out</h2>
<p>Not by playing. The boards looked like boards.</p>
<p>The first sign was a crash in an early version that had no fallback yet: <code>Cannot read properties of null</code>. I added the fallback and the crash went away, which felt like a fix. The second sign was speed. I tried to make step 3 smarter by placing the most boxed-in hole first, and deals got slower: 71 ms, 218 ms and 557 ms for the three board sizes in Chrome. Slow, but they came back.</p>
<p>What settled it was a test of the claim itself. The dealer records the order in which it places pairs, and the test replays that order backwards and checks that each removal is a legal move. On the first run the test had nothing to replay. Every board in the sample had come out of the fallback, so there was no recorded order at all.</p>
<p>I went back later and counted properly, on all three board sizes:</p>
<table>
<thead>
<tr>
<th></th>
<th>10 x 6</th>
<th>12 x 8</th>
<th>16 x 9</th>
</tr>
</thead>
<tbody><tr>
<td>Dealing attempts</td>
<td>19,412</td>
<td>15,000</td>
<td>6,000</td>
</tr>
<tr>
<td>Ended in a dead end</td>
<td>19,391</td>
<td>15,000</td>
<td>6,000</td>
</tr>
<tr>
<td>Pairs placed before the dead end, on average</td>
<td>26.9 of 30</td>
<td>42.9 of 48</td>
<td>64.2 of 72</td>
</tr>
<tr>
<td>Boards that fell back to a shuffle</td>
<td>379 of 400</td>
<td>300 of 300</td>
<td>120 of 120</td>
</tr>
</tbody></table>
<img src="https://cdn.hashnode.com/uploads/covers/6afcd28bfcf9b4f33517722f/7281556e-0f4a-4cf1-9117-95f328115d6d.png" alt="Bar chart: share of dealing attempts that ran into a dead end, forward dealer against reverse dealer" style="display:block;margin:0 auto" />

<p>Fifty attempts per board, and on the two larger sizes not one of 21,000 reached the end. The dead ends came with three to eight pairs still in hand, which is exactly the picture above.</p>
<h2>The same idea, pointed the other way</h2>
<p>The fix was to stop filling and start emptying.</p>
<ol>
<li>Start with a full grid of blank tiles.</li>
<li>Find two blank tiles that can see each other.</li>
<li>Lift them, and remember that those two cells get the next pair of faces.</li>
<li>Repeat until the grid is empty.</li>
</ol>
<pre><code class="language-js">function place(cells, pairs, rnd) {
  var g = [], faces = [], order = shuffle(pairs.slice(), rnd), left = shuffle(cells.slice(), rnd);
  for (var i = 0; i &lt; W * H; i++) { g[i] = -1; faces[i] = -1; }
  cells.forEach(function (c) { g[c] = 0; });            // every cell holds a blank tile
  for (var k = 0; k &lt; order.length; k++) {
    var a = -1, b = -1;
    for (var t = 0; t &lt; left.length &amp;&amp; a &lt; 0; t++) {
      var i2 = Math.floor(rnd() * left.length);
      for (var j = 0; j &lt; left.length; j++)
        if (j !== i2 &amp;&amp; path(g, left[i2], left[j])) { a = left[i2]; b = left[j]; break; }
    }
    if (a &lt; 0)
      for (var i3 = 0; i3 &lt; left.length &amp;&amp; a &lt; 0; i3++)
        for (var j3 = i3 + 1; j3 &lt; left.length; j3++)
          if (path(g, left[i3], left[j3])) { a = left[i3]; b = left[j3]; break; }
    if (a &lt; 0) return null;
    faces[a] = order[k][0]; faces[b] = order[k][1];
    g[a] = -1; g[b] = -1;                                // lifted: now free space
    left = left.filter(function (c) { return c !== a &amp;&amp; c !== b; });
  }
  return faces;
}
</code></pre>
<p>It tries random tiles first and falls through to a full search only if luck runs out. The order of lifting is a solution, read forwards this time. And the direction changes the odds completely, for a reason that fits in two sentences. Removing a tile can open a path and can never close one. So the grid only gets friendlier as the dealer goes, where the forward version made it more hostile with every pair.</p>
<p>It is in fact impossible for this version to get stuck, and the argument is short. Look at the topmost row that still has tiles. If it has two or more, any two of them can be joined through the row above, which is empty or outside the grid: up, across, down. If it has exactly one, go along that row, which is otherwise empty, to the column of any tile in the next occupied row, and then straight down to it. Either way a pair exists while two tiles remain. The <code>return null</code> is still in the code. In 820 deals it has not fired once.</p>
<h2>What changed, measured</h2>
<p>I ran three dealers against the same random-clicking bot: a plain shuffle, the forward dealer with its fallback, and the reverse dealer. The bot clicks a random joinable pair, again and again, and stops when the grid is clear or it has no move. It gets a fixed number of fresh tries at each deal.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6afcd28bfcf9b4f33517722f/3030df25-411e-49c1-9fdb-0c78728c6e6e.png" alt="Bar chart: share of boards the bot cleared at least once, for a plain shuffle, the forward dealer and the reverse dealer on three board sizes" style="display:block;margin:0 auto" />

<table>
<thead>
<tr>
<th>Board</th>
<th>Plain shuffle</th>
<th>Forward dealer</th>
<th>Reverse dealer</th>
</tr>
</thead>
<tbody><tr>
<td>10 x 6, 400 boards, 100 tries</td>
<td>100 cleared</td>
<td>138 cleared</td>
<td>400 cleared</td>
</tr>
<tr>
<td>12 x 8, 300 boards, 100 tries</td>
<td>32 cleared</td>
<td>31 cleared</td>
<td>300 cleared</td>
</tr>
<tr>
<td>16 x 9, 120 boards, 50 tries</td>
<td>30 cleared</td>
<td>35 cleared</td>
<td>120 cleared</td>
</tr>
</tbody></table>
<p>The forward dealer's column tracks the shuffle's, as it should, since that is what it was dealing. On the reverse dealer the bot cleared 376 of 400 small boards on its very first try, 263 of 300 medium ones and 92 of 120 large ones. Connect without gravity is a forgiving game once the deal is sound: a wrong move rarely locks anything, because taking tiles away only ever helps.</p>
<p>Dealing got faster too, which I had not expected from the version with the stronger guarantee. In my test script the forward dealer averaged 42 ms per small board, 197 ms per medium one and 797 ms per large one, nearly all of it spent on attempts that went nowhere. The reverse dealer took 2.3 ms, 9.1 ms and 27 ms.</p>
<p>One more number from the same runs, because I was curious what the moves look like:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6afcd28bfcf9b4f33517722f/73220046-78e1-4596-8ee5-1a81b141efdb.png" alt="Bar chart: share of straight, one-turn and two-turn connections in random play on a 12 by 8 board" style="display:block;margin:0 auto" />

<p>On the medium board 6% of the bot's moves were straight lines, 16% had one turn and 78% used both turns. The game is mostly about the long way round.</p>
<h2>What I took from it</h2>
<p><strong>A fallback that returns a plausible result needs a counter.</strong> Mine converted "the generator is broken" into "the generator is a bit slow". Had it incremented a number I looked at, the first run would have shown 379 out of 400.</p>
<p><strong>Test the promise, not the output.</strong> I had looked at boards. They had tiles on them, the right number of each face, pairs that could be clicked. None of that is the promise. The promise was "there is an order that clears this", and the only test that speaks to it is one that replays an order.</p>
<p><strong>When construction keeps cornering itself, try the mirror image.</strong> Filling a grid makes every next step harder and emptying one makes every next step easier. The proof of correctness was the same in both directions. Only one of them could finish.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6afcd28bfcf9b4f33517722f/1317e858-f245-423e-8d51-4c0b4da1aebd.jpg" alt="The medium Mahjong Connect board on Mahjong Bay, 12 by 8 tiles" style="display:block;margin:0 auto" />

<p>The Connect boards are at <a href="https://mahjongbay.com/mahjong-connect/">mahjongbay.com/mahjong-connect</a> in three sizes, if you want to check my claim about the long way round. The dealer for the stacked solitaire, the one that worked on the first try and made me overconfident, is on GitHub: <a href="https://github.com/gamefancreator/mahjong-solvable-deal">gamefancreator/mahjong-solvable-deal</a>.</p>
]]></content:encoded></item></channel></rss>