Python if-elif语句命令

Rom*_*tas 1 python random if-statement

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

情况是:有一个球员可以移动 - 让我们说向上.移动时,他可能遇到一些障碍 - 让我们说树木.他可以使用像这样的非常简单的算法绕过它们:

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()
Run Code Online (Sandbox Code Playgroud)

嗯,它的效果非常好,但是有一个缺点:如果障碍物从右侧和左侧都有免费的瓷砖,那么它可以从两侧绕过,玩家总是从右侧绕过它.它几乎可以解释,但仍然不那么酷.

想法是添加一些变化并以某种方式随机化玩家检查瓦片可用性的顺序,因此如果两者都是空闲的,他可以不一定向右移动,而是随机移动.而且我必须承认,我无法想出如何以简单而美丽的方式做到这一点.

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

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()
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 5

您可以将所有可用路线放在列表中,然后使用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
Run Code Online (Sandbox Code Playgroud)

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

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

try:
    # pick an available direction at random
    random.choice(directions)()
except IndexError:
    # no directions available
    stop()
Run Code Online (Sandbox Code Playgroud)