Left hand rule in The Farmer Was Replaced
When I first solved the TFWR maze, I reached for DFS without thinking. But when I tried to explain the game to a less seasoned programmer, I realized DFS quietly assumes you’re comfortable with recursion, sets, visited states… not exactly “fun-first”.
So I finally focused on the classic left-hand maze traversal that TFWR guides keep mentioning. And for the first time in my life, I actually coded it.
The four situations (picture 1)
The idea is simple: keep your left hand touching the wall.
➜Wall on the left, open ahead → go forward.
☛Left and forward blocked, right open → turn right.
➽Everything except backward blocked → turn back.
➳The weird one: no wall on the left → you just moved forward and discovered an opening on the left. To “restore contact” with the wall, turn left and step into that passage.
Now the nice part: all four cases collapse into one tiny routine:
ᐉTurn left once, then while forward is blocked, turn right.
That’s it.
Let's consider tools for this task.
d = [East, North, West, South]
Directions from zero point, counterclockwise. Don't use one-letter names in production, please.
dc = 0
dc = (dc + 1) % 4
dc = (dc - 1) % 4
Our initial direction - East. +1 - counterclockwise, -1 - clockwise. God bless Guido van Rossum - % 4 always gives numbers from 0 to 3 inclusive. In C++ it would be slightly less straightforward.
All together now
d = [East, North, West, South]
# black magic to conjure the maze
plant(Entities.Bush)
substance = get_world_size() * 2**(num_unlocked(Unlocks.Mazes) - 1)
use_item(Items.Weird_Substance, substance)
dc = 0
while get_entity_type() != Entities.Treasure:
dc = (dc + 1) % 4
while not can_move(d[dc]):
dc = (dc - 1) % 4
move(d[dc])
harvest()

