Python if-elif statements order -


i've encountered problem seems pretty basic , simple , can't figure out proper , elegant way how solve it.

the situation is: there's player can move - let's upward. while moving can encounter obstacles - let's trees. , can bypass them using pretty simple algorithm one:

if   <the obstacle has free tile on right>:   move_right()  elif <the obstacle has free tile on left>:   move_left() else:   stop() 

well, works perfectly, there's drawback: if obstacle has free tiles both right , left can bypassed both sides, player bypasses right. it's pretty explainable, still not cool.

the idea add variety , randomize somehow order in player checks availability of tiles if both free move not right, in random direction. , must admit cannot come idea how in simple , beautiful way.

basically, solution should this...

if random(0, 1) == 0:   if   <the obstacle has free tile on right>:     move_right()    elif <the obstacle has free tile on left>:     move_left()   else:     stop() else:   if   <the obstacle has free tile on left>:     move_left()   elif <the obstacle has free tile on right>:     move_right()    else:     stop() 

but guess don't need explain why doesn't seem best one. =/

you can put available directions in list, use random.choice() on that:

directions = [] if <the obstacle has free tile on right>:     directions.append(move_right) if <the obstacle has free tile on left>:     directions.append(move_left)  if not directions:     stop() else:     random.choice(directions)()  # pick available direction @ random 

the directions list have either 0, 1 or 2 function references in it; if empty, there no options , call stop(), otherwise randomly pick list , call picked function.

because random.choice() raises indexerror if input list empty, make use tof too:

try:     # pick available direction @ random     random.choice(directions)() except indexerror:     # no directions available     stop() 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -