基于用户输入的迷宫运动顺序

2024-05-18 11:16:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用堆栈解决maze问题,其中每个移动都存储在moves变量中。为了解决这个问题,我需要任意决定从当前位置检查四个方向的可用性的顺序。一种可能的顺序是1)向上、2)向下、3)向左和4)向右。对于不同的移动模式,应该相应地交换if语句

有没有一种更优雅的方法可以做到这一点,可以定义order_of_movement变量和not交换if语句

order_of_movement = ['UP', 'DOWN', 'LEFT', 'RIGHT'] #how such a movement list could be used?

if(not moved and validWay[UP]):
    moved, completed, moves = move_up(moves, maze, end)

if(not moved and validWay[DOWN]):
    moved, completed, moves = move_down(moves, maze, end)

if(not moved and validWay[LEFT]):
    moved, completed, moves = move_left(moves, maze, end)

if(not moved and validWay[RIGHT]):
    moved, completed, moves = move_right(moves, maze, end)

Tags: andofmoveif顺序notorder语句
1条回答
网友
1楼 · 发布于 2024-05-18 11:16:34

由于您澄清了move_up/down/left/right函数可以是泛型的,因此解决方案的外观如下:

for direction in order_of_movement:
    if(not moved and validWay[direction]):
        moved, completed, moves = move_direction(moves, maze, end, direction)

这是假设您在新的泛型move_direction函数中添加了第四个参数direction

我在对字典的评论中的意思是,如果您想将所有移动函数分开,可以定义函数方向的映射,如下所示:

order_of_movement = {
    'UP': move_up,
    'DOWN': move_down,
    'LEFT': move_left,
    'RIGHT': move_right
}

for direction in order_of_movement.keys():
    if(not moved and validWay[direction]):
        moved, completed, moves = order_of_movement[direction](moves, maze, end)

因为每个方向都映射到一个函数,这意味着order_of_movement[direction]将为您提供适当的函数,因此您只需通过在末尾添加括号中的参数来调用它

相关问题 更多 >