Exemplo n.º 1
0
 def __init__(self, url, pid, policy, interval=2, log=None):
     self.policy = policy
     self.log = log or get_logger(__file__, "policy_client.log")
     self.interval = interval
     self.pid = pid
     self.api = TreasureApi(url=url, pid=pid)
     self.games = []
    def __init__(self, url, pid):
        "Creates a new instance of the api we can use, and starts a new game."

        self.api = TreasureApi(url=url, pid=pid)
        self.api.new_game()
        self.api.set_autoplay()
        while self.api.game['status'] != 'complete':
            self.render()
            move = self.ask_player_to_choose_move()
            self.api.play_move(move)
        self.conclude_game()
Exemplo n.º 3
0
 def __init_api(self):
     print "init", args
     while True:
         try:
             # print "self", self.pid
             # print "self", self.name
             self.api = TreasureApi(url=self.url,
                                    pid=self.pid,
                                    name=self.name)
             if hasattr(self.api, 'error'):
                 print self.api.error[
                     'error'] + ": the player probably already exists"
                 self.setup_player()
             else:
                 # print("here")
                 break
         except ValueError:
             self.setup_player()
Exemplo n.º 4
0
class TreasurePolicyClient:
    def __init__(self, url, pid, policy, interval=2, log=None):
        self.policy = policy
        self.log = log or get_logger(__file__, "policy_client.log")
        self.interval = interval
        self.pid = pid
        self.api = TreasureApi(url=url, pid=pid)
        self.games = []

    def play_open_games(self):
        """
        Automatically plays whenever it can, on all open games. Aditionally makes sure 
        there is always one game waiting to start, so that others can join.
        """
        while True:
            self.play_all_possible_turns()
            sleep(self.interval)

    def play_all_games(self):
        """
        Joins every available game and plays whenever possible.
        """
        while True: 
            while self.api.join_any_game():
                self.log.info("Joined game {}".format(self.api.game['gid']))
            self.play_all_possible_turns()
            sleep(self.interval)

    def play_all_possible_turns(self):
        profile = self.api.get_player()
        if not any(profile['games_waiting']):
            self.api.new_game()
            self.log.info("Created game {}".format(self.api.game['gid']))
        for gid in profile['games_playing']:
            game = self.api.get_game(gid=gid)
            choice = self.policy(game, self.api.player['name'])
            self.log.info("Playing {} in game {}".format(choice, gid))
            self.api.play_move(choice)
class TreasureAutoplayClient:
    "A class which autoplays a treasure game"

    def __init__(self, url, pid):
        "Creates a new instance of the api we can use, and starts a new game."

        self.api = TreasureApi(url=url, pid=pid)
        self.api.new_game()
        self.api.set_autoplay()
        while self.api.game['status'] != 'complete':
            self.render()
            move = self.ask_player_to_choose_move()
            self.api.play_move(move)
        self.conclude_game()

    def render(self):
        "Presents a game state. (The api serves as our model, holding the game state.)"

        if len(self.api.game['turns']) > 1:
            print("LAST TURN I PLAYED {} AND {} PLAYED {}.".format(
                self.my_last_play(), self.your_name(), self.your_last_play()))
            print("THE SCORE IS {} (ME) to {} ({})".format(
                self.my_score(), self.your_score(), self.your_name()))
        print("THE TREASURE IS {}.".format(self.treasure()))
        print("THE CARDS IN MY HAND ARE {}.".format(", ".join(
            str(card) for card in self.my_hand())))

    def ask_player_to_choose_move(self):
        "Asks the player to choose a legal move, and then returns it."

        while True:
            choice = input("PLEASE CHOOSE A MOVE: ")
            if choice.isdigit() and int(choice) in self.my_hand():
                return int(choice)
            print("YOU DON'T HAVE THAT CARD. TRY AGAIN.")

    def conclude_game(self):
        "Wraps up the game"
        print("THE FINAL SCORE WAS {} (ME) TO {} ({})".format(
            self.my_score(), self.your_score(), self.your_name()))
        if self.my_score() > self.your_score():
            print("YAY! I WIN.")
        elif self.my_score() < self.your_score():
            print("ALAS. I LOST.")
        else:
            print("WEIRD. WE TIED.")

    # Helpers. These just make the job a little easier.

    def my_name(self):
        return self.api.player['name']

    def your_name(self):
        return self.api.opponent_name()

    def treasure(self):
        return self.api.game['turns'][0]['treasure']

    def my_score(self):
        return self.api.game['players'][self.my_name()]['score']

    def your_score(self):
        return self.api.game['players'][self.your_name()]['score']

    def my_hand(self):
        return self.api.game['players'][self.my_name()]['hand']

    def your_hand(self):
        return self.api.game['players'][self.your_name()]['hand']

    def my_last_play(self):
        if self.api.game['status'] == 'playing':
            return self.api.game['turns'][1][self.my_name()]
        if self.api.game['status'] == 'complete':
            return self.api.game['turns'][0][self.my_name()]

    def your_last_play(self):
        if self.api.game['status'] == 'playing':
            return self.api.game['turns'][1][self.your_name()]
        if self.api.game['status'] == 'complete':
            return self.api.game['turns'][0][self.your_name()]
Exemplo n.º 6
0
 def __init__(self, url=None, pid=None, name=None, gid=None):
     self.api = TreasureApi(url=args.url, pid=args.pid, name=args.name)
     if gid and gid in api.player['games_playing']:
         self.api.get_game(gid=gid)
     else:
         self.select_game()
Exemplo n.º 7
0
class TreasureClient:
    def __init__(self, url=None, pid=None, name=None, gid=None):
        self.api = TreasureApi(url=args.url, pid=args.pid, name=args.name)
        if gid and gid in api.player['games_playing']:
            self.api.get_game(gid=gid)
        else:
            self.select_game()

    def select_game(self):
        print("How would you like to join a game?")
        while not self.prompt_choices(
            [('n', 'new game', self.new_game),
             ('r', 'resume an ongoing game', self.api.resume_game),
             ('j', 'join any game', self.api.join_any_game),
             ('s', 'join a specific game', self.join_game)]):
            print("Sorry, that didn't work. Please choose an option:")

        print("Playing game {} against {}".format(self.api.game['gid'],
                                                  self.api.opponent_name()))
        self.play_turn()

    def new_game(self):
        self.api.new_game()
        return self.wait_for_game_to_start()

    def wait_for_game_to_start(self):
        self.api.get_game()
        if self.api.game['status'] == 'playing':
            return True
        print("Waiting for another player to join.")
        return self.prompt_choices([
            ('w', 'keep waiting', self.wait_for_game_to_start),
            ('o', 'choose another game', self.select_game)
        ])

    def join_game(self):
        return self.api.join_game(gid=input("Game ID: "))

    def play_turn(self):
        if self.api.can_play():
            hand = self.api.game['players'][self.api.player['name']]['hand']
            print("Treasure is {}. Choose a play. (Your hand is {}.)".format(
                self.api.game['turns'][0]['treasure'],
                ", ".join(str(card) for card in hand)))
            while not self.api.play_move(play=input("> ")):
                print("That's not a valid choice.")

        if self.api.game['status'] == 'playing':
            print("Waiting for opponent's move...")
        while self.api.game['status'] == 'playing' and not self.api.can_play():
            self.api.get_game()
            sleep(1)

        print("{} plays {}. You {}.".format(
            self.api.opponent_name(),
            self.api.last_complete_turn()[self.api.opponent_name()], {
                -1: 'lose',
                0: 'tie',
                1: 'win'
            }[self.api.last_turn_result()]))
        print("Your score: {}. {}'s score: {}".format(
            self.api.game['players'][self.api.player['name']]['score'],
            self.api.opponent_name(),
            self.api.game['players'][self.api.opponent_name()]['score'],
        ))
        if self.api.game['status'] == 'playing':
            self.play_turn()
        else:
            self.end_game()

    def end_game(self):
        print("Game over. Your score: {}; Opponent's score: {}".format(
            self.api.game['players'][self.api.player['name']]['score'],
            self.api.game['players'][self.api.opponent_name()]['score'],
        ))
        self.select_game()

    def prompt_choices(self, choices):
        for key, message, action in choices:
            print("  [{}] {}".format(key, message))
        while True:
            choice = input("> ")
            for key, message, action in choices:
                if choice == key:
                    return action()
Exemplo n.º 8
0
class TreasureClient:
    def __init__(self, url=None, pid=None, name=None, gid=None):
        self.name = name
        self.pid = pid
        self.url = url
        self.gid = gid
        self.__init_api()
        if gid and gid in api.player['games_playing']:
            self.api.get_game(gid=gid)
        else:
            self.select_game()

    def __init_api(self):
        print "init", args
        while True:
            try:
                # print "self", self.pid
                # print "self", self.name
                self.api = TreasureApi(url=self.url,
                                       pid=self.pid,
                                       name=self.name)
                if hasattr(self.api, 'error'):
                    print self.api.error[
                        'error'] + ": the player probably already exists"
                    self.setup_player()
                else:
                    # print("here")
                    break
            except ValueError:
                self.setup_player()

    def setup_player(self):
        print("Do you have a player?")
        self.prompt_choices([('n', 'new player', self.create_new_player),
                             ('e', 'existing player', self.get_pid),
                             ('q', 'quit playing', sys.exit)])

    def create_new_player(self):
        print("What is your player's name? ")
        self.name = raw_input()

    def get_pid(self):
        print("What is your existing player's PID? ")
        self.pid = raw_input()

    def select_game(self):
        print("How would you like to join a game?")
        while not self.prompt_choices(
            [('n', 'new game', self.new_game),
             ('r', 'resume an ongoing game', self.api.resume_game),
             ('j', 'join any game', self.api.join_any_game),
             ('s', 'join a specific game', self.join_game),
             ('q', 'quit playing', sys.exit)]):
            print("Sorry, that didn't work. Please choose an option:")

        print("Playing game {} against {}".format(self.api.game['gid'],
                                                  self.api.opponent_name()))
        self.play_turn()

    def new_game(self):
        self.api.new_game()
        return self.wait_for_game_to_start()

    def wait_for_game_to_start(self):
        self.api.get_game()
        if self.api.game['status'] == 'playing':
            return True
        print("Waiting for another player to join.")
        return self.prompt_choices([
            ('w', 'keep waiting', self.wait_for_game_to_start),
            ('o', 'choose another game', self.select_game),
            ('q', 'quit playing', sys.exit)
        ])

    def join_game(self):
        return self.api.join_game(gid=input("Game ID: "))

    def play_turn(self):
        if self.api.can_play():
            hand = self.api.game['players'][self.api.player['name']]['hand']
            print("Treasure is {}. Choose a play. (Your hand is {}.)".format(
                self.api.game['turns'][0]['treasure'],
                ", ".join(str(card) for card in hand)))
            while not self.api.play_move(play=input("> ")):
                print("That's not a valid choice.")

        if self.api.game['status'] == 'playing':
            print("Waiting for opponent's move...")
        while self.api.game['status'] == 'playing' and not self.api.can_play():
            self.api.get_game()
            sleep(1)

        print("{} plays {}. You {}.".format(
            self.api.opponent_name(),
            self.api.last_complete_turn()[self.api.opponent_name()], {
                -1: 'lose',
                0: 'tie',
                1: 'win'
            }[self.api.last_turn_result()]))
        print("Your score: {}. {}'s score: {}".format(
            self.api.game['players'][self.api.player['name']]['score'],
            self.api.opponent_name(),
            self.api.game['players'][self.api.opponent_name()]['score'],
        ))
        if self.api.game['status'] == 'playing':
            self.play_turn()
        else:
            self.end_game()

    def end_game(self):
        print("Game over. Your score: {}; Opponent's score: {}".format(
            self.api.game['players'][self.api.player['name']]['score'],
            self.api.game['players'][self.api.opponent_name()]['score'],
        ))
        self.select_game()

    def prompt_choices(self, choices):
        for key, message, action in choices:
            print("  [{}] {}".format(key, message))
        choice = None
        while True:
            choice = raw_input('> ')
            print choice
            for key, message, action in choices:
                if choice == key:
                    # print key, message, action
                    # print "action", action
                    return action()