Cover: 3 small game repos in 3 languages and their hidden bugs, with a tic-tac-toe board and a fading X
Short answer

Three small public game repos each hide a bug that playing them won't show. The Swift tic-tac-toe keeps letting the AI move after a round ends, both tic-tac-toe AIs block or play threats that vanish under the three-piece rule, and the Kotlin word game can hand you a stage that has too few words to finish. Separate rules from UI, write the invariants down, run random games and full content sweeps against them, and solve small games outright: three-piece tic-tac-toe is a forced first-player win, but only from an edge cell.

Tic-tac-toe looks like the safest possible side project. Nine cells, two players, one afternoon of work. Then you add a single twist, like a rule that makes your oldest piece vanish, and the logic stops behaving the way your head expects. You can play a build for an hour without seeing anything wrong, because a person plays one line of a game while the bugs sit in the lines nobody tries.

This post goes through three public game repos from github.com/jerrypm: the same three-piece tic-tac-toe in Swift and in JavaScript, plus a word puzzle in Kotlin. They are small enough to read in one sitting, and each one has a bug that plain play testing would miss. The numbers below came from running the logic, with a game tree solver for the tic-tac-toe rules and a sweep of the real dictionary for the word game, so you can reproduce all of them.

The three repos at a glance

RepoStackWhat it isBug worth studying
tictactoeSwift, SwiftUIThree-piece tic-tac-toe against an AI, first to 3 round winsThe AI keeps moving after the round has ended
infinite-xoxVanilla JavaScript, 656 lines in script.jsThe same game for the browser, with a stronger AIThe AI counts a piece that is about to leave the board
pentawordsKotlin, Jetpack ComposeA seven-letter word puzzle with 16 stages and 8 translation languagesLater stages can ask for more words than the puzzle contains

The rule behind the first two: each player keeps at most 3 pieces. Place a fourth and your oldest one disappears. Three in a row wins the round. You can try the browser version at jerrypm.github.io/infinite-xox before reading the code.

1. tictactoe: the AI moves on a finished board

All of the game logic lives in ITTTGameViewModel.swift, which is 138 lines long. Here is the shape of makeMove, trimmed to the part that matters:

if checkWinner(symbol: symbol) {
    // score goes up, game over returns early
    DispatchQueue.main.asyncAfter(deadline: .now() + .onePointFive) {
        self.resetRound()
    }
} else {
    statusMessage = isHumanTurn ? SC.strAITurn : SC.strYourTurn
}

isHumanTurn.toggle()
if !isHumanTurn && !gameOver {
    DispatchQueue.main.asyncAfter(deadline: .now() + .pointFive) {
        self.aiMove()
    }
}

A round win only returns early when it also ends the match. For the first two wins, the code falls through to the turn toggle. So when you win a round, the AI gets scheduled half a second later and plays on a board that is already decided, a full second before the reset clears it. If that extra move happens to complete a line for O, the AI scores a point it should never have had, and a second reset goes into the queue. That second reset fires half a second after the first, which means it can wipe the opening move of the next round.

The reverse case exists too. When the AI wins a round, the toggle hands the turn to the human, and the tap handler in ITTTBoardView only checks that the cell is empty, that it is the human's turn and that the match isn't over. You get 1.5 seconds to tap on a dead board. The reset button has a similar gap, since nothing cancels a pending aiMove when you press it.

You rarely notice any of this by playing, because the window is short and your eyes are on the result message. The fix is to give the round an explicit ended state and keep one cancellable handle for delayed work:

@Published var isRoundOver = false
private var pendingWork: Task<Void, Never>?

private func schedule(after seconds: Double, _ work: @escaping @MainActor () -> Void) {
    pendingWork?.cancel()
    pendingWork = Task { @MainActor in
        try? await Task.sleep(for: .seconds(seconds))
        guard !Task.isCancelled else { return }
        work()
    }
}

Set isRoundOver = true on a win and return before the toggle, check it in the tap handler, and cancel pendingWork in both reset functions. Swift task cancellation is cooperative, which is why the guard sits after the sleep: as Apple's structured concurrency session explains, cancelling a task only sets a flag that your code has to check.

Two more things stand out in this repo. The README is an agent rules file, and it asks for async/await and value types while the view model is a class using DispatchQueue. A rules file only describes intent, and the code can drift from it on the first day. The home screen also fills its score history from ITTTMockData.gameResults, so the "last score" list shows hard-coded results dated from 2025. The test targets hold only Xcode's starter templates, which is why the turn bug never failed anything. Before an App Store submission that mock list would have to go, because Guideline 2.1(a) says "placeholder text, empty websites, and other temporary content should be scrubbed before submission."

The bug both versions share: ghost pieces

The Swift AI has three steps: win if it can, block if it must, otherwise play a random move. It looks for a block with this test, which runs over every winning line:

if count == .two && empty == .one {
    return combo[symbols.firstIndex(of: .empty)!]
}

Two of your pieces and one empty cell looks like a threat, and in normal tic-tac-toe it is one. In this variant, if you already have 3 pieces, your next move removes your oldest. When the oldest piece is one of the two in that line, the threat doesn't exist: filling the third cell makes the first one vanish. The AI spends its turn blocking a ghost.

To find out how often this happens, a port of each AI played 100,000 rounds against a random opponent that always moved first. Of the Swift AI's 199,672 blocks, 72,754 were ghost blocks, about 36%.

2. infinite-xox: a stronger AI with a worse version of the same bug

The JavaScript port adds a real strategy ladder in findBestAIMove: win, block, make a fork, stop a fork, take the center, take a corner. It's a clear step up in design, but this version moves its oldest piece instead of deleting it first, and it runs the search while the old piece is still on the board.

That matters for the winning move. The Swift version removes O's oldest piece before searching, so its winning move is real. The JavaScript version can pick a "winning" cell where one of the two supporting pieces is the piece being moved. In the same 100,000-round test, 33,810 of its 126,703 attempted wins were fake, about 27%. Another 17,067 of its 76,326 blocks were ghost blocks, about 22%.

The fix is short. Compute threats from the board as it will be after the move, for both sides:

// pieces = one player's cells, oldest first
function winningCells(pieces, emptyCells) {
  const afterMove = pieces.length === 3 ? pieces.slice(1) : pieces;
  return emptyCells.filter(cell =>
    winningCombinations.some(combo =>
      combo.every(i => i === cell || afterMove.includes(i))
    )
  );
}

A bot built on this check, with just center and corner preferences and no fork search at all, lost 1.3% of rounds to the same random opponent. The Swift AI lost 6.7% and the JavaScript AI lost 7.1%. So the extra ladder in the JavaScript version bought almost nothing, because the rule it needed was the one about the disappearing piece. When an AI feels dumb, check its model of the rules before you add more strategy on top.

Three smaller problems are worth a look in the same file:

  • resetRound has a comment that says it alternates who starts, but the logic gives you the pattern player, player, AI, AI, player. Setting this.isPlayerTurn = !this.playerStartedLastRound on every reset gives a true alternation.
  • When a player reaches 3 wins, handleRoundWin returns before updateScoreDisplay, so the header stays on 2 behind the game over modal. The modal itself shows the right score.
  • isDraw returns false on every path, and canAnyoneWin and removeOldestPiece are defined but never called. Those look like leftovers from an earlier design.

Three-piece tic-tac-toe has a forced win, and only from an edge

The always-false isDraw raises a fair question: can a round go on forever? To answer it, here is a small solver that walks every reachable position and works backward from the wins. A position stores each player's pieces in age order, because age decides what vanishes next. The move rule matches both repos: the target cell must be empty before the move, so you can't drop a piece onto your own oldest one.

from collections import deque, defaultdict
LINES = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
won = lambda q: any(all(c in q for c in l) for l in LINES)

def moves(state):
    x, o, turn = state
    me = x if turn == 0 else o
    for cell in set(range(9)) - set(x) - set(o):
        q = me[-2:] + (cell,) if len(me) == 3 else me + (cell,)
        yield q, ((q, o, 1) if turn == 0 else (x, q, 0))

start = ((), (), 0)
succ, pred, todo = {}, defaultdict(list), [start]
while todo:
    s = todo.pop()
    if s in succ: continue
    succ[s] = list(moves(s))
    for q, n in succ[s]:
        if not won(q):
            pred[n].append(s); todo.append(n)

value = {s: 1 for s in succ if any(won(q) for q, _ in succ[s])}
left = {s: len(succ[s]) for s in succ}
queue = deque(value)
while queue:
    s = queue.popleft()
    for p in pred[s]:
        if p in value: continue
        if value[s] == -1:
            value[p] = 1; queue.append(p)
        else:
            left[p] -= 1
            if left[p] == 0:
                value[p] = -1; queue.append(p)

print(len(succ), value.get(start))
for cell in range(9):
    print(cell, value.get(((cell,), (), 1), "draw"))

It finishes in seconds and reports 116,074 reachable positions that aren't already won. The first player can force a win within 13 plies in total (7 of their own moves), and the opening is the surprise. Starting on any of the 4 edge cells wins. Starting in the center or a corner, which is what normal tic-tac-toe teaches, only draws against perfect play, because the defender can repeat positions forever.

That has three practical consequences for this game:

  • Who starts matters more than it seems, so the pair pattern in resetRound changes how fair a match is. The Swift version always gives the human the first move.
  • A round really can run forever, and neither repo stops it. A simple rule is to call a draw the third time the same position appears, with the piece ages included in the comparison.
  • The solver's table can act as a perfect AI, or as a difficulty setting: take the best move some percentage of the time and a random move otherwise. That is far less code than a hand-written ladder, and it can't get the rules wrong.

3. pentawords: stages that can't be finished

PROGRESS.md calls this a Spelling Bee clone for Android. You get 7 letters in a honeycomb, every word must use the center letter, words need at least 4 letters, and a word using all 7 scores a 7-point bonus. On top of that it adds 16 stages with a 5-minute timer, and failing sends you back to stage 1. Every third stage swaps the word game for a number memory test. The other stages need a growing number of words, up to 11 on stage 16.

The architecture is tidy. Domain, data and presentation layers are separate, and WordValidator returns a sealed result that is pleasant to read. The problem sits between two clean pieces. StageConfig decides how many words a stage needs, and PuzzleGenerator.generatePuzzle() takes no parameters, so it has no idea what the stage needs. It picks a random 7-letter word, picks a random center letter, and returns whatever that gives. In stage mode the new puzzle button is replaced by the timer, so a player can't escape a thin puzzle.

The bundled words.txt has 1,611 words. Of those, 192 use exactly 7 distinct letters, which gives 1,344 possible word and center pairs. A sweep over all of them shows how uneven they are: the median puzzle has 8 valid words, the best (TRANSLATE with center E) has 42, and the worst, such as BUILDING with center G, has only 1. Assuming a uniform pick, here are the odds that a stage is impossible before the timer even starts:

StageWords requiredChance the puzzle has too few
223.3%
5413.3%
8626.3%
11843.3%
141058.2%
161165.4%

Stage 16 is unwinnable in about two of every three attempts, and the failure resets all progress. A player would just read it as a hard game, and a tester who stops at stage 5 would almost never see it. Even a puzzle with exactly 11 words at stage 16 would mean finding every word the dictionary allows in 5 minutes.

The fix is to pass the requirement in, and to build the puzzle by search:

fun generatePuzzle(minWords: Int = 1): Puzzle {
    for (pangram in findPangrams().shuffled()) {
        val letters = pangram.uppercase().toSet()
        for (center in letters.shuffled()) {
            val valid = findValidWords(center, letters)
            if (valid.size >= minWords) {
                return buildPuzzle(center, letters, valid)
            }
        }
    }
    return generateFallbackPuzzle()
}

Then add a test that loads the real dictionary and asserts the result for every stage. The current PuzzleGeneratorTest uses a 20-word test dictionary and has no idea stages exist. Be aware of what a generous margin costs here. Asking for twice the stage 16 requirement, 22 words, leaves only 96 of the 1,344 pairs. The dictionary is small, so growing it is the real long-term fix, and the translation files would have to grow with it.

A few more details are useful if you plan to study this repo: Claude Code Won't Clone Games Anymore: What Still Gets Your Game Rejected by Apple covers what else App Review checks in games.

  • The fallback puzzle lists its own valid words, but WordValidator only checks the dictionary, so a fallback word that isn't in words.txt would be rejected. Puzzle and validator should share one source of truth. With the current file the fallback never runs.
  • translations_vi.txt has 3,380 lines while the other seven files have 1,611. The extra entries do no harm, though they show the files were made by separate passes.
  • The rank list in GameState.kt uses the same ten names, in the same order, as the New York Times game, including Queen Bee at the top. I'd rename those before any public store release. On iOS, Guideline 4.1 covers copycats, and it tells developers to come up with their own ideas.

This repo also ships a CLAUDE.md, and it is a good example of what agent rules can and can't do. It sets a mandatory limit of 200 lines per file, yet four Kotlin files go past it, at 206, 248, 367 and 373 lines. It also requires a compile and a unit test run after each change. A check like that catches broken code, but it can't catch a design gap that no test describes. If you use a coding agent on a game, write the invariant down as a test, such as "every stage puzzle has enough words," because a test keeps failing until someone deals with it. Anthropic Tested How AI Agents Remember. Shrink and Fix Your Claude Code Memory in an iOS Repo looks at how agents treat files like that.

What re-running the code on a Mac showed

The code in this post was run again on macOS 26.0.1. The three repos were not cloned for this, so the 100,000-round simulations and the dictionary sweep above were not repeated. The solver and the fixes, which stand on their own, were.

The solver ran unchanged with the Python 3.9 that ships with macOS and with Python 3.12, in about 4 seconds each. Both printed 116074 1, then a -1 for the second player after each of the four edge openings (1, 3, 5 and 7) and draw after the center and the corners, which is the result described above. A short addition that records how many plies each solved position needs to reach a win reported 13 from the empty board and 12 after an edge opening, matching the 13 plies stated earlier.

The ghost-piece fix was run in Node 22.17.0. With X on cells 0, 1 and 4, cell 0 oldest, and O on 6 and 8, a check that ignores the disappearing piece reported two threat cells, 2 and 7. winningCells reported only 7, because moving to 2 removes the piece at 0 and breaks the line. With the same cells but 4 as the oldest piece, it reported only 2, and with just two X pieces on the board it agreed with the plain check.

The Swift scheduling fix was type-checked inside a small @MainActor view model with Xcode 26.2. It compiled in the Swift 5 and Swift 6 language modes for iOS 16 and 17 and failed for iOS 15 with 'sleep(for:tolerance:clock:)' is only available in iOS 16.0 or newer. If your app still supports iOS 15, try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000)) compiled there and does the same job.

The Kotlin puzzle fix was compiled with kotlinc 2.4.10 and run on Java 17, against a stub dictionary of eight words instead of the repo's words.txt. It returned a puzzle that met the requirement whenever one existed. Asked for 50 words, which no pangram in the stub could give, it quietly returned the fallback puzzle with one word. That is the same unwinnable stage in a new place, so have the stage code check the size of what comes back, or make the function return null so the stage code has to handle the miss, and keep the test that loads the real dictionary for every stage.

How to audit your own small game in one evening

These bugs have a common cause. Game logic has a huge state space, and a person only ever walks a thin path through it. The same steps would have caught all of them:

  1. Separate rules from the UI. Move the board, the turn logic and the win check into a type with no timers and no drawing code, so you can run it thousands of times in a loop. In infinite-xox that means pulling the rules out of the class that also writes to the DOM.
  2. Write down the invariants in plain language. Examples: no moves are accepted after a round ends, each player has at most 3 pieces, every stage can be completed.
  3. Run random games against those invariants. A random player finds timing and state bugs that a careful player steps around. Run 100,000 rounds and count anything odd.
  4. Sweep content instead of sampling it. If your game generates levels from a data file, loop over every combination and print the minimum, median and maximum. That is a ten-line script, and it found the stage bug here.
  5. Solve the game if you can. Under a few million states, a table of solved positions gives you a perfect opponent, a fairness check and a difficulty dial.
  6. Put every delayed action behind one cancellable handle, so that a reset cancels all of it. Most of the Swift bugs came from delayed closures that outlive the state they were meant for.
  7. Give your agent the invariants as tests. An agent can then generate the fuzz loop and the sweep for you, and it has something concrete to fail against.

To run the repos yourself, clone them from GitHub. For the browser game, run python3 -m http.server 8000 in its folder, as its README suggests. For pentawords, run ./gradlew testDebugUnitTest, the command its CLAUDE.md lists. Open tictactoe in Xcode through InfiniteTicTacToe.xcodeproj. A good exercise is to apply one fix from this post, then write the test that would have caught the bug before it.

If you want the same game on Android, the Infinite Tic-Tac-Toe Android App - Complete Kotlin Source Code with AdMob is on Gumroad at a name-your-price listing starting from $0. Its product page lists 2,555 lines of Kotlin in 23 files, MVVM with StateFlow, Jetpack Compose with Material 3, a 7-level AI with fork detection, solo and two-player modes, and AdMob banner ads. It was not part of the checks above, so the ghost piece test is a good first thing to try on it.

Sources