コード例 #1
0
 def __init__(self, pokedata):
     self.log = SimulatorLog()
     self.smogon_data = pokedata.smogon_data
     self.pokedata = pokedata
     for move_name, move in MOVES.items():
         move.pokedata = pokedata
     self.score = 0
     self.total = 0
     self.latest_turn = None
コード例 #2
0
 def play_game(self, challenge=None):
     self.state.update_state("status", "finding_game")
     self.logger.info("Finding a game...")
     self.selenium.screenshot('log.png')
     tier_click = False
     while not tier_click:
         try:
             self.selenium.choose_tier()
             self.selenium.screenshot('log.png')
             if challenge:
                 self.selenium.start_challenge_battle(challenge)
             else:
                 self.selenium.start_ladder_battle()
             self.selenium.screenshot('log.png')
             tier_click = True
         except TierException:
             self.logger.warning("Unable to click tier. Trying again...")
         self.selenium.screenshot('log.png')
         self.battle_url = self.selenium.driver.current_url
         self.selenium.screenshot('log.png')
         self.logger.info("Found game: %s", self.battle_url)
         self.state.update_state("status", "in_battle")
         self.state.update_state("battle_url", self.battle_url)
         #self.update_monitor()
         self.selenium.wait_for_move()
         #self.selenium.chat("gl hf!")
         self.selenium.switch_initial(0, 0)
         self.selenium.screenshot('log.png')
         gamestate = self.create_initial_gamestate()
         gamestate = self.update_latest_turn(gamestate)
         log = SimulatorLog.parse(self.selenium.get_log())
         over, _ = log.is_over()
         while not over:
             print(
                 "=========================================================================================="
             )
             print("My primary:", gamestate.get_team(0).primary())
             print("Their primary:", gamestate.get_team(1).primary())
             print("Their moves: ",
                   gamestate.get_team(1).primary().moveset.moves)
             print("Their item: ", gamestate.get_team(1).primary().item)
             print("Their ability: ",
                   gamestate.get_team(1).primary().ability)
             move = self.agent.get_action(gamestate, 0)
             print("My move:", move)
             if move.is_switch():
                 self.selenium.switch(move.switch_index, move.backup_switch)
             else:
                 print(move.move_index)
                 self.selenium.move(move.move_index,
                                    move.backup_switch,
                                    mega=move.mega,
                                    volt_turn=move.volt_turn)
             gamestate = self.update_latest_turn(gamestate)
             gamestate = self.correct_gamestate(gamestate)
             self.selenium.screenshot('log.png')
     self.state.delete_state("battle_url")
コード例 #3
0
ファイル: simulator.py プロジェクト: smurching/pokemon_ai
 def __init__(self, pokedata):
     self.log = SimulatorLog()
     self.smogon_data = pokedata.smogon_data
     self.pokedata = pokedata
     for move_name, move in MOVES.items():
         move.pokedata = pokedata
     self.score = 0
     self.total = 0
     self.latest_turn = []
コード例 #4
0
class Simulator():
    def __init__(self, pokedata):
        self.log = SimulatorLog()
        self.smogon_data = pokedata.smogon_data
        self.pokedata = pokedata
        for move_name, move in MOVES.items():
            move.pokedata = pokedata
        self.score = 0
        self.total = 0
        self.latest_turn = None

    def append_log(self, gamestate, lines, my_poke=None, opp_poke=None):
        self.latest_turn = []
        for line in lines:
            event = self.log.add_event(line,
                                       my_poke=my_poke,
                                       opp_poke=opp_poke)
            if not event:
                continue
            self.latest_turn.append(event)
            self.handle_event(gamestate, event)

    def handle_event(self, gamestate, event):
        def get_pokemon(team, name):
            for poke in team:
                if poke.name == name:
                    return poke

        def get_mega_item(name):
            for item, (premega, mega) in MEGA_ITEMS.items():
                if mega == name:
                    return item

        player = event.player
        type = event.type
        team = gamestate.get_team(player)
        poke = get_pokemon(team, event.poke)
        if poke == None:
            print(event.poke)
        opp_poke = gamestate.get_team(1 - player).primary()

        if type == "faint":
            poke.health = 0
            poke.alive = False
            print("%s fainted." % (poke))
        elif type == "mega_evolve":
            poke.item = get_mega_item(event.details['mega'])
            team = gamestate.get_team(player)
            team.poke_list[team.primary_poke] = poke.mega_evolve(self.pokedata)
            print("%s mega evolved!" % (poke))
        elif type == "damage":
            hp = poke.final_stats['hp']
            poke.damage(event.details['damage'] / 100 * hp)
            print("%s got damaged: %f" % (poke, event.details['damage']))
        elif type == "move":
            print("%s used %s." % (poke, event.details['move']))
            if event.details['move'] == "Relic Song":
                my_poke = gamestate.get_team(player).primary()
                my_poke.meloetta_evolve()
            if player == 1:
                move = event.details['move']
                poke_name = correct_mega(poke.name)
                if move in MOVE_CORRECTIONS:
                    move = MOVE_CORRECTIONS[move]
                if move == "Hidden Power":
                    hidden_power = get_hidden_power(poke_name,
                                                    self.smogon_data)
                    if hidden_power:
                        move = hidden_power
                    else:
                        return
                known_moves = poke.moveset.known_moves
                if move not in known_moves:
                    self.total += 1
                    old_guess_moves = [
                        x[0] for x in poke.predict_moves(known_moves)
                    ][:4 - len(known_moves)]
                    if move in old_guess_moves:
                        self.score += 1
                    known_moves.append(move)
                    guess_moves = [
                        x[0] for x in poke.predict_moves(known_moves)
                        if x[0] not in known_moves
                    ][:4 - len(known_moves)]
                    poke.moveset.moves = poke.moveset.known_moves + guess_moves
            if player == 0:
                my_poke = gamestate.get_team(player).primary()
                my_poke.last_move = event.details['move']

            if poke.item in ["Choice Scarf", "Choice Specs", "Choice Band"]:
                moves = poke.moveset.moves
                try:
                    moves.index(event.details['move'])
                    poke.choiced = True
                    poke.move_choice = event.details['move']
                    print("%s is choiced to %s" %
                          (poke, event.details['move']))
                except:
                    pass

        elif type == "stat_change":
            stages = event.details['stages']
            if stages > 0:
                poke.increase_stage(event.details['stat'], abs(stages))
                print("%s increased its %s by %d stages" %
                      (poke, event.details['stat'], stages))
            else:
                poke.decrease_stage(event.details['stat'], abs(stages))
                print("%s decreased its %s by %d stages" %
                      (poke, event.details['stat'], stages))
        elif type == "switch":
            if poke == "Meloetta":
                poke.meloetta_reset()
            team.set_primary(team.poke_list.index(poke))
            print("Player %d switched in %s" % (player, poke))
        elif type == "regain_health":
            poke.heal(0.5)
            print("%s regained health" % poke)
        elif type == "leftovers":
            poke.item = "Leftovers"
            poke.heal(1.0 / 16)
            print("%s regained health due to leftovers" % poke)
        elif type == "life_orb":
            poke.item = "Life Orb"
            poke.damage_percent(1.0 / 10)
        elif type == "leech_seed":
            damage = poke.damage_percent(1.0 / 8)
            opp_poke.heal(damage)
            print("%s was sapped and %s gained health due to leech seed." %
                  (poke, opp_poke))
        elif type == "rocks":
            gamestate.set_rocks(player, True)
            print("Player %u got rocked!" % player)
        elif type == "spikes":
            gamestate.spikes[player] += 1
            print("Player %u now has %d spikes!" %
                  (player, gamestate.spikes[player]))
        elif type == "rocks_gone":
            gamestate.set_rocks(player, False)
            print("Player %u's rocks disappeared!" % player)
        elif type == "burn":
            poke.set_status("burn")
        elif type == "paralyze":
            poke.set_status("paralyze")
            print("%s got burned!" % poke)
        elif type == "hurt_burn":
            poke.damage_percent(1.0 / 8)
            print("%s got hurt due to its burn!" % poke)
        elif type == "float_balloon":
            poke.item = "Air Balloon"
            print("%s has an air balloon!" % poke)
        elif type == "pop_balloon":
            poke.item = None
            print("%s's air balloon was popped!" % poke)
        elif type == "new_item":
            poke.item = event.details['item']
            print("%s got a %s" % (poke, event.details['item']))
        elif type == "lost_item":
            poke.item = None
            poke.choiced = False
            print("%s lost its item!" % poke)
        elif type == "belly_drum":
            poke.increase_stage('patk', 9999)
        elif type == "mold_breaker":
            poke.ability = "Mold Breaker"
            print("%s has mold breaker!" % poke)
        elif type == "disabled":
            move = event.details['move']
            poke.disabled = move
            print("%s has mold breaker!" % poke)
        elif type == "taunt":
            poke.set_taunt(True)
            print("%s just got taunted!" % poke)
        elif type == "encore":
            poke.set_encore(True)
            print("%s just got encored!" % poke)

    def get_first(self, gamestate, moves, who=0, log=False):
        my_move = moves[who]
        opp_move = moves[1 - who]

        my_team = gamestate.get_team(who)
        opp_team = gamestate.get_team(1 - who)

        my_poke = my_team.primary()
        opp_poke = opp_team.primary()

        my_speed = my_poke.get_stage('spe')
        opp_speed = opp_poke.get_stage('spe')

        my_spe_buffs = 1.0 + 0.5 * abs(my_speed)
        opp_spe_buffs = 1.0 + 0.5 * abs(opp_speed)

        my_spe_multiplier = my_spe_buffs if my_speed > 0 else 1 / my_spe_buffs
        opp_spe_multiplier = opp_spe_buffs if opp_speed > 0 else 1 / opp_spe_buffs

        if my_poke.item == "Choice Scarf":
            my_spe_multiplier *= 1.5
        if opp_poke.item == "Choice Scarf":
            opp_spe_multiplier *= 1.5

        my_paralyze = 0.25 if my_poke.status == "paralyze" else 1.0
        opp_paralyze = 0.25 if opp_poke.status == "paralyze" else 1.0

        my_final_speed = my_poke.get_stat(
            "spe") * my_spe_multiplier * my_paralyze
        opp_final_speed = opp_poke.get_stat(
            "spe") * opp_spe_multiplier * opp_paralyze

        if my_poke.ability == "Gale Wings":
            if my_move.type == "Flying":
                my_move.priority += 1
        if opp_poke.ability == "Gale Wings":
            if opp_move.type == "Flying":
                opp_move.priority += 1
        if my_poke.ability == "Prankster":
            if my_move.category != "Physical" and my_move.category != "Special":
                my_move.priority += 1
        if opp_poke.ability == "Prankster":
            if opp_move.category != "Physical" and opp_move.category != "Special":
                opp_move.priority += 1

        first = None
        if my_move.priority > opp_move.priority:
            first = who
        elif opp_move.priority > my_move.priority:
            first = 1 - who
        else:
            if my_final_speed > opp_final_speed:
                first = who
            elif opp_final_speed > my_final_speed:
                first = 1 - who
            else:
                first = 1
        return first

    def simulate(self, gamestate, actions, who, log=False):
        assert not gamestate.is_over()
        my_team = gamestate.get_team(who)
        opp_team = gamestate.get_team(1 - who)
        my_poke = my_team.primary()
        opp_poke = opp_team.primary()
        gamestate = gamestate.deep_copy()
        my_action = actions[who]
        opp_action = actions[1 - who]
        if my_action.is_switch():
            gamestate.switch_pokemon(my_action.switch_index, who, log=log)
            my_move = MOVES["Noop"]
            my_poke = my_team.primary()
        if opp_action.is_switch():
            gamestate.switch_pokemon(opp_action.switch_index, 1 - who, log=log)
            opp_move = MOVES["Noop"]
            opp_poke = opp_team.primary()

        if my_action.is_move():
            my_move = get_move(my_poke.moveset.moves[my_action.move_index])
        if opp_action.is_move():
            opp_move = get_move(opp_poke.moveset.moves[opp_action.move_index])

        moves = [None, None]
        moves[who] = my_move
        moves[1 - who] = opp_move

        first = self.get_first(gamestate, moves, who)

        self.make_move(gamestate, moves, actions, first, who, log=log)
        return gamestate

    def make_move(self, gamestate, moves, actions, first, who, log=False):

        for i in [first, 1 - first]:
            team = gamestate.get_team(i)
            action = actions[i]
            if action.mega:
                team.poke_list[team.primary_poke] = team.primary().mega_evolve(
                    self.pokedata, log=log)
                gamestate.switch_pokemon(team.primary_poke,
                                         i,
                                         log=log,
                                         hazards=False)

        for i in [first, 1 - first]:
            team = gamestate.get_team(i)
            other_team = gamestate.get_team(1 - i)

            move = moves[i]
            action = actions[i]
            other_action = actions[1 - i]
            damage = move.handle(gamestate, i, log=log)
            if log:
                print("%s used %s and dealt %u damage." %
                      (team.primary(), move.name, damage))
            if damage > 0 and other_team.primary().item == "Air Balloon":
                other_team.primary().item = None
            if damage > 0 and move.name in ["U-turn", "Volt Switch"
                                            ] and action.volt_turn is not None:
                gamestate.switch_pokemon(action.volt_turn, i, log=log)

            if other_team.primary().health == 0:
                other_team.primary().alive = False
                if log:
                    print("%s fainted." % other_team.primary())

            if gamestate.is_over():
                return

            if not other_team.primary().alive:
                gamestate.switch_pokemon(other_action.backup_switch,
                                         1 - i,
                                         log=log)
                break
コード例 #5
0
ファイル: simulator.py プロジェクト: smurching/pokemon_ai
class Simulator():

    def __init__(self, pokedata):
        self.log = SimulatorLog()
        self.smogon_data = pokedata.smogon_data
        self.pokedata = pokedata
        for move_name, move in MOVES.items():
            move.pokedata = pokedata
        self.score = 0
        self.total = 0
        self.latest_turn = []

    def append_log(self, gamestate, lines, my_poke=None, opp_poke=None):
        self.latest_turn = []
        for line in lines:
            event = self.log.add_event(line, my_poke=my_poke, opp_poke=opp_poke)
            if not event:
                continue
            self.latest_turn.append(event)
            self.handle_event(gamestate, event)

    def handle_event(self, gamestate, event):
        def get_pokemon(team, name):
            for poke in team:
                if poke.name == name:
                    return poke
        def get_mega_item(name):
            for item, (premega, mega) in MEGA_ITEMS.items():
                if mega == name:
                    return item

        player = event.player
        type = event.type
        team = gamestate.get_team(player)
        poke = get_pokemon(team, event.poke)
        opp_poke = gamestate.get_team(1 - player).primary()

        if type == "faint":
            poke.health = 0
            poke.alive = False
            # print "%s fainted." % (poke)
        elif type == "mega_item":
            poke.item = event.details['item']
            team = gamestate.get_team(player)
            team.poke_list[team.primary_poke] = poke.mega_evolve(self.pokedata)
        elif type == "damage":
            hp = poke.final_stats['hp']
            poke.damage(event.details['damage'] / 100 * hp)
            # print "%s got damaged: %f" % (poke, event.details['damage'])
        elif type == "move":
            # print "%s used %s." % (poke, event.details['move'])
            poke.last_move = event.details['move']
            if event.details['move'] == "Relic Song":
                my_poke = gamestate.get_team(player).primary()
                my_poke.meloetta_evolve()
            move = event.details['move']
            poke_name = correct_mega(poke.name)
            if move in MOVE_CORRECTIONS:
                # print move
                move = MOVE_CORRECTIONS[move]
                # print move
            if move == "Hidden Power":
                hidden_power = get_hidden_power(poke_name, self.smogon_data)
                if hidden_power:
                    move = hidden_power
                else:
                    return
            if move != None and move not in poke.moveset.known_moves:
                #self.total += 1
                #old_guess_moves = [x[0] for x in poke.predict_moves(poke.moveset.known_moves)][:4 - len(poke.moveset.known_moves)]
                #if move in old_guess_moves:
                #    self.score += 1
                poke.moveset.known_moves.append(move)
                #guess_moves = [x[0] for x in poke.predict_moves(poke.moveset.known_moves) if x[0] not in poke.moveset.known_moves][:4 - len(poke.moveset.known_moves)]
                # poke.moveset.moves = poke.moveset.known_moves + guess_moves

            if poke.item in ["Choice Scarf", "Choice Specs", "Choice Band"]:
                moves = poke.moveset.known_moves
                try:
                    moves.index(event.details['move'])
                    poke.choiced = True
                    poke.move_choice = event.details['move']
                    # print "%s is choiced to %s" % (poke, event.details['move'])
                except:
                    pass

        elif type == "stat_change":
            stages = event.details['stages']
            if stages > 0:
                poke.increase_stage(event.details['stat'], abs(stages))
                # print "%s increased its %s by %d stages" % (poke, event.details['stat'], stages)
            else:
                poke.decrease_stage(event.details['stat'], abs(stages))
                # print "%s decreased its %s by %d stages" % (poke, event.details['stat'], stages)
        elif type == "switch":
            #if poke == "Meloetta":
            #    poke.meloetta_reset()
            #team.set_primary(team.poke_list.index(poke))
            gamestate.switch_pokemon(team.poke_list.index(poke), player, log=True)
            # print "Player %d switched in %s" % (player, poke)
        elif type == "regain_health":
            poke.heal(0.5)
            # print "%s regained health" % poke
        elif type == "leftovers":
            poke.item = "Leftovers"
            poke.heal(1.0 / 16)
            # print "%s regained health due to leftovers" % poke
        elif type == "life_orb":
            poke.item = "Life Orb"
            poke.damage_percent(1.0/10)
        elif type == "leech_seed":
            damage = poke.damage_percent(1.0 / 8)
            opp_poke.heal(damage)
            # print "%s was sapped and %s gained health due to leech seed." % (poke, opp_poke)
        elif type == "rocks":
            gamestate.set_rocks(player, True)
            # print "Player %u got rocked!" % player
        elif type == "spikes":
            gamestate.spikes[player] += 1
            # print "Player %u now has %d spikes!" % (player, gamestate.spikes[player])
        elif type == "rocks_gone":
            gamestate.set_rocks(player, False)
            # print "Player %u's rocks disappeared!" % player
        elif type == "burn":
            poke.set_status("burn")
        elif type == "paralyze":
            poke.set_status("paralyze")
            # print "%s got burned!" % poke
        elif type == "hurt_burn":
            poke.damage_percent(1.0 / 8)
            # print "%s got hurt due to its burn!" % poke
        elif type == "float_balloon":
            poke.item = "Air Balloon"
            # print "%s has an air balloon!" % poke
        elif type == "pop_balloon":
            poke.item = None
            # print "%s's air balloon was popped!" % poke
        elif type == "new_item":
            poke.item = event.details['item']
            # print "%s got a %s" % (poke, event.details['item'])
        elif type == "lost_item":
            poke.item = None
            poke.choiced = False
            # print "%s lost its item!" % poke
        elif type == "belly_drum":
            poke.increase_stage('patk', 9999)
        elif type == "mold_breaker":
            poke.ability = "Mold Breaker"
            # print "%s has mold breaker!" % poke
        elif type == "disabled":
            move = event.details['move']
            poke.disabled = move
            # print "%s has mold breaker!" % poke
        elif type == "taunt":
            poke.set_taunt(True)
            # print "%s just got taunted!" % poke
        elif type == "encore":
            poke.set_encore(True)
            # print "%s just got encored!" % poke


    def get_first(self, gamestate, moves, who=0, log=False):
        my_move = moves[who]
        opp_move = moves[1 - who]

        my_team = gamestate.get_team(who)
        opp_team = gamestate.get_team(1 - who)

        my_poke = my_team.primary()
        opp_poke = opp_team.primary()

        my_speed = my_poke.get_stage('spe')
        opp_speed = opp_poke.get_stage('spe')

        my_spe_buffs = 1.0 + 0.5 * abs(my_speed)
        opp_spe_buffs = 1.0 + 0.5 * abs(opp_speed)

        my_spe_multiplier = my_spe_buffs if my_speed > 0 else 1 / my_spe_buffs
        opp_spe_multiplier = opp_spe_buffs if opp_speed > 0 else 1 / opp_spe_buffs

        if my_poke.item == "Choice Scarf":
            my_spe_multiplier *= 1.5
        if opp_poke.item == "Choice Scarf":
            opp_spe_multiplier *= 1.5

        my_paralyze = 0.25 if my_poke.status == "paralyze" else 1.0
        opp_paralyze = 0.25 if opp_poke.status == "paralyze" else 1.0

        my_final_speed = my_poke.get_stat("spe") * my_spe_multiplier * my_paralyze
        opp_final_speed = opp_poke.get_stat("spe") * opp_spe_multiplier * opp_paralyze

        if my_poke.ability == "Gale Wings":
            if my_move.type == "Flying":
                my_move.priority += 1
        if opp_poke.ability == "Gale Wings":
            if opp_move.type == "Flying":
                opp_move.priority += 1
        if my_poke.ability == "Prankster":
            if my_move.category != "Physical" and my_move.category != "Special":
                my_move.priority += 1
        if opp_poke.ability == "Prankster":
            if opp_move.category != "Physical" and opp_move.category != "Special":
                opp_move.priority += 1

        first = None
        if my_move.priority > opp_move.priority:
            first = who
        elif opp_move.priority > my_move.priority:
            first = 1 - who
        else:
            if my_final_speed > opp_final_speed:
                first = who
            elif opp_final_speed > my_final_speed:
                first = 1 - who
            else:
                first = 1
        return first

    def simulate(self, gamestate, actions, who, log=False, add_action=False, deep_copy=True):
        assert not gamestate.is_over()
        my_team = gamestate.get_team(who)
        opp_team = gamestate.get_team(1 - who)
        my_poke = my_team.primary()
        opp_poke = opp_team.primary()
        if deep_copy:
            gamestate = gamestate.deep_copy()
        my_action = actions[who]
        opp_action = actions[1 - who]

        if my_action.is_switch():
            gamestate.switch_pokemon(my_action.switch_index, who, log=log)
            my_move = MOVES["Noop"]
            my_poke = my_team.primary()
        if opp_action.is_switch():
            gamestate.switch_pokemon(opp_action.switch_index, 1 - who, log=log)
            opp_move = MOVES["Noop"]
            opp_poke = opp_team.primary()

        if my_action.is_move():
            if not my_action.move_name is None:
                move_name = my_action.move_name
            elif my_action.move_index != -1:
                move_name = my_poke.moveset.known_moves[my_action.move_index]
            else:
                move_name = my_poke.moveset.known_moves[0]
            if add_action and not move_name in my_poke.moveset.known_moves:
                my_poke.moveset.known_moves.append(move_name)
            my_move = get_move(move_name)
        if opp_action.is_move():
            if not opp_action.move_name is None:
                move_name = opp_action.move_name
            elif opp_action.move_index != -1:
                move_name = opp_poke.moveset.known_moves[opp_action.move_index]
            else:
                move_name = opp_poke.moveset.known_moves[0]
            if add_action and not move_name in opp_poke.moveset.known_moves:
                opp_poke.moveset.known_moves.append(move_name)
            opp_move = get_move(move_name)

        moves = [None, None]
        moves[who] = my_move
        moves[1 - who] = opp_move

        first = self.get_first(gamestate, moves, who)

        self.make_move(gamestate, moves, actions, first, who, log=log)
        return gamestate

    def make_move(self, gamestate, moves, actions, first, who, log=False):

        for i in [first, 1 - first]:
            team = gamestate.get_team(i)
            action = actions[i]
            if action.mega:
                team.poke_list[team.primary_poke] = team.primary().mega_evolve(self.pokedata, log=log)
                gamestate.switch_pokemon(team.primary_poke, i, log=log, hazards=False)

        for i in [first, 1 - first]:
            team = gamestate.get_team(i)
            other_team = gamestate.get_team(1 - i)

            move = moves[i]
            action = actions[i]
            other_action = actions[1 - i]
            damage = move.handle(gamestate, i, log=log)
            if log:
                pass
                # print ("%s used %s and dealt %u damage." % (
                #     team.primary(),
                #     move.name,
                #     damage
                # ))
            if damage > 0 and other_team.primary().item == "Air Balloon":
                other_team.primary().item = None
            if damage > 0 and move.name in ["U-turn", "Volt Switch"] and action.volt_turn is not None:
                gamestate.switch_pokemon(action.volt_turn, i, log=log)

            if other_team.primary().health == 0:
                other_team.primary().alive = False
                if log:
                    pass
                    # print (
                    #     "%s fainted." % other_team.primary()
                    # )

            if gamestate.is_over():
                return

            if not other_team.primary().alive:
                gamestate.switch_pokemon(other_action.backup_switch, 1 - i, log=log)
                break
コード例 #6
0
ファイル: showdown.py プロジェクト: AM22/Pokemon-AI
    def create_initial_gamestate(self):
        self.logger.info("Creating initial gamestate...")
        my_pokes = self.my_team.copy()
        for i, poke in enumerate(my_pokes.poke_list):
            poke_name = poke.name
            if poke_name in NAME_CORRECTIONS:
                poke_name = NAME_CORRECTIONS[poke_name]
            poke.health = poke.final_stats['hp']
            poke.alive = True
        opp_poke_list = []
        log = SimulatorLog.parse(self.selenium.get_log())
        for event in log.events:
            if event.type == "team" and event.details[
                    'username'] != self.username:
                opp_poke_names = event.details['team']
        for name in opp_poke_names:
            if not name:
                continue
            poke_name = correct_name(name)
            "Corrected to:", poke_name
            if poke_name in self.smogon_data:
                moveset = [
                    m for m in self.smogon_data[poke_name].movesets
                    if 'Overused' == m['tag'] or 'Underused' == m['tag']
                    or 'Rarelyused' == m['tag'] or 'Neverused' == m['tag']
                    or 'Unreleased' == m['tag'] or 'Ubers' == m['tag']
                    or 'PU' in m['tag']
                ]
                if len(moveset) > 1:
                    moveset = SmogonMoveset.from_dict(moveset[1])
                elif len(moveset) == 1:
                    moveset = SmogonMoveset.from_dict(moveset[0])
                else:
                    moveset = [
                        m for m in self.smogon_bw_data[poke_name].movesets
                        if 'Overused' == m['tag'] or 'Underused' == m['tag']
                        or 'Rarelyused' == m['tag'] or 'Neverused' == m['tag']
                        or 'Unreleased' == m['tag'] or 'Ubers' == m['tag']
                        or 'PU' in m['tag']
                    ]
                    moveset = SmogonMoveset.from_dict(moveset[0])
            elif poke_name not in self.smogon_data and poke_name in self.smogon_bw_data:
                moveset = [
                    m for m in self.smogon_bw_data[poke_name].movesets
                    if 'Overused' == m['tag'] or 'Underused' == m['tag']
                    or 'Rarelyused' == m['tag'] or 'Neverused' == m['tag']
                    or 'Unreleased' == m['tag'] or 'Ubers' == m['tag']
                    or 'PU' in m['tag']
                ]
                moveset = SmogonMoveset.from_dict(moveset[0])
            else:
                moveset = SmogonMoveset(
                    None, None, None, {
                        'hp': 88,
                        'patk': 84,
                        'pdef': 84,
                        'spatk': 84,
                        'spdef': 84,
                        'spe': 84
                    }, {
                        'hp': 1.0,
                        'patk': 1.0,
                        'pdef': 1.0,
                        'spatk': 1.0,
                        'spdef': 1.0,
                        'spe': 1.0
                    }, None, 'ou')
            moveset.moves = None
            if poke_name in self.smogon_data:
                typing = self.smogon_data[poke_name].typing
                stats = self.smogon_data[poke_name].stats
            elif poke_name not in self.smogon_data and poke_name in self.smogon_bw_data:
                typing = self.smogon_bw_data[poke_name].typing
                stats = self.smogon_bw_data[poke_name].stats
            else:
                typing = ['Normal']
                stats = {
                    'hp': 80,
                    'patk': 80,
                    'pdef': 80,
                    'spatk': 80,
                    'spdef': 80,
                    'spe': 80
                }
            predictor = create_predictor(self.predictor_name, name,
                                         self.pokedata)
            poke = Pokemon(name,
                           typing,
                           stats,
                           moveset,
                           predictor,
                           calculate=True)
            moves = [x[0] for x in poke.predict_moves([])]
            poke.moveset.moves = moves[:4]
            poke.health = poke.final_stats['hp']
            poke.alive = True
            opp_poke_list.append(poke)
        my_primary = None
        for event in log.events:
            if event.type == "switch" and event.player == 0:
                for poke in my_pokes.poke_list:
                    if poke.name == event.poke:
                        my_primary = my_pokes.poke_list.index(poke)
            elif event.type == "switch" and event.player == 1:
                for poke in opp_poke_list:
                    if poke.name == event.poke:
                        opp_primary = opp_poke_list.index(poke)

        assert my_primary != None
        self.opp_team = Team(opp_poke_list)
        opp_pokes = self.opp_team.copy()
        my_pokes.primary_poke = my_primary
        opp_pokes.primary_poke = opp_primary

        gamestate = GameState([my_pokes, opp_pokes])
        return gamestate
コード例 #7
0
ファイル: showdown.py プロジェクト: AM22/Pokemon-AI
    def run(self, num_games=1, challenge=None):
        self.state.update_state("status", "initializing_battle")
        if challenge:
            self.logger.info("Set to challenge: %s", challenge)
        else:
            self.logger.info("Set to play %u games", num_games)
        self.init()
        self.scores = {'wins': 0, 'losses': 0, 'crashes': 0}

        def signal_handler(signal, frame):
            self.update_monitor(done=True)
            sys.exit(0)

        #signal.signal(signal.SIGINT, signal_handler)
        for i in range(num_games):
            self.simulator.log.reset()
            result, error = None, None
            try:
                self.play_game(challenge=challenge)
            except GameOverException:
                log = SimulatorLog.parse(self.selenium.get_log())
                disconnected = log.disconnected()
                if disconnected:
                    over, _ = log.is_over()
                    while not over:
                        time.sleep(5)
                        over, _ = log.is_over()
                _, over_event = log.is_over()
                result = over_event.details['username'] == self.username
            except UserNotOnlineException:
                self.logger.error("User not online: %s", challenge)
                self.logger.info("Exiting...")
                return
            except:
                error = traceback.format_exc()
                print "Error", error
                log = SimulatorLog.parse(self.selenium.get_log())
                _, over_event = log.is_over()
                if over_event is not None:
                    result = over_event.details['username'] == self.username
            log = self.selenium.get_log()
            id = self.selenium.get_battle_id()
            battle_url = "http://replay.pokemonshowdown.com/battle-%s" % id
            self.logger.info("Finished game! Replay can be found at: %s",
                             battle_url)
            user_folder = Path(".") / self.username
            if not user_folder.exists():
                user_folder.mkdir()
            if not (user_folder / "wins").exists():
                (user_folder / "wins").mkdir()
            if not (user_folder / "losses").exists():
                (user_folder / "losses").mkdir()
            if not (user_folder / "crashes").exists():
                (user_folder / "crashes").mkdir()
            if result == True:
                print "---------------"
                print "Won the battle! - %s" % battle_url
                print "---------------"
                self.scores['wins'] += 1
                with open(user_folder / "wins" / ("%s.log" % id), 'w') as fp:
                    fp.write(log)
                with open(user_folder / "wins" / ("%s.score" % id), 'w') as fp:
                    print >> fp, self.simulator.score
                    print >> fp, self.simulator.total
            elif result == False:
                print "---------------"
                print "Lost the battle! - %s" % battle_url
                print "---------------"
                self.scores['losses'] += 1
                with open(user_folder / "losses" / ("%s.log" % id), 'w') as fp:
                    fp.write(log)
                with open(user_folder / "losses" / ("%s.score" % id),
                          'w') as fp:
                    print >> fp, self.simulator.score
                    print >> fp, self.simulator.total
            else:
                print "---------------"
                print "Crashed! - %s" % id
                print "---------------"
                self.scores['crashes'] += 1
                with open(user_folder / "crashes" / ("%s.log" % id),
                          'w') as fp:
                    fp.write(log)
                with open(user_folder / "crashes" / ("%s.err" % id),
                          'w') as fp:
                    fp.write(error)
                with open(user_folder / "crashes" / ("%s.score" % id),
                          'w') as fp:
                    print >> fp, self.simulator.score
                    print >> fp, self.simulator.total
            events = SimulatorLog.parse(self.selenium.get_log())
            for event in events:
                if event.type == "ladder":
                    if event.details['username'] == self.username:
                        with open(user_folder / "ladder_ratings.txt",
                                  "a") as fp:
                            fp.write(event.details['ladder'] + "\n")
            self.reset()
        self.update_monitor(done=True)
        self.selenium.close()
        self.logger.info("Done!")
コード例 #8
0
ファイル: showdown.py プロジェクト: vasumv/pokemon_ai
    def create_initial_gamestate(self):
        self.logger.info("Creating initial gamestate...")
        my_pokes = self.my_team.copy()
        for i, poke in enumerate(my_pokes.poke_list):
            poke_name = poke.name
            if poke_name in NAME_CORRECTIONS:
                poke_name = NAME_CORRECTIONS[poke_name]
            poke.health = poke.final_stats['hp']
            poke.alive = True
        opp_poke_list = []
        log = SimulatorLog.parse(self.selenium.get_log())
        for event in log.events:
            if event.type == "team" and event.details['username'] != self.username:
                opp_poke_names = event.details['team']
        for name in opp_poke_names:
            if not name:
                continue
            poke_name = correct_name(name)
            "Corrected to:", poke_name
            if poke_name in self.smogon_data:
                moveset = [m for m in self.smogon_data[poke_name].movesets if 'Overused' == m['tag'] or 'Underused' == m['tag'] or 'Rarelyused' == m['tag'] or 'Neverused' == m['tag'] or 'Unreleased' == m['tag'] or 'Ubers' == m['tag'] or 'PU' in m['tag']]
                if len(moveset) > 1:
                    moveset = SmogonMoveset.from_dict(moveset[1])
                elif len(moveset) == 1:
                    moveset = SmogonMoveset.from_dict(moveset[0])
                else:
                    moveset = [m for m in self.smogon_bw_data[poke_name].movesets if 'Overused' == m['tag'] or 'Underused' == m['tag'] or 'Rarelyused' == m['tag'] or 'Neverused' == m['tag'] or 'Unreleased' == m['tag'] or 'Ubers' == m['tag'] or 'PU' in m['tag']]
                    moveset = SmogonMoveset.from_dict(moveset[0])
            elif poke_name not in self.smogon_data and poke_name in self.smogon_bw_data:
                moveset = [m for m in self.smogon_bw_data[poke_name].movesets if 'Overused' == m['tag'] or 'Underused' == m['tag'] or 'Rarelyused' == m['tag'] or 'Neverused' == m['tag'] or 'Unreleased' == m['tag'] or 'Ubers' == m['tag'] or 'PU' in m['tag']]
                moveset = SmogonMoveset.from_dict(moveset[0])
            else:
                moveset = SmogonMoveset(None, None, None, {'hp': 88, 'patk': 84, 'pdef': 84, 'spatk': 84, 'spdef': 84, 'spe': 84}, {'hp': 1.0, 'patk': 1.0, 'pdef': 1.0, 'spatk': 1.0, 'spdef': 1.0, 'spe': 1.0}, None, 'ou')
            moveset.moves = None
            if poke_name in self.smogon_data:
                typing = self.smogon_data[poke_name].typing
                stats = self.smogon_data[poke_name].stats
            elif poke_name not in self.smogon_data and poke_name in self.smogon_bw_data:
                typing = self.smogon_bw_data[poke_name].typing
                stats = self.smogon_bw_data[poke_name].stats
            else:
                typing = ['Normal']
                stats = {'hp': 80, 'patk': 80, 'pdef': 80, 'spatk': 80, 'spdef': 80, 'spe': 80}
            predictor = create_predictor(self.predictor_name, name, self.pokedata)
            poke = Pokemon(name, typing, stats, moveset, predictor, calculate=True)
            moves = [x[0] for x in poke.predict_moves([])]
            poke.moveset.moves = moves[:4]
            poke.health = poke.final_stats['hp']
            poke.alive = True
            opp_poke_list.append(poke)
        my_primary = None
        for event in log.events:
            if event.type == "switch" and event.player == 0:
                for poke in my_pokes.poke_list:
                    if poke.name == event.poke:
                        my_primary = my_pokes.poke_list.index(poke)
            elif event.type == "switch" and event.player == 1:
                for poke in opp_poke_list:
                    if poke.name == event.poke:
                        opp_primary = opp_poke_list.index(poke)

        assert my_primary != None
        self.opp_team = Team(opp_poke_list)
        opp_pokes = self.opp_team.copy()
        my_pokes.primary_poke = my_primary
        opp_pokes.primary_poke = opp_primary

        gamestate = GameState([my_pokes, opp_pokes])
        return gamestate
コード例 #9
0
ファイル: showdown.py プロジェクト: vasumv/pokemon_ai
 def run(self, num_games=1, challenge=None):
     self.state.update_state("status", "initializing_battle")
     if challenge:
         self.logger.info("Set to challenge: %s", challenge)
     else:
         self.logger.info("Set to play %u games", num_games)
     self.init()
     self.scores = {
         'wins': 0,
         'losses': 0,
         'crashes': 0
     }
     def signal_handler(signal, frame):
         self.update_monitor(done=True)
         sys.exit(0)
     #signal.signal(signal.SIGINT, signal_handler)
     for i in range(num_games):
         self.simulator.log.reset()
         result, error = None, None
         try:
             self.play_game(challenge=challenge)
         except GameOverException:
             log = SimulatorLog.parse(self.selenium.get_log())
             disconnected = log.disconnected()
             if disconnected:
                 over,_ = log.is_over()
                 while not over:
                     time.sleep(5)
                     over,_ = log.is_over()
             _, over_event = log.is_over()
             result = over_event.details['username'] == self.username
         except UserNotOnlineException:
             self.logger.error("User not online: %s", challenge)
             self.logger.info("Exiting...")
             return
         except:
             error = traceback.format_exc()
             print "Error", error
             log = SimulatorLog.parse(self.selenium.get_log())
             _, over_event = log.is_over()
             if over_event is not None:
                 result = over_event.details['username'] == self.username
         log = self.selenium.get_log()
         id = self.selenium.get_battle_id()
         battle_url = "http://replay.pokemonshowdown.com/battle-%s" % id
         self.logger.info("Finished game! Replay can be found at: %s", battle_url)
         user_folder = Path(".") / self.username
         if not user_folder.exists():
             user_folder.mkdir()
         if not (user_folder / "wins").exists():
             (user_folder / "wins").mkdir()
         if not (user_folder / "losses").exists():
             (user_folder / "losses").mkdir()
         if not (user_folder / "crashes").exists():
             (user_folder / "crashes").mkdir()
         if result == True:
             print "---------------"
             print "Won the battle! - %s" % battle_url
             print "---------------"
             self.scores['wins'] += 1
             with open(user_folder / "wins" / ("%s.log" % id), 'w') as fp:
                 fp.write(log)
             with open(user_folder / "wins" / ("%s.score" % id), 'w') as fp:
                 print >>fp, self.simulator.score
                 print >>fp, self.simulator.total
         elif result == False:
             print "---------------"
             print "Lost the battle! - %s" % battle_url
             print "---------------"
             self.scores['losses'] += 1
             with open(user_folder / "losses" / ("%s.log" % id), 'w') as fp:
                 fp.write(log)
             with open(user_folder / "losses" / ("%s.score" % id), 'w') as fp:
                 print >>fp, self.simulator.score
                 print >>fp, self.simulator.total
         else:
             print "---------------"
             print "Crashed! - %s" % id
             print "---------------"
             self.scores['crashes'] += 1
             with open(user_folder / "crashes" / ("%s.log" % id), 'w') as fp:
                 fp.write(log)
             with open(user_folder / "crashes" / ("%s.err" % id), 'w') as fp:
                 fp.write(error)
             with open(user_folder / "crashes" / ("%s.score" % id), 'w') as fp:
                 print >>fp, self.simulator.score
                 print >>fp, self.simulator.total
         events = SimulatorLog.parse(self.selenium.get_log())
         for event in events:
             if event.type == "ladder":
                 if event.details['username'] == self.username:
                     with open(user_folder / "ladder_ratings.txt", "a") as fp:
                         fp.write(event.details['ladder'] + "\n")
         self.reset()
     self.update_monitor(done=True)
     self.selenium.close()
     self.logger.info("Done!")