繁体   English   中英

Python if-elif语句顺序

[英]Python if-elif statements order

我遇到了一个看起来很基本和简单的问题,但是我找不到解决该问题的合适而优雅的方法。

情况是:有一个球员可以移动-假设是向上移动。 他在移动时会遇到一些障碍-假设是树木。 而且他可以使用一种非常简单的算法绕过它们,例如:

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()

但是我想我不需要解释为什么它似乎不是最好的。 = /

您可以将所有可用的路线放在列表中,然后在上面使用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 ,因此您也可以使用它:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM