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