常用代码片段
约 562 字大约 2 分钟
2026-09-23
移动与遍历
蛇形遍历
def move_to(pos_x, pos_y):
while get_pos_x() < pos_x:
move(East)
while get_pos_x() > pos_x:
move(West)
while get_pos_y() < pos_y:
move(North)
while get_pos_y() > pos_y:
move(South)
def visit_snake(size, callback):
for y in range(size):
for x in range(size):
if y % 2 == 0:
move_to(x, y)
else:
move_to(size - 1 - x, y)
callback()农场边界会环绕,move_to() 适合已知目标坐标且距离不大的分区,不要用它跨越整张农场反复绕圈
种植与收获
整地、浇水、种植
def prepare(entity):
if get_ground_type() != Grounds.Soil:
till()
if get_water() < 0.5:
use_item(Items.Water)
return plant(entity)plant() 返回 False 时优先检查地面、背包资源和脚下是否已有实体
成熟后收获
def harvest_if_ready(replant=None):
if can_harvest():
harvest()
if replant is not None:
plant(replant)不确定脚下是什么时先用 get_entity_type(),不要直接 harvest(),因为对不可收获实体调用可能会把它清掉
测量与排序
按实体读取测量值
entity = get_entity_type()
value = measure()
if entity == Entities.Sunflower:
petals = value
elif entity == Entities.Cactus:
cactus_size = value
elif entity == Entities.Treasure:
next_x, next_y = valuemeasure() 对不同实体返回不同类型,其他实体通常返回 None
仙人掌相邻交换
if measure() > measure(East):
swap(East)只能和相邻位置交换,完整排序需要多轮扫描
资源检查
检查资源是否够用
def has_cost(thing):
cost = get_cost(thing)
for item in cost:
if num_items(item) < cost[item]:
return False
return True自动购买解锁
def unlock_if_ready(thing):
if num_unlocked(thing) == 0 and has_cost(thing):
return unlock(thing)
return False多无人机
等待子无人机
def worker():
for _ in range(get_world_size()):
if can_harvest():
harvest()
move(East)
drone = spawn_drone(worker)
if drone is not None:
result = wait_for(drone)spawn_drone() 可能因为达到上限返回 None,不要无条件调用 wait_for(None)
让无人机分区
def work_region(start_x, start_y, width, height):
move_to(start_x, start_y)
for y in range(height):
for x in range(width):
prepare(Entities.Carrot)
if x < width - 1:
move(East)
if y < height - 1:
move(North)
if y % 2 == 0:
move_to(start_x + width - 1, get_pos_y())
else:
move_to(start_x, get_pos_y())实际使用时给每个无人机分配不重叠的区域,区域之间留一格通常更容易调试
计时与调试
start_tick = get_tick_count()
start_time = get_time()
run_task()
quick_print("ticks:", get_tick_count() - start_tick)
quick_print("time:", get_time() - start_time)查询类操作和成功移动的耗时不同,优化时同时记录 tick 和实际时间
