The simplest cacti sort

At the last moment I got a request to write the smallest possible program which sorts cacti in The Farmer Was Replaced game.

Here is my version:

n = 8
set_world_size(n)

disorder_detected = True
while(disorder_detected):
  disorder_detected = False
  for y in range(n):
    for x in range(n):
      if get_entity_type() != Entities.Cactus:
        if get_ground_type() != Grounds.Soil:
          till()
        if plant(Entities.Cactus):
          disorder_detected = True
      if measure() != None and measure(East) != None and measure() > measure(East):
        if swap(East):
          disorder_detected = True
      if measure() != None and measure(North) != None and measure() > measure(North):
        if swap(North):
          disorder_detected = True
      move(East)
    move(North)
harvest()

Let's work through this solution:

n = 8
set_world_size(n)

Here I both set the world size to 8 and introduce a new variable n for the world size.

Let's check an interesting idiom:

disorder_detected = True
while(disorder_detected):
  disorder_detected = False
  ...
  if plant(Entities.Cactus):
          disorder_detected = True
  if swap(East):
          disorder_detected = True

I introduce the flag disorder_detected and put this flag up before the loop. This way the loop will be executed at least once. Then, at the beginning of the loop, I put it down. It means that if there are no disorders, the field is ready for harvest. Disorders are: absence of cactus, or cacti in the wrong order.

Navigation is very simple. I have two nested loops. The inner loop moves the drone horizontally from left to right. The outer loop moves it vertically. The map is toroidal, therefore the drone appears on the left after crossing the right boundary; similarly, it appears at the bottom after crossing the upper boundary.

  if get_entity_type() != Entities.Cactus:
      if get_ground_type() != Grounds.Soil:
        till()
      if plant(Entities.Cactus):
        disorder_detected = True

When we start the script, the field is empty. So we plant cactus on empty cell and count it as a disorder. Cactus requires Soil, we ensure it with till().

And finally, the main thing:

if measure() != None and measure(East) != None and measure() > measure(East):
  if swap(East):
    disorder_detected = True
if measure() != None and measure(North) != None and measure() > measure(North):
  if swap(North):
    disorder_detected = True

If our current cactus is higher than its neighbor to the right or above, we swap them. This way each pass of the drone brings more order into the field, and one day the field becomes sorted. On a sorted field no swaps occur, therefore no disorder is detected and the while loop ends.

The drone stops at the left bottom end of the field, and we can call harvest() function, which picks up all cacti with a big bonus.