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
def main(): deck1 = randomDraft(hero=fireplace.heroes.MAGE) deck2 = randomDraft(hero=fireplace.heroes.WARRIOR) player1 = Player(name="Player1") player1.prepareDeck(deck1, fireplace.heroes.MAGE) player2 = Player(name="Player2") player2.prepareDeck(deck2, fireplace.heroes.WARRIOR) game = Game(players=(player1, player2)) game.start() while True: heropower = game.currentPlayer.hero.power # always play the hero power, just for kicks if heropower.isPlayable(): if heropower.hasTarget(): heropower.play(target=random.choice(heropower.targets)) else: heropower.play() # iterate over our hand and play whatever is playable for card in game.currentPlayer.hand: if card.isPlayable(): if card.hasTarget(): 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.currentPlayer.characters: if character.canAttack(): character.attack(random.choice(character.targets)) game.endTurn()
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
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
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
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()
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
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()
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()
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
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()
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)
class Room(): def __init__(self): self.id = -1 self.players = [] self.game = None 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()
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()
def play_game(hero1, hero2): deck1 = decks[hero1] player1 = Player(name="Player1") player1.prepare_deck(deck1, hero1) deck2 = decks[hero2] 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 if player1.playstate == PlayState.TIED: return None if player1.playstate == PlayState.WON: return player1 return player2
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
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
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()))
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()
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
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()
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
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()
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
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
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
def random_play(game: Game) -> Game: player = game.current_player while True: heropower = player.hero.power if heropower.is_usable() and random.random() < 0.1: if heropower.requires_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.must_choose_one: card = random.choice(card.choose_cards) if card.requires_target(): target = random.choice(card.targets) card.play(target=target) if player.choice: choice = random.choice(player.choice.cards) 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)) break game.end_turn() return game
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
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()
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
def load_game(): data = json.load(open("N://HSTracker//board_state-hunter.json")) assert "player" in data assert "opponent" in data player_name = data["player"]["name"] opponent_name = data["opponent"]["name"] player_class = get_class(data["player"]["playerClass"]) opponent_class = get_class(data["opponent"]["playerClass"]) player_deck = random_draft(player_class) opponent_deck = random_draft(opponent_class) # Keep just enough cards for mulligan while len(player_deck) > 4: player_deck.pop() while len(opponent_deck) > 4: opponent_deck.pop() player_controller_id = data["player"]["entity"]["Tags"]["CONTROLLER"] opponent_controller_id = data["opponent"]["entity"]["Tags"]["CONTROLLER"] player_player = Player(player_name, player_deck, player_class.default_hero) opponent_player = Player(opponent_name, opponent_deck, opponent_class.default_hero) game = None if player_controller_id == 1 and opponent_controller_id == 2: game = Game(players=(player_player, opponent_player)) elif player_controller_id == 2 and opponent_controller_id == 1: game = Game(players=(opponent_player, player_player)) game.start() # Don't redraw mulligan cards for player in game.players: if player.choice: player.choice.choose() assert "cardsInHand" in data["opponent"] cards_in_opponent_hand = data["opponent"]["cardsInHand"] game.players[player_controller_id - 1].discard_hand() game.players[opponent_controller_id - 1].discard_hand() # fill the hand of the opponent with the card which doesn't do anything on draw / reveal for i in range(0, cards_in_opponent_hand): game.players[opponent_controller_id - 1].give("OG_335") # Shifting Shade assert "entity" in data["player"] assert "Tags" in data["player"]["entity"] process_tags(game.players[player_controller_id - 1], data["player"]["entity"]["Tags"]) assert "entity" in data["opponent"] assert "Tags" in data["opponent"]["entity"] process_tags(game.players[opponent_controller_id - 1], data["opponent"]["entity"]["Tags"]) cards_to_recheck = list() for entity in data["hand"]: assert "Tags" in entity assert "CONTROLLER" in entity["Tags"] controller = entity["Tags"]["CONTROLLER"] assert controller == player_controller_id assert "CardId" in entity cur_card_id = entity["CardId"] cur_card = game.players[controller - 1].give(cur_card_id) set_card_tags(cur_card, entity["Tags"], game) add_to_tags_verify_list(cards_to_recheck, cur_card, entity["Tags"]) # first summon heroes and their powers for entity in data["board"]: assert "Tags" in entity and "CONTROLLER" in entity["Tags"] cur_controller_id = entity["Tags"]["CONTROLLER"] assert cur_controller_id == 1 or cur_controller_id == 2 cur_controller = game.players[cur_controller_id - 1] assert "HasCardId" in entity and entity["HasCardId"] is True and "CardId" in entity cur_card_id = entity["CardId"] temp_card = Card(cur_card_id) if isinstance(temp_card, Hero) or isinstance(temp_card, HeroPower) or isinstance(temp_card, Weapon): cur_card = cur_controller.summon(cur_card_id) add_to_tags_verify_list(cards_to_recheck, cur_card, entity["Tags"]) set_card_tags(cur_card, entity["Tags"], game) for entity in data["board"]: assert "Tags" in entity and "CONTROLLER" in entity["Tags"] cur_controller_id = entity["Tags"]["CONTROLLER"] assert cur_controller_id == 1 or cur_controller_id == 2 cur_controller = game.players[cur_controller_id - 1] assert "HasCardId" in entity and entity["HasCardId"] is True and "CardId" in entity cur_card_id = entity["CardId"] temp_card = Card(cur_card_id) if isinstance(temp_card, Enchantment): if cur_card_id != 'EX1_059e' and cur_card_id != 'OG_281e': # don't apply "Experiments!" (health swap) buff # don't apply "Fanatic Devotion" buff (must be C'thun's increased stats) if not ("ATTACHED" in entity["Tags"]): # sometimes enchantments stay in play while not being attached to anything continue attached_id = entity["Tags"]["ATTACHED"] buff_attached_to = get_game_entity_by_id(game, attached_id) assert not (buff_attached_to is None) cur_card = my_add_buff(buff_attached_to, temp_card) set_card_tags(cur_card, entity["Tags"], game) elif not (isinstance(temp_card, Hero) or isinstance(temp_card, HeroPower)): cur_card = my_summon(game, cur_controller, temp_card) add_to_tags_verify_list(cards_to_recheck, cur_card, entity["Tags"]) set_card_tags(cur_card, entity["Tags"], game) for t in cards_to_recheck: set_card_tags(t[0], t[1], game) ensure_tags_are_same(t[0], t[1]) for player in game.players: sorted_cards = dict() for card in player.field: if isinstance(card, Weapon): continue zone_position = card._summon_index assert not zone_position in sorted_cards sorted_cards[zone_position] = card player.field = CardList() for pos in sorted(sorted_cards.keys()): assert pos == len(player.field) player.field.append(sorted_cards[pos]) game.current_player = game.players[player_controller_id - 1] for player in game.players: player.cards_played_this_turn = 0 player.minions_played_this_turn = 0 player.minions_killed_this_turn = 0 return game
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 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): 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): 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 #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())
class HearthState: """ A state of the game, i.e. the game board. """ def __init__(self): self.playerJustMoved = 2 # At the root pretend the player just moved is p2 - p1 has the first move random.seed(1857) # The idea of adjacent cards it to ignore minion placement if none of these cards can be found, since it doesn't # matter. #adjacent_cards = ["Dire Wolf Alpha", "Ancient Mage", "Defender of Argus", "Sunfury Protector", # "Flametongue Totem", "Explosive Shot", "Cone of Cold", "Betrayal", "Void Terror", # "Unstable Portal", "Wee Spellstopper", "Piloted Shredder", "Piloted Sky Golem", # "Recombobulator", "Foe Reaper 4000", "Nefarian"] #self.adjacent_cards = adjacent_cards self.player1 = None self.hero1 = MAGE self.deck1 = [] self.player2 = None self.hero2 = None self.deck2 = [] self.game = None # Simple Arcane Missiles lethal test #self.deck1 = ["EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", # "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", # "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", # "EX1_277", "EX1_277", "EX1_277"] #self.hero1 = MAGE #self.player1 = Player("one", self.deck1, self.hero1) #self.deck2 = ["EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", # "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", # "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", "EX1_277", # "EX1_277", "EX1_277", "EX1_277"] #self.hero2 = MAGE #self.player2 = Player("two", self.deck2, self.hero2) #self.game = Game(players=(self.player1, self.player2)) #self.game.start() #for player in self.game.players: # if player.choice: # player.choice.choose() #self.game.players[0].hero.hit(24) #self.game.players[1].hero.hit(24) def Clone(self): """ Create a deep clone of this game state. """ st = HearthState() st.playerJustMoved = self.playerJustMoved st.player1 = self.player1 st.hero1 = self.hero1 st.deck1 = copy.copy(self.deck1) st.player2 = self.player2 st.hero2 = self.hero2 st.deck2 = copy.copy(self.deck2) #st.game = copy.copy(self.game) st.game = copy.deepcopy(self.game) return st 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 def GetMoves(self): """ Get all possible moves from this state. """ if self.game is not None: if self.game.current_player.playstate != PlayState.PLAYING: return [] valid_moves = [] # Move format is [enum, card, index of card in hand, target index] if self.game is None and len(self.deck1) == 30 and len(self.deck2) == 30: valid_moves.append([MOVE.PRE_GAME]) elif self.game is None and len(self.deck1) == 30 and self.hero2 is None: valid_moves.append([MOVE.PICK_CLASS, DRUID]) valid_moves.append([MOVE.PICK_CLASS, HUNTER]) valid_moves.append([MOVE.PICK_CLASS, MAGE]) valid_moves.append([MOVE.PICK_CLASS, PALADIN]) valid_moves.append([MOVE.PICK_CLASS, PRIEST]) valid_moves.append([MOVE.PICK_CLASS, ROGUE]) valid_moves.append([MOVE.PICK_CLASS, SHAMAN]) valid_moves.append([MOVE.PICK_CLASS, WARLOCK]) valid_moves.append([MOVE.PICK_CLASS, WARRIOR]) elif self.game is None and len(self.deck1) < 30 or len(self.deck2) < 30: collection = [] exclude = [] if len(self.deck1) < 30: hero = cards.db[self.hero1] deck = self.deck1 else: hero = cards.db[self.hero2] deck = self.deck2 for card in cards.db.keys(): if card in exclude: continue cls = cards.db[card] if not cls.collectible: continue if cls.type == CardType.HERO: # Heroes are collectible... continue if cls.card_class and cls.card_class != hero.card_class: continue collection.append(cls) for card in collection: if card.rarity == Rarity.LEGENDARY and card.id in deck: continue elif deck.count(card.id) < Deck.MAX_UNIQUE_CARDS: valid_moves.append([MOVE.PICK_CARD, card]) elif self.game.current_player.choice is not None: for card in self.game.current_player.choice.cards: valid_moves.append([MOVE.CHOICE, card]) else: # Play card for card in self.game.current_player.hand: dupe = False for i in range(len(valid_moves)): if valid_moves[i][1].id == card.id: dupe = True break if not dupe: if card.is_playable(): if card.has_target(): for t in range(len(card.targets)): valid_moves.append([MOVE.PLAY_CARD, card, self.game.current_player.hand.index(card), t]) else: valid_moves.append([MOVE.PLAY_CARD, card, self.game.current_player.hand.index(card), None]) # Hero Power heropower = self.game.current_player.hero.power if heropower.is_usable(): if heropower.has_target(): for t in range(len(heropower.targets)): valid_moves.append([MOVE.HERO_POWER, None, None, t]) else: valid_moves.append([MOVE.HERO_POWER, None, None, None]) # Minion Attack for minion in self.game.current_player.field: if minion.can_attack(): for t in range(len(minion.targets)): valid_moves.append([MOVE.MINION_ATTACK, minion, self.game.current_player.field.index(minion), t]) # Hero Attack hero = self.game.current_player.hero if hero.can_attack(): for t in range(len(hero.targets)): valid_moves.append([MOVE.HERO_ATTACK, hero, None, t]) valid_moves.append([MOVE.END_TURN]) return valid_moves def GetResult(self, playerjm): """ Get the game result from the viewpoint of playerjm. """ if self.game.players[0].hero.health <= 0 and self.game.players[1].hero.health <= 0: return 0.1 elif self.game.players[playerjm - 1].hero.health <= 0: # loss return 0 elif self.game.players[2 - playerjm].hero.health <= 0: # win return pow(0.99, self.game.turn) else: # Should not be possible to get here unless we terminate the game early. return 0.1 def __repr__(self): try: s = "Turn: " + str(self.game.turn) s += "\n[" + str(self.game.players[0].hero.health) + " hp ~ " + str(len(self.game.players[0].hand)) + " in hand ~ " + str(self.game.players[0].tempMana) + "/" + str(self.game.players[0].maxMana) + " mana] " #s += "\n[" + str(self.game.players[0].hero.health) + " hp ~ " + str(len(self.game.players[0].hand)) + " in hand ~ " + str(self.game.players[0].deck.left) + "/" + str(len(self.game.players[0].deck.cards)) + " in deck ~ " + str(self.game.players[0].mana) + "/" + str(self.game.players[0].max_mana) + " mana] " for minion in self.game.players[0].field: s += str(minion.atk) + "/" + str(minion.health) + ":" s += "\n[" + str(self.game.players[1].hero.health) + " hp ~ " + str(len(self.game.players[1].hand)) + " in hand ~ " + str(self.game.players[1].tempMana) + "/" + str(self.game.players[1].maxMana) + " mana] " #s += "\n[" + str(self.game.players[1].hero.health) + " hp ~ " + str(len(self.game.players[1].hand)) + " in hand ~ " + str(self.game.players[1].deck.left) + "/" + str(len(self.game.players[1].deck.cards)) + " in deck ~ " + str(self.game.players[1].mana) + "/" + str(self.game.players[1].max_mana) + " mana] " for minion in self.game.players[1].field: s += str(minion.atk) + "/" + str(minion.health) + ":" s += "\n" + "Current Player: " + str(self.game.currentPlayer) return s except: s = "Deck 1: " + ", ".join(self.deck1) s += "\nDeck 2: " + ", ".join(self.deck2) return s
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): game2 = copy.deepcopy(game) end_time = datetime.datetime.utcnow() print((end_time - begin_time) / N)
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!')
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
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))
class HSEnv: def __init__(self, render): cards.db.initialize() # Create a game with the standardized decks if render: self.renderer = BoardRenderer() self.reset() def start_game(self): self.game.start() # Play the game """TODO: Implement Networked version of mulligan""" for player in self.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) def draft_mage(self): deck = [] deck.append(Card("EX1_277").id) #Arcane Missiles deck.append(Card("EX1_277").id) #Arcane Missiles deck.append(Card("NEW1_012").id) #Mana Wyrm deck.append(Card("NEW1_012").id) #Mana Wyrm deck.append(Card("CS2_027").id) #Mirror Image deck.append(Card("CS2_027").id) #Mirror Image deck.append(Card("EX1_066").id) #Acidic Swamp Ooze deck.append(Card("EX1_066").id) #Acidic Swamp Ooze deck.append(Card("CS2_025").id) #Arcane Explosion deck.append(Card("CS2_025").id) #Arcane Explosion deck.append(Card("CS2_024").id) #Frostbolt deck.append(Card("CS2_024").id) #Frostbolt deck.append(Card("CS2_142").id) #Kobold Geomancer deck.append(Card("CS2_142").id) #Kobold Geomancer deck.append(Card("EX1_608").id) #Sorcerer's Apprentice deck.append(Card("EX1_608").id) #Sorcerer's Apprentice deck.append(Card("CS2_023").id) #Arcane Intellect deck.append(Card("CS2_023").id) #Arcane Intellect deck.append(Card("CS2_029").id) #Fireball deck.append(Card("CS2_029").id) #Fireball deck.append(Card("CS2_022").id) #Polymorph deck.append(Card("CS2_022").id) #Polymorph deck.append(Card("CS2_033").id) #Water Elemental deck.append(Card("CS2_033").id) #Water Elemental deck.append(Card("CS2_155").id) #Archmage deck.append(Card("CS2_155").id) #Archmage deck.append(Card("EX1_559").id) #Archmage Antonidas deck.append(Card("CS2_032").id) #Flamestrike deck.append(Card("CS2_032").id) #Flamestrike deck.append(Card("EX1_279").id) #Pyroblast return deck def create_board_state(self): boardstate = [] # Player 1 mana boardstate.append(self.game.player1.max_mana - self.game.player1.overload_locked) # Player 2 mana boardstate.append(self.game.player2.max_mana - self.game.player2.overload_locked) # Player 1 handSize boardstate.append(self.game.player1.hand.__len__()) # Player 2 handSize boardstate.append(self.game.player2.hand.__len__()) # Player 2 hero health boardstate.append(self.game.player1.hero.health + self.game.player2.hero.armor) # Player 2 Hero Attack value if self.game.player2.weapon is not None: boardstate.append(self.game.player2.hero.atk + self.game.player2.weapon.atk) else: boardstate.append(self.game.player2.hero.atk) # Player 1 hero health boardstate.append(self.game.player1.hero.health + self.game.player2.hero.armor) # Player 1 Weapon if self.game.player1.weapon is not None: # Player 1 Weapon Health boardstate.append(self.game.player1.weapon.health_attribute) # Player 1 Weapon Attack boardstate.append(self.game.player1.weapon.atk) else: boardstate.append(0) boardstate.append(0) # Player 2 Weapon if self.game.player2.weapon is not None: # Player 2 Weapon Health boardstate.append(self.game.player2.weapon.health_attribute) # Player 2 Weapon Attack boardstate.append(self.game.player2.weapon.atk) else: boardstate.append(0) boardstate.append(0) # Player 2 HAND for index in range(10): if (self.game.player2.hand.__len__() > index): # Card ID boardstate.append( sorted(cards.db).index(self.game.player2.hand[index].id)) # Card Type boardstate.append(int(self.game.player2.hand[index].data.type)) # Mana Cost boardstate.append(self.game.player2.hand[index].data.cost) if self.game.player2.hand[index].data.type is ( CardType.MINION or CardType.WEAPON): # Card ATK boardstate.append(self.game.player2.hand[index].data.atk) # Card HEALTH boardstate.append( self.game.player2.hand[index].data.health) else: boardstate.append(0) boardstate.append(0) else: for i in range(5): boardstate.append(0) # Boardtate Player 2 Side for index in range(7): if (self.game.player2.field.__len__() > index): # Card ID boardstate.append( sorted(cards.db).index(self.game.player2.field[index].id)) # Minion ATK boardstate.append(self.game.player2.field[index].atk) # Minion Health boardstate.append(self.game.player2.field[index].health) # Minion CanAttack if self.game.player2.field[index].can_attack(): boardstate.append(1) else: boardstate.append(0) else: for i in range(4): boardstate.append(0) # Boardtate Player 1 Side for index in range(7): if (self.game.player1.field.__len__() > index): # Card ID boardstate.append( sorted(cards.db).index(self.game.player1.field[index].id)) # Minion ATK boardstate.append(self.game.player1.field[index].atk) # Minion Health boardstate.append(self.game.player1.field[index].health) else: for i in range(3): boardstate.append(0) return boardstate def play_turn_random(self): player = self.game.current_player while True: heropower = player.hero.power if heropower.is_usable() and random.random() < 0.1: if heropower.requires_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.1: target = None if card.must_choose_one: card = random.choice(card.choose_cards) if card.requires_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)) break self.game.end_turn() return game def play_turn_untrained_network(self): while True: action = random.randrange(0, 34, 1) if action is not None: player = self.game.current_player if action is 0: self.game.end_turn() return elif action is 1: if player.hero.can_attack(): player.hero.attack( target=random.choice(player.hero.targets)) elif action is 2: heropower = player.hero.power if heropower.is_usable(): if heropower.requires_target(): heropower.use( target=random.choice(heropower.targets)) else: heropower.use() elif action is 3: # find the coin and play it for card in player.hand: if card.data.id == THE_COIN and card.is_playable(): card.play() else: to_play = self.draft_mage()[action - 4] for card in player.hand: if card.id == to_play and card.is_playable(): target = None if card.must_choose_one: card = random.choice(card.choose_cards) if card.requires_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) break for minion in player.field: if minion.id == to_play and minion.can_attack(): target = None minion.attack( target=random.choice(minion.attack_targets)) if self.check_remaining_actions(): return def check_remaining_actions(self): player = self.game.current_player # check if there are any more possible actions heropower = player.hero.power if heropower.is_usable(): return False # iterate over our hand and play whatever is playable for card in player.hand: if card.is_playable(): return False # Randomly attack with whatever can attack for character in player.characters: if character.can_attack(): return False # NO MORE ACTIONS POSSIBLE - end turn self.game.end_turn() return True def get_action_meanings(self): strings = list() strings.append("END_TURN") strings.append("HERO") strings.append("HERO_POWER") strings.append("THE_COIN") for card in self.draft_mage(): strings.append(Card(card).data.name) return strings 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() def step(self, action, targeting_agent, learn_to_play_cards): if self.game.ended: if learn_to_play_cards: return self.create_board_state(), 0, self.is_game_over() else: return self.create_board_state(), self.calculate_reward( ), self.is_game_over() if self.game.current_player is not self.game.player2: self.play_turn_untrained_network() if learn_to_play_cards: return self.create_board_state(), 0, self.is_game_over() else: return self.create_board_state(), self.calculate_reward( ), self.is_game_over() if action is not None: player = self.game.current_player if action is 0: self.game.end_turn() if learn_to_play_cards: return self.create_board_state(), 0, self.is_game_over() else: return self.create_board_state(), self.calculate_reward( ), self.is_game_over() elif action is 1: if player.hero.can_attack(): targeting_agent.run(action, self.new_game) self.new_game = False self.check_remaining_actions() if learn_to_play_cards: return self.create_board_state(), 0, self.is_game_over( ) else: return self.create_board_state( ), self.calculate_reward(), self.is_game_over() if learn_to_play_cards: self.game.end_turn() return self.create_board_state(), 0, self.is_game_over() else: return self.create_board_state( ), self.calculate_reward() - 100, self.is_game_over() elif action is 2: heropower = player.hero.power if heropower.is_usable(): if heropower.requires_target(): #targeting_agent.run(action, self.new_game) heropower.play(target=random.choice(heropower.targets)) self.new_game = False self.check_remaining_actions() if learn_to_play_cards: return self.create_board_state( ), 1, self.is_game_over() else: return self.create_board_state( ), self.calculate_reward(), self.is_game_over() else: heropower.use() self.check_remaining_actions() if learn_to_play_cards: return self.create_board_state( ), 1, self.is_game_over() else: return self.create_board_state( ), self.calculate_reward(), self.is_game_over() if learn_to_play_cards: self.game.end_turn() return self.create_board_state(), 0, self.is_game_over() else: return self.create_board_state( ), self.calculate_reward() - 100, self.is_game_over() elif action is 3: # find the coin and play it for card in player.hand: if card.data.id == THE_COIN and card.is_playable(): card.play() self.check_remaining_actions() if learn_to_play_cards: return self.create_board_state( ), 1, self.is_game_over() else: return self.create_board_state( ), self.calculate_reward(), self.is_game_over() if learn_to_play_cards: self.game.end_turn() return self.create_board_state(), 0, self.is_game_over( ) else: return self.create_board_state( ), self.calculate_reward() - 100, self.is_game_over() else: to_play = self.draft_mage()[action - 4] for card in player.hand: if card.id == to_play and card.is_playable(): target = None if card.must_choose_one: card = random.choice(card.choose_cards) if card.requires_target(): #targeting_agent.run(action, self.new_game) card.play(target=random.choice(card.targets)) self.new_game = False if player.choice: choice = random.choice(player.choice.cards) print("Choosing card %r" % (choice)) player.choice.choose(choice) self.check_remaining_actions() if learn_to_play_cards: return self.create_board_state( ), 1, self.is_game_over() else: return self.create_board_state( ), self.calculate_reward(), self.is_game_over( ) else: card.play(target=target) print("Playing %r on %r" % (card, target)) if player.choice: choice = random.choice(player.choice.cards) print("Choosing card %r" % (choice)) player.choice.choose(choice) self.check_remaining_actions() if learn_to_play_cards: return self.create_board_state( ), 1, self.is_game_over() else: return self.create_board_state( ), self.calculate_reward(), self.is_game_over( ) for minion in player.field: if minion.id == to_play and minion.can_attack(): #targeting_agent.run(action, self.new_game) minion.attack(random.choice(minion.targets)) self.new_game = False self.check_remaining_actions() if learn_to_play_cards: return self.create_board_state( ), 1, self.is_game_over() else: return self.create_board_state( ), self.calculate_reward(), self.is_game_over() if learn_to_play_cards: self.game.end_turn() return self.create_board_state(), 0, self.is_game_over() else: return self.create_board_state( ), self.calculate_reward() - 100, self.is_game_over() if self.game.ended: if learn_to_play_cards: self.game.end_turn() return self.create_board_state(), 0, self.is_game_over() else: return self.create_board_state(), self.calculate_reward( ), self.is_game_over() #If there are no more actions pass the turn self.check_remaining_actions() if learn_to_play_cards: self.game.end_turn() return self.create_board_state(), 0, self.is_game_over() else: return self.create_board_state(), self.calculate_reward( ), self.is_game_over() def calculate_reward(self): reward = 0 reward += self.game.player2.hero.health reward += self.game.player2.hero.armor reward += self.game.player2.hero.atk if self.game.player2.weapon is not None: reward += self.game.player2.weapon.health reward += self.game.player2.weapon.atk reward -= self.game.player1.hero.health reward -= self.game.player1.hero.armor reward -= self.game.player1.hero.atk if self.game.player1.weapon is not None: reward -= self.game.player1.weapon.health reward -= self.game.player1.weapon.atk for minion in self.game.player2.field: reward += minion.health reward += minion.atk for minion in self.game.player1.field: reward -= minion.health reward -= minion.atk return reward def is_game_over(self): return self.game.ended def render(self): """ TODO: ADD RENDERING """ self.renderer.render_board_state(game=self.game) def get_lives(self): return self.game.player1.hero.health def get_output_space(self): return 34