【问题标题】:Python if-elif statements orderPython if-elif 语句顺序
【发布时间】:2015-01-16 19:43:29
【问题描述】:

我遇到了一个看起来非常基本和简单的问题,但是我无法找到一种适当而优雅的方法来解决它。

情况是:有一个可以移动的玩家——比如说向上。在移动时,他可能会遇到一些障碍——比如说树木。他可以使用像这样的非常简单的算法绕过它们:

if   <the obstacle has a free tile on its RIGHT>:
  move_right() 
elif <the obstacle has a free tile on its LEFT>:
  move_left()
else:
  stop()

嗯,它工作得很好,但有一个缺点:如果障碍物的左右两侧都有空闲的瓷砖,因此可以从两侧绕过它,玩家总是从右侧绕过它。这几乎可以解释,但仍然不是那么酷。

这个想法是增加一些变化并以某种方式随机化玩家检查瓷砖可用性的顺序,因此如果两者都是空闲的,他不一定可以向右移动,而是随机移动。而且我必须承认,我无法想出如何以一种简单而优美的方式来完成它。

基本上,解决方案应该是这样的......

if random(0, 1) == 0:
  if   <the obstacle has a free tile on its RIGHT>:
    move_right() 
  elif <the obstacle has a free tile on its LEFT>:
    move_left()
  else:
    stop()
else:
  if   <the obstacle has a free tile on its LEFT>:
    move_left()
  elif <the obstacle has a free tile on its RIGHT>:
    move_right() 
  else:
    stop()

但我想我不需要解释为什么它看起来不是最好的。 =/

【问题讨论】:

    标签: python if-statement random


    【解决方案1】:

    您可以将所有可用的路线放在一个列表中,然后在上面使用random.choice()

    directions = []
    if <the obstacle has a free tile on its RIGHT>:
        directions.append(move_right)
    if <the obstacle has a free tile on its LEFT>:
        directions.append(move_left)
    
    if not directions:
        stop()
    else:
        random.choice(directions)()  # pick an available direction at random
    

    方向列表中将包含 0、1 或 2 个函数引用;如果它为空,则没有选项,您调用stop(),否则您从列表中随机选择并调用选择的函数。

    因为如果输入列表为空,random.choice() 会引发 IndexError,因此您也可以使用 tof:

    try:
        # pick an available direction at random
        random.choice(directions)()
    except IndexError:
        # no directions available
        stop()
    

    【讨论】:

    • 看起来不错。但是,如果我们让事情变得更复杂一点呢?假设没有像move_right()move_left()这样的方法,而是像self.X += stepself.X -= step这样的简单操作。
    • @Romitas:你可以添加lambda函数来代替;例如将表达式包装在一个匿名函数中:directions.append(lambda: setattr(self, 'X', self.X + self.step)) # move right(使用setattr(),因为您不能在lambda 中使用语句)或者只是为运动创建方法或本地嵌套函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多