精通仙人掌自动化:二维冒泡排序
仙人掌种植非常独特,因为按大小排序可以获得更好的奖励或满足关卡要求。本指南将解释如何将经典的“冒泡排序”算法应用到你的农场网格中。
核心策略
与其他作物不同,仅仅收获仙人掌是不够的。我们需要测量它们的大小,并不断交换它们的位置,直到它们被完美地排列。
- 测量 (Measure): 比较当前位置与相邻位置(右侧和下方)的仙人掌大小。
- 交换 (Swap): 如果当前仙人掌比邻居大,则交换位置。
- 重复 (Repeat): 在整个网格上重复此过程,直到没有需要交换的为止。
代码分步解析
Step 1 智能导航与方向控制
在排序之前,我们需要一些辅助函数来帮助无人机回到原点 (`back`) 以及处理方向的反转 (`reverse`)。
python
def back(x=0,y=0):
while x!=get_pos_x() or y!=get_pos_y():
if(get_pos_x()<x):
move(East)
else:
move(West)
if(get_pos_y()<y):
move(North)
else:
move(South)
def reverse(dir):
if(dir == West): return East
if(dir == East): return West
if(dir == North): return South
if(dir == South): return North Step 2 核心排序逻辑 (Bubble Sort)
这是代码的大脑部分。它不仅检查水平方向 (`East`/`West`),还检查垂直方向 (`North`/`South`)。如果发现顺序错误,就调用 `swap()`。
python
# ... inside the loop
current=measure()
neighbor=measure(dir)
down=measure(South)
up=measure(North)
# Swap Horizontal (水平交换)
if(x!=size-1 and neighbor!=None and dir==East and current>neighbor):
swap(East)
sorted=False # Mark as not fully sorted yet
# Swap Vertical (垂直交换)
if(y!=0 and down != None and current<down):
swap(South)
vsorted=False 完整源代码
Pythonpython
def back(x=0,y=0):
while x!=get_pos_x() or y!=get_pos_y():
if(get_pos_x()<x):
move(East)
else:
move(West)
if(get_pos_y()<y):
move(North)
else:
move(South)
def plantCactus():
if get_ground_type()==Grounds.Grassland:
till()
plant(Entities.Cactus)
def reverse(dir):
if(dir == West): return East
if(dir == East): return West
if(dir == North): return South
if(dir == South): return North
def cactusProject(size=3):
while True:
dir=East
vdir=North
sorted=False
vsorted=False
# 1. Planting Phase
for i in range(size):
for j in range(size):
plantCactus()
if(j!=size-1):
move(dir)
if(i!=size-1):
move(vdir)
dir=reverse(dir)
vdir=reverse(vdir)
# 2. Sorting Phase
while not sorted or not vsorted:
sorted=True
vsorted=True
for i in range(size):
for j in range(size):
x=get_pos_x()
y=get_pos_y()
current=measure()
neighbor=measure(dir)
down=measure(South)
up=measure(North)
# Logic to swap East/West
if(x!=size-1 and neighbor!=None and dir==East and current>neighbor):
swap(East)
sorted=False
if(x!=0 and neighbor!=None and dir==West and current<neighbor):
swap(West)
sorted=False
# Logic to swap North/South
if(y!=0 and down != None and current<down):
swap(South)
vsorted=False
if(y!=size-1 and up != None and current>up):
swap(North)
vsorted=False
if(j!=size-1):
move(dir)
if(i!=size-1):
move(vdir)
dir=reverse(dir)
# 3. Harvesting Phase (Once sorted)
back()
harvest()
clear()
# Change '6' to your grid size
cactusProject(6) 优化建议
- • 确保传入 `cactusProject(size)` 的 size 参数与你的土地大小一致,否则无人机会撞墙。
- • 这个算法在大型网格(如 10x10)上可能会变慢,这是冒泡排序的特性。