예제 #1
0
def do_stuff():
    _count = 0

    def play_game():
        nonlocal _count
        _count += 1
        new_game = game.copy()
        try:
            new_game.start()
        except Exception as e:
            print(
                json.dumps(new_game.__to_json__(),
                           default=lambda o: o.__to_json__(),
                           indent=1))
            print(new_game._all_cards_played)
            raise e

        del new_game

        if _count % 1000 == 0:
            print("---- game #{} ----".format(_count))

    deck1 = load_deck("mage.hsdeck")
    deck2 = load_deck("mage2.hsdeck")
    game = Game([deck1, deck2], [RandomAgent(), RandomAgent()])

    print(timeit.timeit(play_game, 'gc.enable()', number=100000))
예제 #2
0
def do_stuff():
    def play_game():
        new_game = game.copy()
        new_game.start()

    deck1 = load_deck("example.hsdeck")
    deck2 = load_deck("example.hsdeck")
    game = Game([deck1, deck2], [RandomAgent(), RandomAgent()])
    game.start()

    print(timeit.timeit(play_game, 'gc.enable()', number=1000))
예제 #3
0
 def test_deck_shortening(self):
     deck1 = Deck([
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         RagnarosTheFirelord(),
         GoldshireFootman(),
         GoldshireFootman()
     ], Malfurion())
     deck2 = StackedDeck([StonetuskBoar()], CHARACTER_CLASS.HUNTER)
     game = Game([deck1, deck2], [RandomAgent(), RandomAgent()])
     replay = record(game)
     game.start()
     replay.write(StringIO())
예제 #4
0
def do_stuff():
    _count = 0

    def play_game():
        nonlocal _count
        _count += 1
        new_game = game.copy()
        try:
            winner = new_game.start()
            print("Winner: ", winner)
            print("turns passed : ", new_game._turns_passed)

            print("# " * 27, " GAME OVER ", " #" * 27)
            print(new_game.players[0],
                  "has",
                  new_game.players[0].hero.health,
                  "life points,\t",
                  end='')
            print(new_game.players[1], "has", new_game.players[1].hero.health,
                  "life points")
            print(winner, 'won the game (', winner.agent, ')')
            print("# " * 61, "\n")
            print("AVG tree depth per nr of turns", global_depth)
            print("AVG percent of explored children", global_nodesvisited)

        except Exception as e:
            # print(json.dumps(new_game.__to_json__(), default=lambda o: o.__to_json__(), indent=1))
            # print(new_game._all_cards_played)
            raise e

        del new_game

        if _count % 1000 == 0:
            print("---- game #{} ----".format(_count))

    cards = load_deck("mage3.hsdeck")
    deck1 = Deck(cards, Jaina())
    deck2 = Deck(cards, Malfurion())
    game = Game([deck1, deck2], [MCTSAgent(30), RandomAgent()])
    # game = Game([deck1, deck2], [AggressiveAgent(), RandomAgent()])

    # game = Game([deck1, deck2], [ControllingAgent(), RandomAgent()])
    # game = Game([deck1, deck2], [TalkativeAgent(), RandomAgent()])
    # game = Game([deck1, deck2], [RandomAgent(), RandomAgent()])

    print(timeit.timeit(play_game, 'gc.enable()', number=1))
예제 #5
0
    def test_RandomAgent(self):
        deck1 = Deck([
            GoldshireFootman(),
            GoldshireFootman(),
            MurlocRaider(),
            MurlocRaider(),
            BloodfenRaptor(),
            BloodfenRaptor(),
            FrostwolfGrunt(),
            FrostwolfGrunt(),
            RiverCrocolisk(),
            RiverCrocolisk(),
            IronfurGrizzly(),
            IronfurGrizzly(),
            MagmaRager(),
            MagmaRager(),
            SilverbackPatriarch(),
            SilverbackPatriarch(),
            ChillwindYeti(),
            ChillwindYeti(),
            KeeperOfTheGrove(),
            KeeperOfTheGrove(),
            SenjinShieldmasta(),
            SenjinShieldmasta(),
            BootyBayBodyguard(),
            BootyBayBodyguard(),
            FenCreeper(),
            FenCreeper(),
            BoulderfistOgre(),
            BoulderfistOgre(),
            WarGolem(),
            WarGolem(),
        ], Malfurion())

        deck2 = Deck([
            Shieldbearer(),
            Shieldbearer(),
            FlameImp(),
            FlameImp(),
            YoungPriestess(),
            YoungPriestess(),
            DarkIronDwarf(),
            DarkIronDwarf(),
            DireWolfAlpha(),
            DireWolfAlpha(),
            Voidwalker(),
            Voidwalker(),
            HarvestGolem(),
            HarvestGolem(),
            KnifeJuggler(),
            KnifeJuggler(),
            ShatteredSunCleric(),
            ShatteredSunCleric(),
            ArgentSquire(),
            ArgentSquire(),
            Doomguard(),
            Doomguard(),
            Soulfire(),
            Soulfire(),
            DefenderOfArgus(),
            DefenderOfArgus(),
            AbusiveSergeant(),
            AbusiveSergeant(),
            NerubianEgg(),
            NerubianEgg(),
        ], Guldan())

        game = Game([deck1, deck2], [RandomAgent(), RandomAgent()])
        game.pre_game()
        game.current_player = game.players[1]

        game.play_single_turn()

        self.assertEqual(0, len(game.current_player.minions))

        game.play_single_turn()
        self.assertEqual(2, len(game.current_player.minions))
        self.assertEqual(3, game.current_player.minions[1].health)
        self.assertEqual("Young Priestess",
                         game.current_player.minions[0].card.name)

        game.play_single_turn()
        self.assertEqual(1, len(game.current_player.minions))
        self.assertEqual("Frostwolf Grunt",
                         game.current_player.minions[0].card.name)

        game.play_single_turn()
        self.assertEqual(0, len(game.other_player.minions))
        self.assertEqual(28, game.other_player.hero.health)
        self.assertEqual(3, len(game.current_player.minions))
        self.assertEqual("Dire Wolf Alpha",
                         game.current_player.minions[2].card.name)

        for turn in range(0, 13):
            game.play_single_turn()
            self.assertFalse(game.game_ended)

        game.play_single_turn()

        self.assertEqual(0, game.current_player.hero.health)
        self.assertEqual(21, game.other_player.hero.health)

        self.assertTrue(game.game_ended)
예제 #6
0
 def __init__(self, finishrate=0.0001, period=200):
     RandomAgent.__init__(self)
     self.__finishrate = finishrate
     self.__period = period
예제 #7
0
def uct(rootstate, itermax, verbose=False):
    rootnode = Node(state=rootstate)
    counters = []
    visited = []

    for i in range(itermax):
        node = rootnode
        state = rootstate.clone()
        visited.append(
            len(node.childNodes) /
            (len(node.untriedMoves) + len(node.childNodes)) * 100)

        # print("Turn:", state.game._turns_passed, ", iteration:", i, "\nTried moves:", len(node.childNodes),
        #     "\nuntried moves:", len(node.untriedMoves))

        # Select
        while node.untriedMoves == [] and node.childNodes != []:  # node is fully expanded and non-terminal
            node = node.uct_select_child()
            # print("==========\nSelect - chosen move:", node.move)
            state.do_move(node.move)
            # print("Select - finished selecting for move:", node.move, "\n==========")

        # Expand
        if node.untriedMoves != []:  # if we can expand (i.e. state/node is non-terminal)
            m = random.choice(node.untriedMoves)
            # print("==========\nExpand - chosen move:", m)
            state.do_move(m)
            node = node.add_child(m, state)  # add child and descend tree
            # print("Expand - finished expanding for move:", m, "\n==========")

        # My rollout
        curr_player_won = 0
        if not state.game.current_player.hero.dead and not state.game.other_player.hero.dead:
            game_copy = state.game.copy()
            game_copy.players[0].change_agent(RandomAgent())
            game_copy.players[1].change_agent(RandomAgent())

            while not game_copy.current_player.hero.dead and not game_copy.other_player.hero.dead:
                game_copy._start_turn()
                game_copy.remove_dead_minions()
                game_copy.current_player.agent.do_turn(
                    game_copy.current_player)
                game_copy._end_turn()
            curr_player_won = 0 if game_copy.current_player.hero.dead else 1
            # print("Rollout - current player won") if curr_player_won == 0 else print("Rollout - other player won")
        counter = 0
        # My Backpropagate
        while node != None:  # backpropagate from the expanded node and work back to the root node
            # print("==========\nBackpropagation - updating node:", node)
            node.update(
                curr_player_won
            )  # state is terminal. update node with result from POV of node.playerJustMoved
            # print("Backpropagation - finished updating node:", node, "\n==========")
            node = node.parentNode
            counter += 1
        counters.append(counter)

    # Output some information about the tree - can be omitted
    if (verbose): print("Tree info:", rootnode.tree_to_string(0))
    else: print("Children of tree info:", rootnode.children_to_string())
    global_depth.append(
        (rootstate.game._turns_passed, sum(counters) / len(counters)))
    global_nodesvisited.append(
        (rootstate.game._turns_passed, sum(visited) / len(visited)))
    return sorted(rootnode.childNodes, key=lambda c: c.visits
                  )[-1].move  # return the move that was most visited
예제 #8
0
def render_game(stdscr):
    class TextAgent:

        def __init__(self, game_window, prompt_window, text_window):
            self.window = prompt_window
            self.game_window = game_window
            self.text_window = text_window
            curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_CYAN)
            curses.init_pair(6, curses.COLOR_BLACK, curses.COLOR_GREEN)

        def do_turn(self, player):
            renderer.draw_game()
            index = 0
            action = self.choose_action()
            while not (action == "quit" or action == "end"):
                if action == "play":
                    card = self.choose_card(player)
                    if card is not None:
                        player.game.play_card(card)
                elif action == "attack":
                    attacker = self.choose_attacker(player)
                    if attacker is not None:
                        attacker.attack()
                elif action == "power":
                    if player.hero.power.can_use():
                        player.hero.power.use()
                index += 1
                renderer.draw_game()
                action = self.choose_action()
            if action == "quit":
                sys.exit(0)

        def choose_action(self):
            self.window.addstr(0, 0, "Choose action")
            actions = ["play", "attack", "power", "end", "quit"]
            index = 0
            selected = 0
            for action in actions:
                if index == selected:
                    color = curses.color_pair(4)
                else:
                    color = curses.color_pair(3)

                self.text_window.addstr(0, index * 10, "{0:^9}".format(action), color)
                index += 1
            self.window.refresh()
            self.text_window.refresh()
            ch = 0
            while ch != 10 and ch != 27:
                ch = self.window.getch()
                if ch == curses.KEY_LEFT:
                    selected -= 1
                    if selected < 0:
                        selected = len(actions) - 1
                if ch == curses.KEY_RIGHT:
                    selected += 1
                    if selected == len(actions):
                        selected = 0
                index = 0
                for action in actions:
                    if index == selected:
                        color = curses.color_pair(4)
                    else:
                        color = curses.color_pair(3)

                    self.text_window.addstr(0, index * 10, "{0:^9}".format(action), color)
                    index += 1
                self.window.refresh()
                self.text_window.refresh()
            if ch == 27:
                return None

            return actions[selected]

        def choose_card(self, player):
            filtered_cards = [card for card in filter(lambda card: card.can_use(player, player.game), player.hand)]
            if len(filtered_cards) is 0:
                return None
            renderer.targets = filtered_cards
            renderer.selected_target = renderer.targets[0]
            renderer.draw_game()
            self.window.addstr(0, 0, "Choose Card")
            self.window.refresh()
            ch = 0
            index = 0
            while ch != 10 and ch != 27:
                ch = self.window.getch()

                if ch == curses.KEY_LEFT:
                    index -= 1
                    if index < 0:
                        index = len(renderer.targets) - 1
                if ch == curses.KEY_RIGHT:
                    index += 1
                    if index == len(renderer.targets):
                        index = 0
                renderer.selected_target = renderer.targets[index]
                renderer.draw_game()
                self.window.addstr(0, 0, "Choose Card")
                self.window.refresh()
            renderer.targets = None
            if ch == 27:
                return None

            return renderer.selected_target

        def choose_attacker(self, player):
            filtered_attackers = [minion for minion in filter(lambda minion: minion.can_attack(), player.minions)]
            if player.hero.can_attack():
                filtered_attackers.append(player.hero)
            if len(filtered_attackers) is 0:
                return None
            renderer.targets = filtered_attackers
            renderer.selected_target = renderer.targets[0]
            renderer.draw_game()
            self.window.addstr(0, 0, "Choose attacker")
            self.window.refresh()
            ch = 0
            index = 0
            while ch != 10 and ch != 27:
                ch = self.window.getch()
                self.window.addstr(0, 0, "{0}".format(ch))
                self.window.refresh()
                if ch == curses.KEY_LEFT:
                    index -= 1
                    if index < 0:
                        index = len(renderer.targets) - 1
                if ch == curses.KEY_RIGHT:
                    index += 1
                    if index == len(renderer.targets):
                        index = 0
                renderer.selected_target = renderer.targets[index]
                renderer.draw_game()
                self.window.refresh()
            renderer.targets = None
            if ch == 27:
                return None

            return renderer.selected_target

        def do_card_check(self, cards):

            self.window.addstr(0, 0, "Select cards to keep (space selects/deselects a card)")
            keeping = [True, True, True]
            if len(cards) > 3:
                keeping.append(True)
            index = 0
            selected = 0
            for card in cards:
                if keeping[index]:
                    if index == selected:
                        color = curses.color_pair(6)
                    else:
                        color = curses.color_pair(5)
                else:
                    if index == selected:
                        color = curses.color_pair(4)
                    else:
                        color = curses.color_pair(0)

                self.text_window.addstr(0, index * 20, "{0:^19}".format(card.name[:19]), color)
                index += 1
            self.window.refresh()
            self.text_window.refresh()
            ch = 0
            while ch != 10 and ch != 27:
                ch = self.window.getch()
                if ch == curses.KEY_LEFT:
                    selected -= 1
                    if selected < 0:
                        selected = len(cards) - 1
                if ch == curses.KEY_RIGHT:
                    selected += 1
                    if selected == len(cards):
                        selected = 0
                if ch == 32:
                    keeping[selected] = not keeping[selected]
                index = 0
                for card in cards:
                    if keeping[index]:
                        if index == selected:
                            color = curses.color_pair(6)
                        else:
                            color = curses.color_pair(5)
                    else:
                        if index == selected:
                            color = curses.color_pair(4)
                        else:
                            color = curses.color_pair(0)

                    self.text_window.addstr(0, index * 20, "{0:^19}".format(card.name[:19]), color)
                    index += 1
                self.window.refresh()
                self.text_window.refresh()
            if ch == 27:
                return None

            return keeping

        def choose_target(self, targets):

            if len(targets) is 0:
                return None
            renderer.targets = targets
            renderer.selected_target = renderer.targets[0]
            renderer.draw_game()
            self.window.addstr(0, 0, "Choose target")
            self.window.refresh()
            ch = 0
            index = 0
            while ch != 10 and ch != 27:
                ch = self.window.getch()
                if ch == curses.KEY_LEFT:
                    index -= 1
                    if index < 0:
                        index = len(renderer.targets) - 1
                if ch == curses.KEY_RIGHT:
                    index += 1
                    if index == len(renderer.targets):
                        index = 0
                renderer.selected_target = renderer.targets[index]
                renderer.draw_game()
                self.window.refresh()
            renderer.targets = None
            if ch == 27:
                return None

            return renderer.selected_target

        def choose_index(self, card, player):
            renderer.selection_index = 0
            renderer.draw_game()
            self.window.addstr(0, 0, "Choose placement location")
            self.window.refresh()
            ch = 0
            while ch != 10 and ch != 27:
                ch = self.window.getch()
                if ch == curses.KEY_LEFT:
                    renderer.selection_index -= 1
                    if renderer.selection_index < 0:
                        renderer.selection_index = len(player.minions)
                if ch == curses.KEY_RIGHT:
                    renderer.selection_index += 1
                    if renderer.selection_index > len(player.minions):
                        renderer.selection_index = 0
                renderer.draw_game()
                self.window.refresh()
            index = renderer.selection_index
            renderer.selection_index = -1
            if ch == 27:
                return -1

            return index

        def choose_option(self, *options):
            self.window.addstr(0, 0, "Choose option")
            index = 0
            selected = 0
            for option in options:
                if index == selected:
                    color = curses.color_pair(4)
                else:
                    color = curses.color_pair(3)

                self.text_window.addstr(0, index * 20, "{0:^19}".format(option.name[:19], color))
                index += 1
            self.window.refresh()
            self.text_window.refresh()
            ch = 0
            while ch != 10 and ch != 27:
                ch = self.window.getch()
                if ch == curses.KEY_LEFT:
                    selected -= 1
                    if selected < 0:
                        selected = len(options) - 1
                if ch == curses.KEY_RIGHT:
                    selected += 1
                    if selected == len(options):
                        selected = 0
                index = 0
                for option in options:
                    if index == selected:
                        color = curses.color_pair(4)
                    else:
                        color = curses.color_pair(3)

                    self.text_window.addstr(0, index * 20, "{0:^19}".format(option.name[:19], color))
                    index += 1
                self.window.refresh()
                self.text_window.refresh()
            if ch == 27:
                return None

            return options[selected]

    stdscr.clear()

    prompt_window = stdscr.derwin(1, 80, 23, 0)
    text_window = stdscr.derwin(1, 80, 24, 0)

    deck1 = load_deck(sys.argv[1])
    deck2 = load_deck(sys.argv[2])
    game = Game([deck1, deck2], [TextAgent(stdscr, prompt_window, text_window), RandomAgent()])
    if isinstance(game.players[0].agent, TextAgent):
        renderer = GameRender(stdscr, game, game.players[0])
    else:
        renderer = GameRender(stdscr, game, game.players[1])
    game.start()
예제 #9
0
                       ) + " with deck " + d1 + ": " + str(lwins) + " wins"
    returnString += '\n\t' + str(
        game.players[1].agent) + " with deck " + d2 + ": " + str(
            rwins) + " wins"
    if rwins != 0:
        returnString += '\n\t ratio: ' + str(lwins / rwins)

    return (returnString, lwins, rwins)


if __name__ == "__main__":
    rd = "rampDruid.hsdeck"
    vm = "valueMage.hsdeck"
    sw = "zooLock.hsdeck"

    ra = RandomAgent()
    ta = TempoAgent()
    ca = ControlAgent()
    aa = AggressiveAgent()

    agentList = [ra, ta, ca, aa]

    LOG_FILENAME = '_lolresults4.log'
    logging.basicConfig(filename=LOG_FILENAME,
                        level=logging.DEBUG,
                        filemode='w')

    for x in range(3, 4):

        for y in range(0, 4):
예제 #10
0

def bulid_starting_hands(deck_1, deck_2):
    starting_hands1 = list(itertools.combinations(deck_1.cards, 2))
    starting_hands2 = list(itertools.combinations(deck_2.cards, 2))


deck1 = load_deck("patron.hsdeck")
deck2 = load_deck("zoo.hsdeck")
'''
for i in range(len(deck1.cards)):
    print(type(deck1.cards[i].name))
    print(deck1.cards[i].name)
'''

game1 = Game([deck1, deck2], [RandomAgent(), RandomAgent()])

root = build_tree.RootChanceGameState(game1)

print('tree built')

X1 = []
Y1 = []
X2 = []
Y2 = []
nash1 = []
nash2 = []

chance_sampling_cfr = ChanceSamplingCFR(root)
for i in range(100):
    X1.append(i * 10)