The Farmer, Chicken, Fox and Corn Puzzle

I saw this puzzle on

and decided it would be quick and easy on AI2, no hardware.

The rules:

The farmer has a chicken, a fox and a basket of corn. He has to get them all across the river but he can only take one item at a time. See if you can have him do this without the chicken eating the corn or the fox eating the chicken while the farmer leaves them unattended.

Sample run:

sample run
It's just two banks of 4 Buttons, across a River Label.

Clicking an object on the same side as the farmer moves the farmer and the object.
Clicking the farmer alone just moves the farmer.

The Designer:

The initial position has everything on the left bank (bank 0):

The Button components are all in the same list, lined up so the button at slot n is opposite slot n+4.

This list of 8 text values is used to fill the 8 buttons at reset time.

The reset button refills the 8 buttons from the starting positions, and sets them all enabled.
Because the lists of buttons and text had to be traversed together, the For each N from 1 to 8 loop had to be used, instead of the For Each Item in List loop.

when  btnReset .Click do

when  Screen1 .Initialize do

Button Click Logic:

This a generic Click handler, so we need to exclude other buttons like the Reset button, using the notAlreadyHandled test.

We get a local variable to hold the Text of the button just pressed, and call it selection.
That saves us from having to repeat that code later in this event.
If the Farmer was clicked, then he always moves across the river using the move procedure.

If another button was clicked and it is non-blank and on the same bank of the river as the farmer, we have the farmer move that object across the river.

Then we call the check_damage procedure to check for the results.

Moving an object:

This is where value procedures come in handy to simplify logic.
The slot procedure returns the index (1-8) of the button holding the given (nonblank) text value.
We move from slot1 (just calculated) to slot2, the opposing slot on the opposite side of the river. Because there are 4 buttons on each side of the river, each slot is 4 steps away from its opposite slot.
The actual move is just a pair of Text replacements in the two opposing buttons.

Slot calculation:

This is a good use case for the advanced list functions. The inner list is a list of the Text values of the 8 buttons.

bank (0-1) calculation:

This where lining up the buttons in a single list pays off.
(I tested the round function independently against 1/8, 2/8 ... 7/8, 8/8 just to be sure it would give me 4 0's and 4 1's.)

Judging a move result:

The first test is to see if the chicken is alone with the corn.
The second test is to see if the fox is alone with the chicken
The third test is to see if all 4 objects are on bank 1 (the right side of the river.)

Finally, the game_over procedure:

farmer_chicken_fox_corn.aia (6.5 KB)

All blocks: