Skip to content

Instantly share code, notes, and snippets.

@AlexeyMK
Created September 25, 2011 01:41
Show Gist options
  • Save AlexeyMK/1240101 to your computer and use it in GitHub Desktop.
Save AlexeyMK/1240101 to your computer and use it in GitHub Desktop.
Strategy Decorator for Ants AI challenge
### possible_moves = ['e':0, 'n':0, 'w':0, 's':0, 'halt':0]
### extra = {} # pass info to others if needed
class Strategies:
INITIAL_MOVES = dict([(m, 0) for m in AIM.keys()])
@classmethod
def best_option(cls, moves):
return max(list(moves.keys()), key=lambda d: moves[d])
def __init__(self, pre=[], post=[], wrap=[]): #each is a list
self.pre_strats = pre
self.post_strats = post
def __call__(self, main_strat):
that=self
def run_this_instead(self, ant, possible_moves, extra=None):
def apply_strat(moves_and_extra, strat):
return strat(ant, moves_and_extra[0], moves_and_extra[1])
#apply each pre decorator
pre_moves = reduce(apply_strat, that.pre_strats, (possible_moves, extra))
#run the main strategy
main_moves = main_strat(self, ant, pre_moves, extra)
#apply each post decorator
post_moves = reduce(apply_strat, that.post_strats, (main_moves, extra))
return post_moves[0] # no need for 'extra'
return run_this_instead
#what a 'strategy' actually looks like
def remove_water(ant, possible_moves, extra):
return dict([(move, possible_moves[move]) for move in possible_moves.keys() \
if ant.world.passable(ant.world.next_position(ant.location, move))])
class GreedyBot(AntsBot):
#Greedy bot with a strategy appended to it that removes water.
@Strategies(pre=[remove_water])
def rank_directions(self, ant, possible_moves, extra=None):
'''Finds a direction for this ant to move in according to the food, enemy, exploration routine.'''
# Get the list of directions towards food, enemy, and random
rand_dirs = possible_moves.keys()
random.shuffle(rand_dirs)
dirs = (ant.toward(ant.closest_food()) + ant.toward(ant.closest_enemy()) + rand_dirs)
# Get the first passable direction from that long list.
d = ant.get_passable_direction(dirs)
possible_moves[d] = 1
return possible_moves #it's saying - go make that move, I like that one
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment