def PresetGame(pp, testNr=1):
    from fireplace import cards
    cards.db.initialize()
    for test in range(testNr):
        class1 = pp.class1
        class2 = pp.class2
        Dummy1 = DummyAgent("Dummy1", DummyAgent.DummyAI, myClass=class1)
        Dummy2 = DummyAgent("Dummy2", DummyAgent.DummyAI, myClass=class2)
        deck1 = random_draft(Dummy1.myClass, [])  #random deck wrt its class
        deck2 = random_draft(Dummy2.myClass, [])  #random deck wrt its class
        player1 = Player(Dummy1.name, deck1, Dummy1.myClass.default_hero)
        player2 = Player(Dummy2.name, deck2, Dummy2.myClass.default_hero)
        game = Game(players=(player1, player2))
        # Configurations
        player1._start_hand_size = 3  ## this line must be before 'start()'
        player2._start_hand_size = 3  ##
        player1.max_mana = 9  ## this line must be before 'start()'
        player2.max_mana = 9  ##
        game.start()
        player1.hero.max_health = 30  ## this line must be below 'start()'
        player2.hero.max_health = 30  ##
        cards_to_mulligan = []
        player1.choice.choose(*cards_to_mulligan)
        player2.choice.choose(*cards_to_mulligan)
        player1._targetedaction_log = []
        player2._targetedaction_log = []
        pp(game.current_player).execute(test)
    pass
예제 #2
0
def main():
	deck1 = random_draft(hero=MAGE)
	deck2 = random_draft(hero=WARRIOR)
	player1 = Player(name="Player1")
	player1.prepare_deck(deck1, MAGE)
	player2 = Player(name="Player2")
	player2.prepare_deck(deck2, WARRIOR)

	game = Game(players=(player1, player2))
	game.start()

	while True:
		heropower = game.current_player.hero.power
		# always play the hero power, just for kicks
		if heropower.is_playable():
			if heropower.has_target():
				heropower.play(target=random.choice(heropower.targets))
			else:
				heropower.play()
		# iterate over our hand and play whatever is playable
		for card in game.current_player.hand:
			if card.is_playable():
				if card.has_target():
					card.play(target=random.choice(card.targets))
				else:
					card.play()
			else:
				print("Not playing", card)

		# Randomly attack with whatever can attack
		for character in game.current_player.characters:
			if character.can_attack():
				character.attack(random.choice(character.targets))

		game.end_turn()
예제 #3
0
    def getInitGame(self):
        """
        Returns:
            startBoard: a representation of the board (ideally this is the form
                        that will be the input to your neural network)
        """
        if self.isolate:
            self.isolateSet()

        cards.db.initialize()
        if self.is_basic:  #create quick simple game
            with open('notbasic.data', 'rb') as f:
                extra_set = pickle.load(f)
            p1 = 6  #priest
            p2 = 7  #rogue
            deck1 = random_draft(CardClass(p1), exclude=extra_set)
            deck2 = random_draft(CardClass(p2), exclude=extra_set)
        else:
            p1 = random.randint(1, 9)
            p2 = random.randint(1, 9)
            deck1 = random_draft(CardClass(p1))
            deck2 = random_draft(CardClass(p2))
        self.players[0] = Player("Player1", deck1, CardClass(p1).default_hero)
        self.players[1] = Player("Player2", deck2, CardClass(p2).default_hero)
        game = Game(players=self.players)
        game.start()

        # Skip mulligan for now
        for player in game.players:
            cards_to_mulligan = random.sample(player.choice.cards, 0)
            player.choice.choose(*cards_to_mulligan)

        game.player_to_start = game.current_player
        self.game = game
        return game
예제 #4
0
def setup_game():
    """
    initializes a game between two players
    Returns:
        game: A game entity representing the start of the game after the mulligan phase
    """

    #choose classes (priest, rogue, shaman, warlock)
    p1 = random.randint(6, 9)
    p2 = random.randint(6, 9)
    #initialize players and randomly draft decks
    #pdb.set_trace()
    deck1 = random_draft(CardClass(p1))
    deck2 = random_draft(CardClass(p2))
    player1 = Player("Player1", deck1, CardClass(p1).default_hero)
    player2 = Player("Player2", deck2, CardClass(p2).default_hero)
    #begin the game
    game = Game(players=(player1, player2))
    game.start()

    #Skip mulligan for now
    for player in game.players:
        cards_to_mulligan = random.sample(player.choice.cards, 0)
        player.choice.choose(*cards_to_mulligan)

    return game
예제 #5
0
    def initGame(self):
        cards.db.initialize()
        if self.is_basic: #create quick simple game
            with open('notbasic.data', 'rb') as f:
                extra_set = pickle.load(f)
            p1 = 6 #priest
            p2 = 7 #rogue
            deck1 = random_draft(CardClass(p1), exclude=extra_set)
            deck2 = random_draft(CardClass(p2), exclude=extra_set)
        else:
            p1 = random.randint(1, 9)
            p2 = random.randint(1, 9)
            deck1 = random_draft(CardClass(p1))
            deck2 = random_draft(CardClass(p2))
        Board.players[0] = Player("Player1", deck1, CardClass(p1).default_hero)
        Board.players[1] = Player("Player2", deck2, CardClass(p2).default_hero)
        game = Game(players=self.players)
        game.start()

        # Skip mulligan for now
        for player in game.players:
            cards_to_mulligan = random.sample(player.choice.cards, 0)
            player.choice.choose(*cards_to_mulligan)

        # self.start_player = game.current_player
        game.player_to_start = game.current_player
        Board.game = game
        return game
예제 #6
0
    def add_player(self, player):
        if len(self.players) >= 2:
            raise RoomFull

        self.players.append(player)
        if len(self.players) == 2:
            self.game = Game(players=self.players)
            self.game.start()
예제 #7
0
    def init_game(self):
        """
        initializes a game between two players
        Returns:
            game: A game entity representing the start of the game after the mulligan phase
        """
        if self.is_basic:  #create quick simple game
            p1 = 6  #priest
            p2 = 7  #rogue
            deck1 = random_draft(CardClass(p1))
            deck2 = random_draft(CardClass(p2))
            self.players[0] = Player("Player1", deck1,
                                     CardClass(p1).default_hero)
            self.players[1] = Player("Player2", deck2,
                                     CardClass(p2).default_hero)
            self.game = Game(players=self.players)
            self.game.start()

            #Skip mulligan
            for player in self.game.players:
                cards_to_mulligan = random.sample(player.choice.cards, 0)
                player.choice.choose(*cards_to_mulligan)

            return self.game

        else:
            p1 = random.randint(1, 9)
            p2 = random.randint(1, 9)
            #initialize players and randomly draft decks
            #pdb.set_trace()
            deck1 = random_draft(CardClass(p1))
            deck2 = random_draft(CardClass(p2))
            self.players[0] = Player("Player1", deck1,
                                     CardClass(p1).default_hero)
            self.players[1] = Player("Player2", deck2,
                                     CardClass(p2).default_hero)
            #begin the game
            self.game = Game(players=self.players)
            self.game.start()

            #Skip mulligan for now
            for player in self.game.players:
                cards_to_mulligan = random.sample(player.choice.cards, 0)
                player.choice.choose(*cards_to_mulligan)

            return self.game
예제 #8
0
    def DoMove(self, move):
        """ Update a state by carrying out the given move.
        """
        if self.game is not None:
            assert self.game.current_player.playstate == PlayState.PLAYING

            if self.game.current_player is not None:
                if self.game.current_player.name == "one":
                    self.playerJustMoved = 1
                else:
                    self.playerJustMoved = 2

        try:
            if move[0] == MOVE.PRE_GAME:
                self.player1 = Player("one", self.deck1, self.hero1)
                self.player2 = Player("two", self.deck2, self.hero2)
                self.game = Game(players=(self.player1, self.player2))
                self.game.start()

                # TODO: Mulligan
                for player in self.game.players:
                    if player.choice:
                        player.choice.choose()
            elif move[0] == MOVE.PICK_CLASS:
                self.hero2 = move[1]
            elif move[0] == MOVE.PICK_CARD:
                if len(self.deck1) < 30:
                    self.deck1.append(move[1].id)
                else:
                    self.deck2.append(move[1].id)
            elif move[0] == MOVE.MULLIGAN:
                self.game.current_player.choice.choose(*move[1])
            elif move[0] == MOVE.END_TURN:
                self.game.end_turn()
            elif move[0] == MOVE.HERO_POWER:
                heropower = self.game.current_player.hero.power
                if move[3] is None:
                    heropower.use()
                else:
                    heropower.use(target=heropower.targets[move[3]])
            elif move[0] == MOVE.PLAY_CARD:
                card = self.game.current_player.hand[move[2]]
                if move[3] is None:
                    card.play()
                else:
                    card.play(target=card.targets[move[3]])
            elif move[0] == MOVE.MINION_ATTACK:
                minion = self.game.current_player.field[move[2]]
                minion.attack(minion.targets[move[3]])
            elif move[0] == MOVE.HERO_ATTACK:
                hero = self.game.current_player.hero
                hero.attack(hero.targets[move[3]])
            elif move[0] == MOVE.CHOICE:
                self.game.current_player.choice.choose(move[1])
            else:
                raise NameError("DoMove ran into unclassified card", move)
        except:
            return
예제 #9
0
파일: turn_bench.py 프로젝트: leod/arena
def play_full_game():
        deck1 = random_draft(hero=MAGE)
        deck2 = random_draft(hero=WARRIOR)
        player1 = Player("Player1", deck1, MAGE)
        player2 = Player("Player2", deck2, WARRIOR)

        game = Game(players=(player1, player2))
        game.start()

        for player in game.players:
                # print("Can mulligan %r" % (player.choice.cards))
                mull_count = random.randint(0, len(player.choice.cards))
                cards_to_mulligan = random.sample(player.choice.cards, mull_count)
                player.choice.choose(*cards_to_mulligan)

        try:
                while True:
                        player = game.current_player

                        heropower = player.hero.power
                        if heropower.is_usable() and random.random() < 0.1:
                                if heropower.has_target():
                                        heropower.use(target=random.choice(heropower.targets))
                                else:
                                        heropower.use()
                                continue

                        # iterate over our hand and play whatever is playable
                        for card in player.hand:
                                if card.is_playable() and random.random() < 0.5:
                                        target = None
                                        if card.choose_cards:
                                                card = random.choice(card.choose_cards)
                                        if card.has_target():
                                                target = random.choice(card.targets)
                                        # print("Playing %r on %r" % (card, target))
                                        card.play(target=target)

                                        if player.choice:
                                                choice = random.choice(player.choice.cards)
                                                # print("Choosing card %r" % (choice))
                                                player.choice.choose(choice)

                                        continue

                        # Randomly attack with whatever can attack
                        for character in player.characters:
                                if character.can_attack():
                                        character.attack(random.choice(character.targets))
                                continue

                        game.end_turn()

        except GameOver:
                return game
                # print("Game completed normally in " + str(game.turn) + " turns.")

        return game
예제 #10
0
    def getInitGame(self):
        """
        Returns:
            startBoard: a representation of the board (ideally this is the form
                        that will be the input to your neural network)
        """
        if self.isolate:
            self.isolateSet()

        cards.db.initialize()
        if self.is_basic:  #create quick simple game
            # with open('notbasic.data', 'rb') as f:
            #     extra_set = pickle.load(f)

            extra_set = cards.filter(card_set=[
                CardSet.EXPERT1, CardSet.HOF, CardSet.NAXX, CardSet.GVG,
                CardSet.BRM, CardSet.TGT, CardSet.LOE, CardSet.OG, CardSet.
                KARA, CardSet.GANGS, CardSet.UNGORO, CardSet.ICECROWN, CardSet.
                LOOTAPALOOZA, CardSet.GILNEAS, CardSet.BOOMSDAY, CardSet.TROLL
            ])
            # LOOTAPALOOZA = Kobolds and Catacombs # GILNEAS = Witchwood # TROLL = Rasthakan's Rumble

            # p1 = 6 #priest
            p1 = 7  #rogue
            p2 = 7  #rogue
            # p1 = 4 # mage
            # p2 = 4 # mage
            # deck1 = random_draft(CardClass(p1), exclude=extra_set)
            # deck2 = random_draft(CardClass(p2), exclude=extra_set)
            deck1 = self.roguebasic_draft(
            )  # use same shuffled rogue AI basic decks for now
            deck2 = self.roguebasic_draft()
        else:
            p1 = random.randint(1, 9)
            p2 = random.randint(1, 9)
            deck1 = random_draft(CardClass(p1))
            deck2 = random_draft(CardClass(p2))
        self.players[0] = Player("Player1", deck1, CardClass(p1).default_hero)
        self.players[1] = Player("Player2", deck2, CardClass(p2).default_hero)
        game = Game(players=self.players)
        game.start()

        # Skip mulligan for now (only mulligan expensive cards)
        for player in game.players:
            # if player.name == 'Player1':
            # cards_to_mulligan = [c for c in player.choice.cards if c.cost > 3]
            # else:
            cards_to_mulligan = random.sample(player.choice.cards, 0)
            player.choice.choose(*cards_to_mulligan)

        # track played card list
        self.players[0].playedcards = []
        self.players[1].playedcards = []

        #game.player_to_start = game.current_player      # obsolete?
        self.game = game
        return game
	def start(self):
		self.hero1 = CardClass.HUNTER.default_hero
		self.hero2 = CardClass.HUNTER.default_hero
		self.deck1 = list(hunter_simple_deck)
		self.deck2 = list(hunter_simple_deck)
		self.player1 = Player(PLAYER_1_NAME, self.deck1, self.hero1)
		self.player2 = Player(PLAYER_2_NAME, self.deck2, self.hero2)
		self.game = Game(players=(self.player1, self.player2))
		self.game.start()
		self.skipMulligan()
예제 #12
0
def play_full_game():
    deck1 = random_draft(hero=MAGE)
    deck2 = random_draft(hero=WARRIOR)
    player1 = Player(name="Player1")
    player1.prepare_deck(deck1, MAGE)
    player2 = Player(name="Player2")
    player2.prepare_deck(deck2, WARRIOR)

    game = Game(players=(player1, player2))
    game.start()

    for player in game.players:
        print("Can mulligan %r" % (player.choice.cards))
        mull_count = random.randint(0, len(player.choice.cards))
        cards_to_mulligan = random.sample(player.choice.cards, mull_count)
        player.choice.choose(*cards_to_mulligan)

    while True:
        player = game.current_player

        heropower = player.hero.power
        if heropower.is_usable() and percent_chance(10):
            if heropower.has_target():
                heropower.use(target=random.choice(heropower.targets))
            else:
                heropower.use()
            continue

        # iterate over our hand and play whatever is playable
        for card in player.hand:
            if card.is_playable() and percent_chance(50):
                target = None
                if card.choose_cards:
                    card = random.choice(card.choose_cards)
                if card.has_target():
                    target = random.choice(card.targets)
                print("Playing %r on %r" % (card, target))
                card.play(target=target)
                continue

        # Randomly attack with whatever can attack
        for character in player.characters:
            if character.can_attack():
                character.attack(random.choice(character.targets))
            continue

        if player.choice:
            choice = random.choice(player.choice.cards)
            print("Choosing card %r" % (choice))
            player.choice.choose(choice)
            continue

        game.end_turn()
예제 #13
0
    def collect_game_data(self):
        win_num = 0
        game_data = []
        start_time = time.time()

        for game_round in range(self.model_config.round_num):
            # initialize game
            deck1 = [
                c[1] for c in self.game_config.card_config.cards_list[1:] * 4
            ]
            player1 = HearthStoneGod('Player1',
                                     deck1,
                                     CardClass.MAGE.default_hero,
                                     self.game_config,
                                     game_model=self.player1_model,
                                     mode=self.player1_mode,
                                     device=self.device)

            deck2 = [
                c[1] for c in self.game_config.card_config.cards_list[1:] * 4
            ]
            player2 = HearthStoneGod('Player2',
                                     deck2,
                                     CardClass.MAGE.default_hero,
                                     self.game_config,
                                     game_model=self.player2_model,
                                     mode=self.player2_mode,
                                     device=self.device)

            game = Game(players=[player1, player2])
            game.start()

            # play game
            # mulligan
            player1.mulligan(skip=True)
            player2.mulligan(skip=True)

            try:
                while True:
                    player = game.current_player
                    player.play_turn(game)

            except GameOver:
                if player2.hero.dead:
                    win_num += 1
                    game_data.append((player1.replay, player1.hero.health))
                else:
                    game_data.append((player1.replay, -player2.hero.health))

        end_time = time.time()
        win_rate = win_num / self.model_config.round_num

        return game_data, win_rate
예제 #14
0
def test_full_game():
    global __last_turn__
    __last_turn__ = [None, None, None]
    try:
        json = []

        deck1 = get_face_hunter_deck()
        deck2 = random_draft(hero=WARRIOR)
        player1 = Player("Player1", deck1, HUNTER)
        player2 = Player("Player2", deck2, WARRIOR)

        game = Game(players=(player1, player2))
        game.start()
        play_full_game(json, game, player1, player2)
    except GameOver:
        #LAST TURN
        if (__last_turn__[1] != None):
            hashmap = get_hash_map(game, player1, player2, __last_turn__[2],
                                   __last_turn__[0].entity_id,
                                   __last_turn__[0].entity_id,
                                   __last_turn__[1].entity_id,
                                   __last_turn__[0])
            json.append(hashmap)
        else:
            hashmap = get_hash_map(game, player1, player2, __last_turn__[2],
                                   __last_turn__[0].entity_id,
                                   __last_turn__[0].entity_id, None,
                                   __last_turn__[0])
            json.append(hashmap)

        #RESULT
        if (game.current_player.hero.health < 1):
            hashmap = get_hash_map(game, player1, player2, 21,
                                   game.current_player.hero.entity_id, None,
                                   None, None)
            json.append(hashmap)
        else:
            hashmap = get_hash_map(game, player1, player2, 20,
                                   game.current_player.hero.entity_id, None,
                                   None, None)
            json.append(hashmap)

        f = open(REPLAY_JSON_PATH, 'w')
        write_line_to_file(f, json.__str__())
        my_datetime = datetime.now()
        path_to_zip = "C:\\Users\\Lubko\\OneDrive\\Documents\\matfyz\\bakalarka\\Hearthstone-Deck-Tracker-master\\Hearthstone Deck Tracker\\obj\\Debug\\Replay\\Replays\\" + my_datetime.strftime(
            "%d_%B_%Y__%H_%M.hdtreplay")
        my_zip_file = zipfile.ZipFile(path_to_zip, mode='w')
        my_zip_file.write(REPLAY_JSON_PATH)
        f.close()
        my_zip_file.close()
예제 #15
0
def setup_game() -> (Game, (Agent, Agent)):
    agent1 = MonteCarloAgent(CardClass.WARRIOR)
    agent2 = GameStateAgent(CardClass.PALADIN)

    print(agent1.player, " vs ", agent2.player)

    game = Game(players=(agent1.player, agent2.player))

    agent1.game = game
    agent2.game = game

    game.start()

    return game, (agent1, agent2)
예제 #16
0
    def reset(self):
        from fireplace.game import Game
        from fireplace.player import Player

        deck1 = self.draft_mage()
        deck2 = self.draft_mage()
        player1 = Player("Player1", deck1, CardClass.MAGE.default_hero)
        player2 = Player("Player2", deck2, CardClass.MAGE.default_hero)

        self.game = Game(players=(player1, player2))
        self.start_game()

        self.new_game = True

        return self.create_board_state()
예제 #17
0
def setup_basic_game():
    p1 = 6 #priest
    p2 = 7 #rogue

    deck1 = random_draft(CardClass(p1))
    deck2 = random_draft(CardClass(p2))
    player1 = Player("Player1", deck1, CardClass(p1).default_hero)
    player2 = Player("Player2", deck2, CardClass(p2).default_hero)
    game = Game(players=(player1, player2))
    game.start()

    #Skip mulligan
    for player in game.players:
        cards_to_mulligan = random.sample(player.choice.cards, 0)
        player.choice.choose(*cards_to_mulligan)

    return game
예제 #18
0
파일: full_game.py 프로젝트: leod/arena
def play_full_game(hero1, deck1, hero2, deck2):
    log.info('{} vs {}'.format(hero1, hero2))
    player1 = Player("Player1", deck1, hero1)
    player2 = Player("Player2", deck2, hero2)

    game = Game(players=(player1, player2))
    game.start()

    # Random mulligan for now
    for player in game.players:
        if player.choice:
            player.choice.choose()

    print(repr(game))
    return

    begin_time = datetime.datetime.utcnow()
    N = 1000
    for i in range(N):
        game2 = copy.deepcopy(game)
    end_time = datetime.datetime.utcnow()
    print((end_time - begin_time))
    return

    try:
        while True:
            state = GameState(game)

            #if state.winner() != None:
            #print("Winner: " + str(state.winner()))
            #break

            mcts = MonteCarlo(state, 1)
            play = mcts.get_play()

            log.info("GOT A MOVE!!!! %r", play)
            break

            fireplace.logging.log.setLevel(logging.DEBUG)
            play.play(game)
            fireplace.logging.log.setLevel(logging.WARN)
    except GameOver:
        state = GameState(game)
        if state.winner() != None:
            log.info("Winner: " + str(state.winner()))
예제 #19
0
def main():
	deck1 = random_draft(hero=MAGE)
	deck2 = random_draft(hero=WARRIOR)
	player1 = Player(name="Player1")
	player1.prepare_deck(deck1, MAGE)
	player2 = Player(name="Player2")
	player2.prepare_deck(deck2, WARRIOR)

	game = Game(players=(player1, player2))
	game.start()

	for player in game.players:
		print("Can mulligan %r" % (player.choice.cards))
		mull_count = random.randint(0, len(player.choice.cards))
		cards_to_mulligan = random.sample(player.choice.cards, mull_count)
		player.choice.choose(*cards_to_mulligan)

	while True:
		heropower = game.current_player.hero.power
		# always play the hero power, just for kicks
		if heropower.is_usable():
			if heropower.has_target():
				heropower.use(target=random.choice(heropower.targets))
			else:
				heropower.use()
		# iterate over our hand and play whatever is playable
		for card in game.current_player.hand:
			if card.is_playable():
				target = None
				if card.choose_cards:
					card = random.choice(card.choose_cards)
				if card.has_target():
					target = random.choice(card.targets)
				print("Playing %r on %r" % (card, target))
				card.play(target=target)
			else:
				print("Not playing", card)

		# Randomly attack with whatever can attack
		for character in game.current_player.characters:
			if character.can_attack():
				character.attack(random.choice(character.targets))

		game.end_turn()
예제 #20
0
def setup_game():
    from fireplace.game import Game
    from fireplace.player import Player
    fireplace.cards.filter(name="Garrosh")

    player1 = Player("OddWarrior", warrior_deck,
                     CardClass.WARRIOR.default_hero)
    player2 = Player("MurlocPaladin", paladin_deck,
                     CardClass.PALADIN.default_hero)

    game = Game(players=(player1, player2))
    game.start()

    for player in game.players:
        mull_count = 0
        cards_to_mulligan = []
        player.choice.choose(*cards_to_mulligan)

        game.begin_turn(player)

    return game
예제 #21
0
    def initGame(self):
        self.init_envi()

        if self.is_basic:  #create quick simple game
            p1 = 6  #priest
            p2 = 7  #rogue
        else:
            p1 = random.randint(1, 9)
            p2 = random.randint(1, 9)
        deck1 = random_draft(CardClass(p1))
        deck2 = random_draft(CardClass(p2))
        self.players[0] = Player("Player1", deck1, CardClass(p1).default_hero)
        self.players[1] = Player("Player2", deck2, CardClass(p2).default_hero)
        game = Game(players=self.players)
        game.start()

        #Skip mulligan for now
        for player in self.game.players:
            cards_to_mulligan = random.sample(player.choice.cards, 0)
            player.choice.choose(*cards_to_mulligan)

        return game
예제 #22
0
def setup_game(deck, player_name, opponents_deck):
	from fireplace.game import Game
	from fireplace.player import Player

	#Some cards from these decks aren't implemented which means that they won't have an effect,
	#if they are a minion then it will have it's stats but not the battlecry effect, spell will just do nothing
	#either implement it or talk about it
	deck1 = deck
	deck2 = opponents_deck

	#global so it can carry over to other functions
	global name
	name = player_name

	#It seems that player classes influence the deck win rate, Hunters win more than Warlocks due to the dumb AI
	player1 = Player(name, deck1, CardClass.WARRIOR.default_hero)
	player2 = Player("Oppenent", deck2, CardClass.MAGE.default_hero)

	game = Game(players=(player1, player2))
	game.start()

	return game
예제 #23
0
    def create_game(self, payload):
        # self.game_id = payload["GameID"]
        player_data = payload["Players"]
        players = []
        for player in player_data:
            # Shuffle the cards to prevent information leaking
            cards = player["Cards"]
            random.shuffle(cards)
            p = Player(player["Name"], cards, player["Hero"])
            players.append(p)

        INFO("Initializing a Kettle game with players=%r", players)
        game = Game(players=players)
        manager = KettleManager(game)
        game.manager.register(manager)
        game.current_player = game.players[0]  # Dumb.
        game.start()

        # Skip mulligan
        for player in game.players:
            player.choice = None

        return manager
예제 #24
0
def setup_game() -> ".game.Game":
    from fireplace.game import Game
    from simulator.player import Player

    # card_indices = [27, 48, 68, 159, 169, 180, 307, 386, 546, 588]  # randomly chosen 10 integers from [1,698]
    # card_indices = [random.randrange(1, 25) for i in range(10)]

    deck1 = shuffled_const_draft([])  # choose cards for Player1
    deck2 = shuffled_const_draft([])  # choose cards for Player2

    printer.print_deck_content("Player1", deck1)
    printer.print_deck_content("Player2", deck2)

    player1 = Player("Player1", deck1, CardClass.MAGE.default_hero)
    player2 = Player("Player2", deck2, CardClass.HUNTER.default_hero)

    game = Game(players=(player1, player2))
    game.start()

    player1.hero.set_current_health(20)
    player2.hero.set_current_health(20)

    return game
예제 #25
0
파일: interactive.py 프로젝트: hackiey/TAGI
    deck1 = [c[1] for c in game_config.card_config.cards_list[1:] * 4]
    player1 = HearthStoneGod('Player1',
                             deck1,
                             CardClass.MAGE.default_hero,
                             game_config,
                             mode='manual')

    deck2 = [c[1] for c in game_config.card_config.cards_list[1:] * 4]
    player2 = HearthStoneGod('Player2',
                             deck2,
                             CardClass.MAGE.default_hero,
                             game_config,
                             game_model=game_model,
                             mode='model_play')

    game = Game(players=(player1, player2))
    game.start()

    player1.mulligan(skip=True)
    player2.mulligan(skip=True)

    try:
        while True:
            player = game.current_player
            player.play_turn(game)

    except GameOver:
        if game.player2.hero.dead:
            print('You Win!')
        else:
            print('You Lose!')
예제 #26
0
def play_one_game(P1: Agent,
                  P2: Agent,
                  deck1=[],
                  deck2=[],
                  debugLog=True,
                  HEROHPOPTION=30,
                  P1MAXMANA=1,
                  P2MAXMANA=1,
                  P1HAND=3,
                  P2HAND=3):
    """ エージェント同士で1回対戦する。
	実験的に、ヒーローの体力、初期マナ数、初期ハンド枚数をコントロールできます。
	play one game by P1 and P2 """
    from fireplace.utils import random_draft
    from fireplace.player import Player
    import random
    exclude = []  # you may exclude some cards to construct a deck
    log.info("New game settings")
    if len(deck1) == 0:
        deck1 = random_draft(P1.myClass, exclude)  #random deck wrt its class
    if len(deck2) == 0:
        deck2 = random_draft(P2.myClass, exclude)  #random deck wrt its class
    player1 = Player(P1.name, deck1, P1.myClass.default_hero)
    player2 = Player(P2.name, deck2, P2.myClass.default_hero)
    player1.choiceStrategy = P1.choiceStrategy
    player2.choiceStrategy = P2.choiceStrategy
    game = Game(players=(player1, player2))
    # Configurations
    player1._start_hand_size = P1HAND  ## this line must be before 'start()'
    player2._start_hand_size = P2HAND  ##
    player1.max_mana = int(
        P1MAXMANA) - 1  ## this line must be before 'start()'
    player2.max_mana = int(P2MAXMANA) - 1
    game.start()
    player1.hero.max_health = int(
        HEROHPOPTION)  ## this line must be below 'start()'
    player2.hero.max_health = int(HEROHPOPTION)  ##

    #mulligan exchange
    # Any agent are allowed to give an algorithm to do mulligan exchange.
    for player in game.players:
        if player.name == P1.name:
            if P1.mulliganStrategy == None:
                mull_count = random.randint(0, len(player.choice.cards))
                cards_to_mulligan = random.sample(player.choice.cards,
                                                  mull_count)
            else:
                cards_to_mulligan = P1.mulliganStrategy(
                    P1, player.choice.cards)
        elif player.name == P2.name:
            if P2.mulliganStrategy == None:
                mull_count = random.randint(0, len(player.choice.cards))
                cards_to_mulligan = random.sample(player.choice.cards,
                                                  mull_count)
            else:
                cards_to_mulligan = P2.mulliganStrategy(
                    P2, player.choice.cards)
        player.choice.choose(*cards_to_mulligan)  # includes begin_turn()
    #mulligan exchange end
    log.info("New game start")

    while True:
        #game main loop
        player = game.current_player
        start_time = time.time()
        if player.name == P1.name:
            #please make each Agent.func has arguments 'self, game, option, gameLog, debugLog'
            P1.func(P1,
                    game,
                    option=P1.option,
                    gameLog=game.get_log(),
                    debugLog=debugLog)
        elif player.name == P2.name:
            #please make each Agent.func has arguments 'self, game, option, gameLog, debugLog'
            P2.func(P2,
                    game,
                    option=P2.option,
                    gameLog=game.get_log(),
                    debugLog=debugLog)
        else:
            Original_random(game)  #random player by fireplace
        #turn end procedure from here
        if player.choice != None:
            player.choice = None  #somotimes it comes here
        if game.state != State.COMPLETE:
            try:
                game.end_turn()
                if debugLog:
                    print(">>>>%s>>>>turn change %d[sec]>>>>%s" %
                          (player, time.time() - start_time, player.opponent),
                          end='  ')
                    print("%d : %d" %
                          (player1.hero.health + player1.hero.armor,
                           player2.hero.health + player2.hero.armor))
                if game.current_player.choice != None:
                    postAction(game.current_player)
            except GameOver:  #it rarely occurs
                gameover = 0
        #ゲーム終了フラグが立っていたらゲーム終了処理を行う
        #if game was over
        if game.state == State.COMPLETE:
            if debugLog:
                print(">>>>>>>>>>game end >>>>>>>>" % (), end=' ')
                print("%d : %d" % (player1.hero.health, player2.hero.health))
            if game.current_player.playstate == PlayState.WON:
                return game.current_player.name
            if game.current_player.playstate == PlayState.LOST:
                return game.current_player.opponent.name
            return 'DRAW'  #Maybe impossible to come here.
예제 #27
0
def test_full_game(ai_1_id, deck_1_id, ai_2_id, deck_2_id, clear_results):
    global __last_turn__
    global player1
    global player2
    global my_json
    global neural_net
    global table

    player1 = get_instance_by_name(ai_1_id, deck_1_id)
    player2 = get_instance_by_name(ai_2_id, deck_2_id)
    __last_turn__ = [None, None, None]

    attributes = get_attributes()
    my_datetime = datetime.now()
    game_id = player1.get_id() + "-" + deck_1_id + "-" + player2.get_id(
    ) + "-" + deck_2_id + "-" + my_datetime.strftime("%Y_%m_%d") + "-" + str(
        attributes["NumGame"]).zfill(7)

    try:
        path_to_dir = os.path.dirname(
            os.getcwd()) + "\\game_results\\" + game_id + "\\"
        if not os.path.exists(path_to_dir):
            os.makedirs(path_to_dir)
        my_json = []

        path_to_csv = path_to_dir + game_id + ".csv"
        csv_file = open(path_to_csv, "w")
        fieldnames = get_field_names()
        csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        csv_writer.writeheader()

        #        path_to_deck1 = path_to_dir + type(player1).__name__ + "_" + my_datetime.strftime("%d_%B_%Y__%H_%M.hsdeck.txt")
        #        deck1_file = open(path_to_deck1,"w")
        #        log_deck(deck1_file, player1)

        #        path_to_deck2 = path_to_dir + type(player2).__name__ + "_" + my_datetime.strftime("%d_%B_%Y__%H_%M.hsdeck.txt")
        #        deck2_file = open(path_to_deck2,"w")
        #        log_deck(deck2_file, player2)

        game = Game(players=(player1, player2))
        game.start()

        play_full_game(my_json, game, csv_writer)

    except GameOver:
        win_reward = 0
        #         if (player1.__class__ is Q_learner_super_makro or player1.__class__ is Q_learner_super_makro_alt):
        #             if (player1.hero.health > 0):
        #                 reward = win_reward
        #             else:
        #                 reward = 0
        #             player1.update_neural_network(player1.previous_state, player1.previous_q_value, player1.get_state(), player1.previous_action, reward)
        #             net = player1.neural_network
        # #            path = os.path.join(os.path.dirname(os.getcwd()), 'network.xml')
        # #            NetworkWriter.writeToFile(net, path)
        #             neural_net = net
        #
        #         if (player2.__class__ is Q_learner_super_makro or player2.__class__ is Q_learner_super_makro_alt):
        #             if (player2.hero.health > 0):
        #                 reward = win_reward
        #             else:
        #                 reward = 0
        #             player2.update_neural_network(player2.previous_state, player2.previous_q_value, player2.get_state(), player2.previous_action, reward)
        #             net = player2.neural_network
        # #            path = os.path.join(os.path.dirname(os.getcwd()), 'network.xml')
        # #            NetworkWriter.writeToFile(net, path)
        #             neural_net = net

        if (player1.__class__ is Q_learner_table
                or player1.__class__ is Q_learner_table_08
                or player1.__class__ is Q_learner_table_win):
            if (player1.hero.health > 0):
                reward = 0
            else:
                reward = 0
            player1.update_table(player1.previous_state, player1.get_state(),
                                 player1.previous_action, reward)
            table = player1.table

        if (player2.__class__ is Q_learner_table
                or player2.__class__ is Q_learner_table_08
                or player2.__class__ is Q_learner_table_win):
            if (player2.hero.health > 0):
                reward = 0
            else:
                reward = 0
            player2.update_table(player2.previous_state, player2.get_state(),
                                 player2.previous_action, reward)
            table = player2.table

        #LAST TURN
        if (__last_turn__[1] != None):
            hashmap = get_hash_map(game, player1, player2, __last_turn__[2],
                                   __last_turn__[0].entity_id,
                                   __last_turn__[0], __last_turn__[1],
                                   __last_turn__[0])
            my_json.append(hashmap)
        else:
            hashmap = get_hash_map(game, player1, player2, __last_turn__[2],
                                   __last_turn__[0].entity_id,
                                   __last_turn__[0], None, __last_turn__[0])
            my_json.append(hashmap)

        #RESULT
        if (game.current_player.hero.health < 1):
            hashmap = get_hash_map(game, player1, player2, 21,
                                   game.current_player.hero.entity_id, None,
                                   None, None)
            my_json.append(hashmap)
        else:
            hashmap = get_hash_map(game, player1, player2, 20,
                                   game.current_player.hero.entity_id, None,
                                   None, None)
            my_json.append(hashmap)

        f = open(REPLAY_JSON_PATH, 'w')
        write_line_to_file(f, my_json.__str__())
        path_to_replay = path_to_dir + game_id + ".hdtreplay"
        my_zip_file = zipfile.ZipFile(path_to_replay, mode='w')
        my_zip_file.write(REPLAY_JSON_PATH)

        if (clear_results):
            csv_result_file = open(path_to_result, "w")
            csv_writer = csv.DictWriter(csv_result_file,
                                        fieldnames=get_field_names_of_result())
            csv_writer.writeheader()
        else:
            csv_result_file = open(path_to_result, "a")
            csv_writer = csv.DictWriter(csv_result_file,
                                        fieldnames=get_field_names_of_result())
        csv_writer.writerow(get_result_of_game(game))
        csv_result_file.close()
        f.close()
        my_zip_file.close()

        set_attributes(attributes)
    except:
        print("UNEXPECTED ERROR:", sys.exc_info())
예제 #28
0
def play_one_game(P1: Agent,
                  P2: Agent,
                  deck1=[],
                  deck2=[],
                  HeroHPOption=30,
                  debugLog=True):
    from fireplace.utils import random_draft
    from fireplace.player import Player
    import random
    #バグが確認されているものを当面除外する
    exclude = ['CFM_672', 'CFM_621', 'CFM_095', 'LOE_076', 'BT_490']
    # 'LOE_076' : Sir Finley Mrrgglton
    # 'BT_490' : 魔力喰い、ターゲットの扱いにエラーがあるので除外。
    if len(deck1) == 0:
        deck1 = random_draft(P1.myClass, exclude)  #ランダムなデッキ
    if len(deck2) == 0:
        deck2 = random_draft(P2.myClass, exclude)  #ランダムなデッキ
    player1 = Player(P1.name, deck1, P1.myClass.default_hero)
    player2 = Player(P2.name, deck2, P2.myClass.default_hero)

    game = Game(players=(player1, player2))
    game.start()

    for player in game.players:
        #print("Can mulligan %r" % (player.choice.cards))
        mull_count = random.randint(0, len(player.choice.cards))
        cards_to_mulligan = random.sample(player.choice.cards, mull_count)
        player.choice.choose(*cards_to_mulligan)
    if HeroHPOption != 30:
        game.player1.hero.max_health = HeroHPOption
        game.player2.hero.max_health = HeroHPOption
    while True:
        from agent_Standard import StandardRandom, HumanInput, Original_random
        from agent_Maya import Maya_MCTS
        player = game.current_player
        #print("%r starts their turn."%player.name);
        if player.name == "Maya":
            Maya_MCTS(game)  #マヤ氏の作品
        elif player.name == "Standard":
            StandardRandom(
                game, debugLog=debugLog)  #公式のランダムより、もう少しキチンとしたランダムプレーエージェント
        elif player.name == "Human":
            HumanInput(game)  #人がプレーするときはこれ
        elif player.name == P1.name:
            P1.func(game, option=P1.option,
                    debugLog=debugLog)  #P1.funcには引数option, debugLogを作ってください
        elif player.name == P2.name:
            P2.func(game, option=P2.option,
                    debugLog=debugLog)  #P2.funcには引数option, debugLogを作ってください
        else:
            Original_random(game)  #公式のランダム
        if player.choice != None:
            player.choice = None  #論理的にはおこらないが、ときどきおこる
        if game.state != State.COMPLETE:
            try:
                game.end_turn()
            except GameOver:  #まれにおこる
                gameover = 0
        if game.state == State.COMPLETE:  #ゲーム終了フラグが立っていたら
            if game.current_player.playstate == PlayState.WON:
                return game.current_player.name
            if game.current_player.playstate == PlayState.LOST:
                return game.current_player.opponent.name
            return 'DRAW'
예제 #29
0
def find_card_pair(onlyresult=1):
    card_class = CardClass.MAGE  #カードクラスを設定することは必須
    allCards = get_all_cards(card_class, costMax=2)
    vanillas = get_all_vanillas(allCards)
    nonVanillas = get_all_non_vanillas(allCards)
    spells = get_all_spells(allCards)

    #良いカードペアを漠然と探す旅に出る2枚は呪文カードしばり
    for matchNumber in range(10):
        count1 = 0
        count2 = 0

        #ヒーローパワーを消す、というのもよいかも。
        nonvanillaName1 = random.choice(nonVanillas)
        nonvanilla1 = nonvanillaName1.id
        nonvanillaName2 = random.choice(spells)  #この呪文によって、まえのカードが活かされるかどうか
        nonvanilla2 = nonvanillaName2.id

        print(" specific cards : %r%r" % (nonvanillaName1, nonvanillaName2))
        for repeat in range(25):
            if onlyresult == 0:
                print("    GAME %d" % repeat, end="  -> ")
            #set decks and players
            deck1 = []
            position = random.randint(1, 7)
            for i in range(position):
                deck1.append((random.choice(vanillas)).id)
            deck1.append(nonvanilla1)
            deck1.append(nonvanilla2)
            for i in range(8 - position):  #デッキは10枚
                deck1.append(random.choice(vanillas).id)
            player1 = Player("Player1", deck1, card_class.default_hero)
            deck2 = copy.deepcopy(deck1)
            random.shuffle(deck2)
            player2 = Player("Player2", deck2, card_class.default_hero)
            #set a game
            game = Game(players=(player1, player2))
            game.start()

            for player in game.players:
                #print("Can mulligan %r" % (player.choice.cards))
                mull_count = random.randint(0, len(player.choice.cards))
                cards_to_mulligan = random.sample(player.choice.cards,
                                                  mull_count)
                player.choice.choose(*cards_to_mulligan)
            game.player1.hero.max_health = 10
            game.player2.hero.max_health = 10
            turnNumber = 0
            if onlyresult == 0:
                print("Turn ", end=':')
            while True:
                turnNumber += 1
                if onlyresult == 0:
                    print(turnNumber, end=":")
                #StandardRandom(game)#ここはもう少し賢くする
                weight = [
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                ]
                weight[0] = weight[1] = 5
                weight[26] = 10
                weight[2] = weight[3] = weight[6] = weight[7] = 5
                weight[10] = weight[11] = weight[12] = weight[13] = 5
                StandardStep1(game, debugLog=False)
                if game.state != State.COMPLETE:
                    try:
                        game.end_turn()
                    except GameOver:  #まれにおこる
                        pass
                if game.state == State.COMPLETE:
                    if game.current_player.playstate == PlayState.WON:
                        winner = game.current_player.name
                        break
                    elif game.current_player.playstate == PlayState.LOST:
                        winner = game.current_player.opponent.name
                        break
                    else:
                        winner = "DRAW"
                    break
            if onlyresult == 0:
                print("%s won." % winner)
            if winner == "Player1":
                if onlyresult == 1:
                    print("O", end=".")
                count1 += 1
            elif winner == "Player2":
                if onlyresult == 1:
                    print("X", end=".")
                count2 += 1
        print("(%d : %d)" % (count1, count2), end=" ")  #25戦で10点差があれば有意な差あり
        if count1 - count2 >= 10:
            print("Significant")
        else:
            print("")
    pass
예제 #30
0
def investigate_card_pair(onlyresult=0):
    card_class = CardClass.HUNTER
    allCards = get_all_cards(card_class)
    vanillas = get_all_vanillas(allCards)
    nonVanillas = get_all_non_vanillas(allCards)

    count1 = 0
    count2 = 0

    #ヒーローパワーを消す、というのもよいかも。
    #良いカードペアを漠然と探す旅に出る?
    nonvanilla1 = 'EX1_045'  #random.choice(nonVanillas).id#自分で指定してもよい
    nonvanilla2 = 'EX1_332'  #random.choice(nonVanillas).id#
    #古代の番人:EX1_045:攻撃できない。
    #沈黙:EX1_332:ミニオン1体を沈黙させる

    print(" specific cards : %r%r" % (nonvanilla1, nonvanilla2))
    for repeat in range(50):
        print("    GAME %d" % repeat, end="  -> ")
        #set decks and players
        deck1 = []
        position = random.randint(1, 7)
        for i in range(position):
            deck1.append((random.choice(vanillas)).id)
        deck1.append(nonvanilla1)
        deck1.append(nonvanilla2)
        for i in range(8 - position):  #デッキは10枚
            deck1.append(random.choice(vanillas).id)
        player1 = Player("AAAA", deck1, card_class.default_hero)
        deck2 = copy.deepcopy(deck1)
        random.shuffle(deck2)
        player2 = Player("BBBB", deck2, card_class.default_hero)
        #set a game
        game = Game(players=(player1, player2))
        game.start()

        for player in game.players:
            #print("Can mulligan %r" % (player.choice.cards))
            mull_count = random.randint(0, len(player.choice.cards))
            cards_to_mulligan = random.sample(player.choice.cards, mull_count)
            player.choice.choose(*cards_to_mulligan)
        game.player1.hero.max_health = 10  # ヒーローのHPは10
        game.player2.hero.max_health = 10

        turnNumber = 0
        print("Turn ", end=':')
        while True:
            turnNumber += 1
            print(turnNumber, end=":")
            weight = [
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            ]
            weight[0] = weight[1] = 5
            weight[26] = 10
            weight[2] = weight[3] = weight[6] = weight[7] = 5
            weight[10] = weight[11] = weight[12] = weight[13] = 5
            StandardStep1(game, debugLog=False)
            #StandardRandom(game,debugLog=True)
            #ここはもう少し賢い人にやってほしい
            if game.state != State.COMPLETE:
                try:
                    game.end_turn()
                except GameOver:  #まれにおこる
                    pass
            else:
                if game.current_player.playstate == PlayState.WON:
                    winner = game.current_player.name
                    break
                elif game.current_player.playstate == PlayState.LOST:
                    winner = game.current_player.opponent.name
                    break
                else:
                    winner = "DRAW"
                    break
        print("%s won." % winner)
        if winner == "AAAA":
            count1 += 1
        elif winner == "BBBB":
            count2 += 1
    print("%d : %d" % (count1, count2))