Living Museum of Learning

Where real moments become exhibits
← Prev Next →
The Chess Piece That Sometimes Refused to Die

The Chess Piece That Sometimes Refused to Die

Tianjing vs. the Most Stubborn Bug in Chinese Chess

Situation

There were only two pieces on the Chinese chessboard: one black Che and one red Che.

The black Che tried to capture the red Che. The rules were simple. The move was legal. There was nowhere for the bug to hide.

Except that sometimes the capture worked, and sometimes it didn't.

Tianjing relaunched the program and tried again. And again. And again.

At least 100 times.

The same board. The same move. Different results.

LOL.

Turning Point

The mystery wasn't in how a Che moves. It was in the order of operations.

The program removed the moving piece from the pieces set, created a new piece at the destination, and inserted it into the set. Only then did it look for the piece at the destination to decide whether a capture had occurred.

For a brief moment, both pieces occupied the same coordinates.

The program then asked pieceAt() to find the piece at that location. But pieces was a Set, and its iteration order was not guaranteed. The lookup could find the newly inserted black Che instead of the original red Che.

If it found the red Che, the capture succeeded.

If it found the black Che, nothing happened to the red Che.

The computer wasn't being mysterious. Our program had created an ambiguous situation and then trusted an arbitrary lookup to resolve it.

Emergence

The solution was to identify the destination piece before moving anything.

First, remember the piece being captured. Then remove the moving piece, remove the captured piece, and finally insert the moving piece at its destination.

No overlapping pieces. No ambiguous lookup. No more ghostly red Che surviving its own capture.

Learning

Tianjing's 100 experiments taught us something important about debugging:

A bug that appears random is not necessarily random.

Sometimes the rules are correct, but the sequence of operations is wrong. Sometimes the state of a program becomes temporarily inconsistent, and a later lookup exposes the mistake.

And sometimes, finding the bug requires a student to be more persistent than the bug itself.

The computer repeated its mistake. Tianjing repeated the experiment. Eventually, the experiment won.

Theme

Debugging · Experimental Science · State and Identity · Persistence

Can you construct a test that reproduces the bug?

Why is it dangerous to look up an object after changing the collection that contains it?

How can we write a unit test to verify that a capture always leaves exactly one piece at the destination?