任务目标:让Karel把房间里的所有beeper清理干净。
逐步求精分解思路:
1.清理当前行
2.移动到下一行
3.清理当前行
4.重复
# 高层次伪代码 def main(): 清理当前行 while 左侧有路: 移动到下一行 清理当前行 # 细化每一步 def main(): 清理当前行 while 左侧有路: 移动到下一行并向西 清理当前行 if 右侧有路: 移动到下一行并向东 清理当前行 else: 转身 # 进一步细化为具体函数 def main(): clean_current_row() while left_is_clear(): reposition_for_row_to_west() clean_current_row() if right_is_clear(): reposition_for_row_to_east() clean_current_row() else: turn_around() # 细化子任务:清理当前行 def clean_current_row(): while front_is_clear(): if beepers_present(): pick_beeper() else: move() # 仿照栅栏柱错误: if beepers_present(): pick_beeper() # 细化子任务:移动到下一行并向西 def reposition_for_row_to_west(): turn_left() move() turn_left() # 细化子任务:移动到下一行并向东 def reposition_for_row_to_east(): turn_right() move() turn_right() # 细化子任务:向右转 def turn_right(): for i in range(3): turn_left() # 细化子任务:向后转 def turn_around(): turn_left() turn_left()
下面是清理房间任务的完整实现示例:
def main(): clear_to_line_of_beepers() while left_is_clear(): move_to_west_line() clear_to_line_of_beepers() if right_is_clear(): move_to_east_line() clear_to_line_of_beepers() else: turn_around() def clear_to_line_of_beepers(): while front_is_clear(): if beepers_present(): pick_beeper() else: move() if beepers_present(): pick_beeper() def move_to_west_line(): if left_is_clear(): turn_left() move() turn_left() def move_to_east_line(): if right_is_clear(): turn_right() move() turn_right() def turn_right(): for i in range(3): turn_left() def turn_around(): turn_left() turn_left()