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
Ejemplo n.º 2
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
Ejemplo n.º 3
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()
Ejemplo n.º 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
Ejemplo n.º 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
Ejemplo n.º 6
0
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
Ejemplo n.º 7
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
Ejemplo n.º 8
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()
Ejemplo n.º 9
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()
Ejemplo n.º 10
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
Ejemplo n.º 11
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
Ejemplo n.º 12
0
def play_game(hero1, hero2):
    open(log_file, 'w').close()

    deck1 = random_draft(hero=hero1)
    deck1[0] = "EX1_160a"
    player1 = Player(name="Player1")
    player1.prepare_deck(deck1, hero1)

    deck2 = random_draft(hero=hero2)
    deck2[0] = "EX1_160a"
    player2 = Player(name="Player2")
    player2.prepare_deck(deck2, hero2)

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

    player1.choice.choose(*[])
    player2.choice.choose(*[])

    while game.state != State.COMPLETE:
        try:
            heropower = game.current_player.hero.power
            if heropower.is_usable():
                if heropower.has_target():
                    heropower.use(target=random.choice(heropower.targets))
                else:
                    heropower.use()

            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)
                    card.play(target=target)

            for character in game.current_player.characters:
                if character.can_attack():
                    character.attack(random.choice(character.targets))

            game.end_turn()
        except GameOver:
            pass
Ejemplo n.º 13
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
				choice = None
				if card.has_target():
					target = random.choice(card.targets)
				if card.data.choose_cards:
					choice = random.choice(card.data.choose_cards)
				card.play(target=target, choose=choice)
			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()
Ejemplo n.º 14
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()
Ejemplo n.º 15
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
Ejemplo n.º 16
0
def _draft(hero, exclude):
    # random_draft() is fairly slow, this caches the drafts
    if (hero, exclude) not in _draftcache:
        _draftcache[(hero, exclude)] = random_draft(hero, exclude + BLACKLIST)
    return _draftcache[(hero, exclude)]
Ejemplo n.º 17
0
def _draft(hero, exclude):
	# random_draft() is fairly slow, this caches the drafts
	if (hero, exclude) not in _draftcache:
		_draftcache[(hero, exclude)] = random_draft(hero, exclude + BLACKLIST)
	return _draftcache[(hero, exclude)], hero
Ejemplo n.º 18
0
def _draft(card_class, exclude):
    # random_draft() is fairly slow, this caches the drafts
    if (card_class, exclude) not in _draftcache:
        _draftcache[(card_class,
                     exclude)] = random_draft(card_class, exclude + BLACKLIST)
    return _draftcache[(card_class, exclude)], card_class.default_hero
Ejemplo n.º 19
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.
Ejemplo n.º 20
0
from random import choice

import fireplace.logging
from fireplace import cards
from fireplace.cards.heroes import *
from fireplace.exceptions import GameOver
from fireplace.entity import Entity
from fireplace.game import Game
from fireplace.player import Player
from fireplace.utils import random_draft
from hearthstone.enums import PlayState

cards.db.initialize()
fireplace.logging.log.setLevel(logging.WARN)

deck1 = random_draft(SHAMAN)
deck2 = random_draft(PALADIN)

player1 = Player("Player1", deck1, SHAMAN)
player2 = Player("Player2", deck2, PALADIN)

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

for player in game.players:
    if player.choice:
        player.choice.choose()

begin_time = datetime.datetime.utcnow()
N = 100
for i in range(N):
Ejemplo n.º 21
0
def _draft(card_class, exclude):
	# random_draft() is fairly slow, this caches the drafts
	if (card_class, exclude) not in _draftcache:
		_draftcache[(card_class, exclude)] = random_draft(card_class, exclude + BLACKLIST)
	return _draftcache[(card_class, exclude)], card_class.default_hero
Ejemplo n.º 22
0
def try_montecarlo_tree_search(_game,
                               _candidates=[],
                               _trialPerTree=50,
                               _numOfTree=10):
    from fireplace.deck import Deck
    copyGame = copy.deepcopy(_game)  #フルコピーをとる。
    myPlayer = copyGame.current_player  #呼び出した「自分」
    enemy = myPlayer.opponent  #呼び出した「相手」
    handNum = len(enemy.hand)  #相手のハンドの枚数
    totalScores = []
    if len(_candidates) == 0:  #事前にはじいているので、これは起こらない。
        return
        pass
    if len(_candidates) == 1:  #そもそもアクション候補が1つなら、そのアクションを行う。
        return _candidates[0]
        pass
    for i in range(_numOfTree):
        #シミュレーション下準備(この下準備は運営側で提供すべき。具体的にはdeepcopyのときに組み込むべき。)
        #random_sampling
        exclude = []  # 除外すべきカードは、読み込みを停めている。
        d = random_draft(enemy.hero.card_class,
                         exclude)  #カードクラスに従ったランダムなデッキ。第1引数はクラス名に変更。
        enemy.hand = CardList()  #敵のハンドをクリア
        enemy.deck = Deck()  #敵のデッキをクリア
        for item in d:  #敵のデッキを更新
            enemy.card(item, zone=Zone.DECK)
            pass
        enemy.draw(count=handNum)  #敵のハンドを更新
        #ゲーム木展開
        #あとでcandidatesをpopするからそのまま使うと_candidatesは空説
        cand = getCandidates(copyGame, _includeTurnEnd=True)
        root = Node(copyGame, None, None, cand)  #ファイル内クラス
        for k in range(_trialPerTree):
            current_node = root
            while len(current_node.untriedMoves) == 0 and len(
                    current_node.childNodes) != 0:
                current_node = current_node.selectChild()
            if len(current_node.untriedMoves) != 0:
                expanding_action = current_node.choose_expanding_action()
                current_node = current_node.expandChild(expanding_action)
            result = current_node.simulate()
            current_node.backPropagate(result)
        visitScores = list(
            map(lambda node: myActionValue(node.move, node.visits),
                root.childNodes))
        totalScores = addActionValues(totalScores, visitScores)
        print("totalScores")
        for item in totalScores:
            print("{action} -->{score}".format(action=item.action,
                                               score=item.score))
            pass
    maxScore = max(
        list(map(lambda actionValue: actionValue.score, totalScores)))
    retAction = 0
    for item in totalScores:
        if item.score == maxScore:
            retAction = item.action
            pass
        pass
    print(retAction)
    for item in _candidates:
        if item == retAction:
            retAction = item
            pass
        pass
    #time.sleep(5)
    return retAction
    pass
Ejemplo n.º 23
0
def try_montecarlo_tree_search(_game,
                               _candidates=[],
                               _trialPerTree=10,
                               _numOfTree=10):
    from fireplace.deck import Deck
    copyGame = copy.deepcopy(_game)
    myPlayer = copyGame.current_player
    enemy = myPlayer.opponent
    handNum = len(enemy.hand)
    totalScores = []
    if len(_candidates) == 0:
        return
        pass
    if len(_candidates) == 1:
        return _candidates[0]
        pass
    for i in range(_numOfTree):
        #シミュレーション下準備
        #random_sampling
        d = random_draft(enemy.hero)
        enemy.hand = CardList()
        enemy.deck = Deck()
        for item in d:
            enemy.card(item, zone=Zone.DECK)
            pass
        enemy.draw(count=handNum)
        #ゲーム木展開
        root = Node(copyGame, None, None, _candidates)
        print(_candidates)
        for k in range(_trialPerTree):
            currentNode = root
            print("----------")
            print("dig tree...")
            while len(currentNode.untriedMoves) == 0 and len(
                    currentNode.childNodes) != 0:
                currentNode = currentNode.selectChild()
                print(currentNode.move)
                print("->")
                pass
            print("digged!!")
            print("expand child...")
            if len(currentNode.untriedMoves) != 0:
                #まだ探索してない枝がある
                print("expanding...")
                expandingAction = currentNode.choose_expanding_action()
                try:
                    currentNode = currentNode.expandChild(expandingAction)
                except GameOver:
                    #今gameoverに勝者の情報は入っていないので注意して
                    newChild = Node(None, expandingAction, currentNode, [])
                    if winner == "Maya":
                        newChild.setScore(1)
                        pass
                    else:
                        newChild.setScore(0)
                    currentNode.childNodes.append(newChild)
                    newChild.backPropagate()
                    continue
                print("done")
                pass
            else:
                currentNode.backPropagate()
                continue
                pass
            print("is it ended?")
            result = simulate_random_game(currentNode.gameTree)
            currentNode.backPropagate(result)
            pass
        visitScores = list(
            map(lambda node: myActionValue(node.move, node.visits),
                root.childNodes))
        totalScores = addActionValues(totalScores, visitScores)
        print("totalScores")
        for item in totalScores:
            print(item.action)
            print("-->{score}".format(score=item.score))
            pass
    maxScore = max(
        list(map(lambda actionValue: actionValue.score, totalScores)))
    retAction = 0
    for item in totalScores:
        if item.score == maxScore:
            retAction = item.action
            pass
        pass
    print(retAction)
    #time.sleep(5)
    return retAction
    pass
Ejemplo n.º 24
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'
Ejemplo n.º 25
0
def generate_decks(winner_hero=None, winner_deck=None):
    decks = {}
    for hero in heroes:
        decks[hero] = winner_deck if hero == winner_hero else random_draft(hero=hero)
    return decks