python中的elif语句怎么运行_Python if-elif语句命令

I've encountered a problem that seems pretty much basic and simple and however I can't figure out a proper and elegant way how to solve it.

The situation is: there's a player who can move - let's say upward. While moving he can encounter some obstacles - let's say trees. And he can bypass them using a pretty simple algorithm like this one:

if :

move_right()

elif :

move_left()

else:

stop()

Well, it works perfectly, but there's a drawback: if the obstacle has free tiles both from its right and left so it can be bypassed from the both sides, the player always bypasses it from the right. It's pretty much explainable, but still not that cool.

The idea is to add some variety and randomize somehow the order in which the player checks the availability of tiles so if both are free he could move not necessarily to the right, but in random direction. And I must admit I cannot come up with an idea how to do it in a simple and beautiful way.

Basically, the solution should probably be something like this...

if random(0, 1) == 0:

if :

move_right()

elif :

move_left()

else:

stop()

else:

if :

move_left()

elif :

move_right()

else:

stop()

but I guess I don't need to explain why it doesn't seem the best one. =/

解决方案

You can put all available directions in a list, then use random.choice() on that:

directions = []

if :

directions.append(move_right)

if :

directions.append(move_left)

if not directions:

stop()

else:

random.choice(directions)() # pick an available direction at random

The directions list will then have either 0, 1 or 2 function references in it; if it is empty, there were no options and you call stop(), otherwise you randomly pick from the list and call the picked function.

Because random.choice() raises IndexError if the input list is empty, you could make use tof that too:

try:

# pick an available direction at random

random.choice(directions)()

except IndexError:

# no directions available

stop()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值