def test_pokemon_capture_gen2(): """Test simulation of capture Pokémons of generation II""" pokemon = Pokemon(PokemonType.Electabuzz) catch_arr = [] HPmax = pokemon.HP hp_arr = [i for i in range(1, HPmax)] # Simulate for i in range(1, HPmax): catch_sum = 0 pokemon.HPcurrent = i for j in range(1000): a = capture_simulation_gen2(pokemon, BallType.MasterBall) catch_sum += a catch_arr.append(catch_sum/10) fig, ax = plt.subplots() fig.suptitle('Pokemon gen2 simulation', fontsize=17, fontweight='bold') ax.set_title(pokemon.name, fontsize=16) ax.plot(hp_arr, catch_arr, label="Catch Probability", color='m') ax.set_xlabel('Current HP', fontsize=15) ax.set_ylabel('Ratio', fontsize=15) legend = ax.legend() plt.show()
def teste_melhor_ataque(self): """ Vamos testar se a função melhor_ataque dá realmente o ataque com a melhor relação dano x acurácia testando todos os ataques do pokemon atacante no pokemon defensor.""" for j in range(100): # Cria um pokemon atacante e um defensor dados_atk = RandomPoke() dados_def = RandomPoke() atacante = Pokemon(dados_atk.gera()) defensor = Pokemon(dados_def.gera()) melhor = melhor_ataque(atacante, defensor) danos = [] if atacante.hp < atacante.hp_max/5: estado_critico = True else: estado_critico = False for ataque in atacante.ataques: if ataque.pp > 0 and estado_critico is False: dano = ataque.calcula_dano(atacante, defensor, is_basico=True) danos.append(dano * (ataque.acu*ataque.acu)/10000) elif ataque.pp > 0 and estado_critico is True: dano = ataque.calcula_dano(atacante, defensor, is_basico=True) # Caso não tire todo o hp, escolhe o que causa (em média) o maior # dano usando a relação dano x acurácia. if max(danos) < defensor.hp: melhor_dano = melhor.calcula_dano(atacante, defensor, is_basico=True) self.assertEqual(atacante.get_ataque(danos.index(max(danos))), melhor, 1)
def create_entry(self): trainer_name = input('What is your name? ') trainer_age = input('How old are you? ') trainer_city = input('What city are you from? ') trainer = Trainer(trainer_name, trainer_age, trainer_city) pokemon_name = input('What is the name of your pokemon? ') pokemon_type = input('What type is your pokemon? ') pokemon = Pokemon(pokemon_name, pokemon_type) move_name = input('Enter its signature move: ') move_type = input('Enter the move type: ') move = Move(move_name, move_type) pokemon.add_moves(move_name) print('Thank you for your information!') print('Here is your entry: ') #creates list of trainer attributes trainer_list = [ 'Name: ' + trainer_name, 'Age: ' + trainer_age, 'City: ' + trainer_city ] for i in trainer_list: print(i) #creates list for pokemon attributes pokemon_list = [ 'Pokemon: ' + pokemon_name, 'Type: ' + pokemon_type, 'Signature Move: ' + move_name, 'Move Type: ' + move_type ] for i in pokemon_list: print(i)
def start_battle(self): try: self.poke_cliente = Pokemon(request.data, xml=True) except etree.XMLSyntaxError as e: print('Erro de sintaxe no XML: ', e) abort(422) if len(sys.argv) == 3: poke = Pokemon(sys.argv[2]) elif len(sys.argv) == 2: poke = Pokemon(sys.stdin) self.poke_server = poke self.battle = Battle() self.ai = AI() first = self.battle.get_first(self.poke_server, self.poke_cliente) if first is self.poke_server: choice = self.battle.make_choice(self.poke_server, self.poke_cliente, self.ai) self.battle.attack(self.poke_server, self.poke_cliente, choice) self.battle.all_alive(self.poke_server, self.poke_cliente) xml = self.poke_cliente.to_XML('<battle_state></battle_state>') xml = self.poke_server.to_XML(xml) else: xml = self.poke_server.to_XML(request.data) return xml, 200
def test_nestball(self): pok = Pokemon(PokemonType.Audino) pok.level = 29.999999 rate, cond = self.catchRate(BallType.NestBall, wild = pok) self.assertTrue(rate > 1) pok.level = 40 self.assertEqual(self.catchRate(BallType.NestBall, wild = pok), (1,True))
def teste_melhor_ataque(self): """ Vamos testar se a função melhor_ataque dá realmente o ataque com a melhor relação dano x acurácia testando todos os ataques do pokemon atacante no pokemon defensor.""" for j in range(100): # Cria um pokemon atacante e um defensor dados_atk = RandomPoke() dados_def = RandomPoke() atacante = Pokemon(dados_atk.gera()) defensor = Pokemon(dados_def.gera()) melhor = melhor_ataque(atacante, defensor) danos = [] if atacante.hp < atacante.hp_max / 5: estado_critico = True else: estado_critico = False for ataque in atacante.ataques: if ataque.pp > 0 and estado_critico is False: dano = ataque.calcula_dano(atacante, defensor, basico=True) danos.append(dano * (ataque.acu * ataque.acu) / 10000) elif ataque.pp > 0 and estado_critico is True: dano = ataque.calcula_dano(atacante, defensor, basico=True) # Caso não tire todo o hp, escolhe o que causa (em média) o maior # dano usando a relação dano x acurácia. if max(danos) < defensor.hp: melhor_dano = melhor.calcula_dano(atacante, defensor, basico=True) self.assertEqual(atacante.get_ataque(danos.index(max(danos))), melhor, 1)
def test_xml(self): """Verifica integridade e corretude dos xmls gerados.""" for i in range(300): data1 = RandomPoke() data2 = RandomPoke() dados1 = data1.gera() dados2 = data2.gera() poke1 = Pokemon(dados1) poke2 = Pokemon(dados2) # Testando to_xml bs_poke1 = poke1.to_xml() bs_poke2 = poke2.to_xml() data_teste1 = xml_to_poke(bs_poke1) data_teste2 = xml_to_poke(bs_poke2) for i in range(9): self.assertEqual(data_teste1[i], dados1[i]) self.assertEqual(data_teste2[i], dados2[i]) pos_atk = 9 # Posição da lista de ataques na lista de dados atk_dados1 = dados1[pos_atk] atk_dados2 = dados2[pos_atk] atk_test1 = data_teste1[pos_atk] atk_test2 = data_teste2[pos_atk] for i in range(len(poke1.ataques)): self.assertEqual(atk_dados1[i].nome, atk_test1[i].nome) self.assertEqual(atk_dados1[i].typ, atk_test1[i].typ) self.assertEqual(atk_dados1[i].acu, atk_test1[i].acu) self.assertEqual(atk_dados1[i].pwr, atk_test1[i].pwr) self.assertEqual(atk_dados1[i].pp, atk_test1[i].pp)
def unknown_init(self): self.unknown = Pokemon() self.unknown.set_name('???') self.unknown.set_type('???') self.unknown.set_stats(['???','???','???','???','???','???','???']) self.unknown.set_weaknesses([['???'],['???'],['???'],['???'],['???'],['???']]) self.unknown.set_image()
def create_pokemon(ai_settings, screen, pokemons, pokemon_number, row_number): pokemon = Pokemon(ai_settings, screen) pokemon_width = pokemon.rect.width pokemon.x = pokemon_width + 2 * pokemon_width * pokemon_number pokemon.rect.x = pokemon.x pokemon.rect.y = pokemon.rect.height + 2 * pokemon.rect.height * row_number pokemons.add(pokemon)
def test_pokemon_level_disadvantage(self): self.assertEqual( Pokemon('Fire', 19).check_odds(Pokemon('Fighting', 20)), "Disadvantage") self.assertEqual( Pokemon('Fire', 19).check_odds(Pokemon('Fire', 20)), "Disadvantage")
def pokemon(pokemon): """ Creates a pokemon object based on the clicked pokemon on index. If there is no pokemon, returns error template. """ try: mon = Pokemon(pokemon) stats = mon.get_stats() total_stats = mon.total_stats max_stat = mon.max_stat stringify_stats = lambda x: str(x * 100 // max_stat) def check_style(stat): """ Returns a bootstrap color class depending on the stat """ if stat == "hp": return "bg-secondary" elif stat == "attack": return "bg-success" elif stat == "defense": return "bg-info" elif stat == "special-attack": return "bg-warning" elif stat == "special-defense": return "bg-danger" elif stat == 'speed': return "" return render_template('pokemon.html', **locals()) except: return render_template('error.html')
def test_pokemon_capture_gen1(): """Test simulation of capturing Pokémons of catch algorithm generation 1""" pokemon = Pokemon(PokemonType.Pikachu, State.asleep) HPmax = pokemon.HP catch_arr = [] shakes_arr = np.zeros(HPmax-1) hp_arr = [i for i in range(1,HPmax)] # Simulate for i in range(1,HPmax): catch_sum = 0 shake_sum = 0 pokemon.HPcurrent = i for j in range(400): a, b = capture_simulation_gen1(BallType.UltraBall, pokemon) catch_sum += float(a/4.0) catch_arr.append(catch_sum) fig, ax = plt.subplots() fig.suptitle('Pokemon gen1 simulation', fontsize=17, fontweight='bold') ax.set_title(pokemon.name, fontsize=16) ax.plot(hp_arr, catch_arr, label="Catch Probability") ax.set_xlabel('Current HP', fontsize=15) ax.set_ylabel('Ratio', fontsize=15) legend = ax.legend() plt.show()
def initialise_teams(self, msg_arr): for i in range(3, len(msg_arr)): if (msg_arr[i - 3] == "poke"): # get name/id of pokemon and if has item split_msg = [i.strip() for i in msg_arr[i - 1].split(',')] id = split_msg[0] # don't see if have item in gen 8 so assume true if (self.gen >= 8): has_item = True else: has_item = (msg_arr[i] == "item\n") # look for level, gender level, gender, shiny = 100, None, False # values if not given for part in split_msg[1:]: if (part[0] == "L"): # level level = int(part[1:]) elif (part == "M" or part == "F"): # gender gender = part # add to appropriate team if (msg_arr[i - 2] == self.my_side): self.my_team.append( Pokemon("bot", id, has_item, level, gender)) else: self.foe_team.append( Pokemon("foe", id, has_item, level, gender)) predict_foe_sets.update_likely_sets(self, self.foe_team)
def __init__(self, ui, session): super(PokemonUserInterface, self).__init__(ui, 'pokemon', session) self.title('Pokemon Editor', color=session.game.color) self.data = Pokemon(session.game) with self.menu('file') as file_menu: file_menu.action('new', self.new, file_menu.shortcut('n', ctrl=True)) file_menu.action('save', self.save, file_menu.shortcut('s', ctrl=True)) file_menu.action('save_as', self.save_as, file_menu.shortcut('s', ctrl=True, shift=True)) file_menu.action('export', self.export, file_menu.shortcut('e', ctrl=True)) file_menu.action('export_as', self.export_as, file_menu.shortcut('e', ctrl=True, shift=True)) file_menu.action('close', self.close, file_menu.shortcut('w', ctrl=True)) """with self.group('pokemon') as pokemon_group: natid = self.edit('natid') @natid.on('changed') def natid_changed(evt): print(evt.data.value, ) with pokemon_group.group('personal') as personal_group: with personal_group.group('base_stat') as base_stat_group: for stat in Stats.STATS: base_stat_group.edit(stat) personal_group.number('catchrate') personal_group.number('baseexp') with personal_group.group('evs') as evs_group: for stat in Stats.STATS: evs_group.number(stat) personal_group.edit('gender') personal_group.edit('hatchsteps') personal_group.edit('happiness') personal_group.edit('growth') personal_group.edit('flee') personal_group.edit('color') with pokemon_group.group('evolutions') as evolutions_group: with evolutions_group.group('0') as group_0: group_0.edit('method') group_0.edit('parameter') group_0.edit('target') with pokemon_group.group('levelmoves') as levelmoves_group: with levelmoves_group.group('0') as group_0: group_0.edit('moveid') group_0.edit('level')""" with self.group('pokemon') as pokemon_group: self.update_from_data(self.data, pokemon_group) natid = self['pokemon']['natid'] @natid.on('changed') def natid_changed(evt): self.load(evt.data.value) print('prebind', self.data) self.bind('pokemon', self, 'data') print(self.data)
def test_switch_pokemon(): first_pokemon_trainer3 = Pokemon("Charmander", 11, "Fire", 100, 70, "yes") second_pokemon_trainer3 = Pokemon("WaterDuck", 34, "Water", 100, 90, "no") trainer3 = Trainer("Misty", [first_pokemon_trainer3, second_pokemon_trainer3], 1, second_pokemon_trainer3) assert trainer3.switch_pokemon( first_pokemon_trainer3) == "\nCan't switch if was knocked out."
def main(): p1 = Pokemon(client.get_pokemon(3), 50) p2 = Pokemon(client.get_pokemon(6), 50) battle = Battle(p1, p2) battle.make_move(p1.moves[0])
def initialize_pokemons(): pokemon = [] pokemon.append(Pokemon("Balbasaur", "fű", "víz")) pokemon.append(Pokemon("Pikatchu", "elektromos", "víz")) pokemon.append(Pokemon("Charizard", "tűz", "fű")) pokemon.append(Pokemon("Balbasaur", "víz", "tűz")) pokemon.append(Pokemon("Kingler", "víz", "tűz")) return pokemon
def setUp(self): """Inicializa os dois Pokémons aleatórios para os testes.""" sys.stdout = open(os.devnull, "w") # Suprime o output de batalha.py sys.stderr = sys.stdout self.a = RandomPoke() self.b = RandomPoke() self.poke1 = Pokemon(self.a.gera()) self.poke2 = Pokemon(self.b.gera()) self.struggle = Ataque(["Struggle", 0, 100, 50, 10])
def testPokemon(): poke1 = Pokemon("Charmander") logger.info("Charmander toJSON: %s", Pokemon.toJson(poke1)) poke1AsJson = '''{ "name": "Charmander" }''' logger.info("Charmander fromJSON: %s", Pokemon.fromJson(poke1AsJson).name)
def __init__(self, name: str, *pokemons: tuple, level: int = 5): self.name = name.capitalize() self.bag = Bag() self.party = Party( *(Pokemon(pokemon, level=randint(floor(level * 0.9), floor(level * 1.1))) for pokemon in pokemons) if pokemons else Pokemon(choice( ['bulbasaur', 'charmander', 'squirtle', 'pikachu']), level=5)) self.in_battle = False
def get_cell_pokemons(self): wilds = self.cell.get('wild_pokemons', []) catchables = self.cell.get('catchable_pokemons', []) pokemons = [] pokemons.extend([Pokemon.from_wild(wild).to_dict() for wild in wilds]) pokemons.extend([Pokemon.from_catch(catch).to_dict() for catch in catchables]) return pokemons
def test_potion(): first_pokemon_trainer1 = Pokemon("Charmander", 81, "Fire", 100, 70, "no", 100, 45) second_pokemon_trainer1 = Pokemon("Balbazor", 1, "Grass", 100, 100, "no", 100, 6) trainer1 = Trainer("Brooke", [first_pokemon_trainer1, second_pokemon_trainer1], 1, second_pokemon_trainer1) assert trainer1.healing_potion( 2) == "\nCan't use a potion past the maximum health."
def get_cell_pokemons(self): wilds = self.cell.get('wild_pokemons', []) catchables = self.cell.get('catchable_pokemons', []) pokemons = [] pokemons.extend([Pokemon.from_wild(wild).to_dict() for wild in wilds]) pokemons.extend( [Pokemon.from_catch(catch).to_dict() for catch in catchables]) return pokemons
def test_breeder_init_correctly(self): self.assertEqual( str( Breeder("npc", [ Pokemon("Fire", 10), Pokemon("Water", 11), Pokemon("Grass", 12), Pokemon("Electric", 13), Pokemon("Psychic", 14) ])), "npc[Fire#10, Water#11, Grass#12, Electric#13, Psychic#14]")
def __init__(self): self._pause = True self._stop = False self.hp_nichi_threshold = 130 self.ocr = Ocr() self.all_poke_data = pd.read_csv("data/all_poke_data.csv", encoding="SHIFT-JIS") self.my_pokemon = Pokemon() self.enemy_pokemon = Pokemon()
def get(self): if not 'Authorization' in request.headers: return {"msg": "Missing Authorization Header"}, 401 project_secret_key = request.headers.get('Authorization') types = Pokemon.getPokeTypeUserAccess(project_secret_key) if not 'types' in types: return types['error'] pokemon = Pokemon.getPokemonListForPokeTypeUserAccess(types['types']) if not 'pokemon' in pokemon: return {'erreur': pokemon['erreur']} return {'pokemon': pokemon['pokemon']}
def test_model_inference(model, device, model_path, resize_h, resize_w, classes, use_multilabel): pokemon = Pokemon(POKEMON_DIR, resize_h, resize_w, None, use_multilabel) images_list, _ = pokemon.load_csv( os.path.join(POKEMON_DIR, 'pokemon_multilabel.csv')) #image_path = os.path.join(POKEMON_DIR, '4杰尼龟', '00000020.jpg') #images_list = [image_path] # 加载模型 if os.path.exists(model_path): # 导入模型 pretrain_model = torch.load(model_path) state_dict = pretrain_model['model_state_dict'] new_state_dict = OrderedDict() is_multigpu_train = False for key, value in state_dict.items(): if key[:6] == "module": is_multigpu_train = True new_key = key[7:] new_state_dict[new_key] = value else: break # 恢复网络的参数 if is_multigpu_train: model.load_state_dict(new_state_dict) else: model.load_state_dict(state_dict) print('Successfully Load {} Model'.format(model_path)) # train时的BN作用和test不一样 model.eval() # 前向计算 不用更新梯度 with torch.no_grad(): for image_path in images_list: image = Image.open(image_path).convert('RGB') #png是RGBA所以要转换 # 对图片预处理 image = pokemon.transform(image) # c h w在第一维上添加一个维度变成n c h w image = image.unsqueeze(0) image = image.to(device) output = model.forward(image) if use_multilabel: output1, output2 = output # data得到tensor转成python数组(用于数组) _, predict_output1 = torch.max(output1.data, dim=1) _, predict_output2 = torch.max(output2.data, dim=1) print(image_path, ':', classes[0][int(predict_output1)], classes[1][int(predict_output2)]) else: _, predict_output = torch.max(output.data, dim=1) print(image_path, ':', classes[int(predict_output)])
def scrape_data(): x = open("inst2.txt", "w+") try: for i in range(1, 730): data =requests.get("http://pokeapi.co/api/v1/pokemon/" + str(i)).json() p = Pokemon(data) p.id = i print(str(p.__dict__), file=x) print(str(data["name"]).upper() +" has been successfully created! Id: " + str(i) + ", Generation: " + str(p.generation)) finally: x.close()
def test_breeder_unique_pokemon_type(self): with self.assertRaises(ValueError) as context: Breeder("npc", [ Pokemon("Fire", 10), Pokemon("Fire", 10), Pokemon("Electric", 10), Pokemon("Grass", 10), Pokemon("Water", 10) ]) self.assertTrue( "A breeder can hold a maximum of one pokemon of each type" in str( context.exception))
def initialize(self): self.sessions = 0 self.num_pcs = 2 self.num_npcs = 2 self.pokemon = {} for index in [('pc', i) for i in range(self.num_pcs)]: self.add_pokemon(index, Pokemon.random_pokemon('pc')) for index in [('npc', i) for i in range(self.num_npcs)]: self.add_pokemon(index, Pokemon.random_pokemon('npc')) self.state = Initialize(self) self.soft_state = {} self.ui = BattleUI()
def test_correct_eff_dict_creation(self): # Example Pokémon Litleo (Fire/Normal) and Misdreavus (Ghost) litleo = Pokemon("Litleo", "Female", 100, example_moves, "Adamant", [31, 31, 31, 31, 31, 31], [252, 0, 0, 252, 0, 4]) misdreavus = Pokemon("Misdreavus", "Female", 100, example_moves, "Adamant", [31, 31, 31, 31, 31, 31], [252, 0, 0, 252, 0, 4]) # Example Pokémon correct type effectiveness dictionaries litleo_effectiveness = { "Normal": 1, "Fire": 0.5, "Water": 2, "Electric": 1, "Grass": 0.5, "Ice": 0.5, "Fighting": 2, "Poison": 1, "Ground": 2, "Flying": 1, "Psychic": 1, "Bug": 0.5, "Rock": 2, "Ghost": 0, "Dragon": 1, "Dark": 1, "Steel": 0.5, "Fairy": 0.5 } misdreavus_effectiveness = { "Normal": 0, "Fire": 1, "Water": 1, "Electric": 1, "Grass": 1, "Ice": 1, "Fighting": 0, "Poison": 0.5, "Ground": 1, "Flying": 1, "Psychic": 1, "Bug": 0.5, "Rock": 1, "Ghost": 2, "Dragon": 1, "Dark": 2, "Steel": 1, "Fairy": 1 } self.assertDictEqual(litleo.type_effect, litleo_effectiveness) self.assertDictEqual(misdreavus.type_effect, misdreavus_effectiveness)
def setUp(self): """Inicializa dados para teste.""" sys.stdout = open(os.devnull, "w") # Suprime o output de batalha.py sys.stderr = sys.stdout self.srv = Servidor(False) self.srv.app.config["TESTING"] = True self.app = self.srv.app.test_client() self.data1 = RandomPoke() self.data2 = RandomPoke() self.dados1 = self.data1.gera() self.dados2 = self.data2.gera() self.poke1 = Pokemon(self.dados1) self.poke2 = Pokemon(self.dados2)
def test_attack_trainer(): first_pokemon_trainer2 = Pokemon("WaterDuck", 13, "Water", 100, 4, "yes") second_pokemon_trainer2 = Pokemon("Balbazor", 1, "Grass", 100, 60, "no") first_pokemon_trainer3 = Pokemon("Charmander", 11, "Fire", 100, 70, "no") second_pokemon_trainer3 = Pokemon("WaterDuck", 34, "Water", 100, 90, "no") trainer2 = Trainer("Ash", [first_pokemon_trainer2, second_pokemon_trainer2], 2, first_pokemon_trainer2) trainer3 = Trainer("Misty", [first_pokemon_trainer3, second_pokemon_trainer3], 1, second_pokemon_trainer3) assert trainer2.attack_other_trainer( trainer3) == "\nCan't attack if was knocked out."
def chooseCompPkmn(): compChoice = Pokemon.choosePokemon(pkmnObjects) compPkmn = pkmnObjects[compChoice] '''for y in pkmnObjects: if y.getName() == userChoice: #print("MATCH") userPkmn = y break''' for x in range(len(pkmnObjects)): if compPkmn == userChoice: compChoice = Pokemon.choosePokemon(pkmnObjects) compPkmn = pkmnObjects[compChoice] return compPkmn
def trainer_party(trainer_id): """ Uses a users databse id to query the pokemon and trainer database join table and return all results where the trainer id matches the current trainer. That data is then taken and used to construct a list of pokemon objects Keyword argument: trainer_id -- a users database id """ db.execute('SELECT * FROM pokemon_party WHERE trainer_id= :trainer_id',{'trainer_id': trainer_id}) pokemon_trainer_list = db.fetchall() pokemon_party = [] #If pokemon party_tranier list is empty prompt them to create their own team for pokemon in pokemon_trainer_list: db.execute('SELECT * FROM pokemon WHERE pokedex_id= :pokemon_id',{'pokemon_id':pokemon[2] }) monster = db.fetchone() # print(monster) #Pokemon Name monster_name = monster[1] #Pokemon Level monster_level = monster[2] #First pokemon type monster_type1 = db.execute('SELECT type FROM pokemon_type WHERE id= :id', {'id': monster[3]}).fetchone() #second pokemon type monster_type2 = db.execute('SELECT type FROM pokemon_type WHERE id= :id', {'id': monster[4]}).fetchone() #pokemon base hp monster_hp = monster[5] #pokemon base attack monster_atk = monster[6] #pokemon base defense monster_def = monster[7] #pokemon base special attack monster_spatk = monster[8] #pokemon base special defense monster_spdef = monster[9] #pokemon base speed monster_spe = monster[10] pkmn = Pokemon(monster_name, monster_level, monster_type1[0], monster_type2[0], monster_hp, monster_atk, monster_def, monster_spatk, monster_spdef, monster_spe) #assign all weakness and resistance to pokemon after their creation pkmn.pokemon_weak_resist(monster_type1[0],monster_type2[0]) pokemon_party.append(pkmn) return pokemon_party
def create_member(self, member_type: str, pokedex_num: int, source: str, nickname: str = None, item: str = None, ability: str = None, json: Dict = None) -> int: """ Adds a member (egg or Pokemon) to the player's _pc. Depending on the type of member, this function adds a new entry to the player's party. It also assigns the Pokemon an ID, and then increments it by 1 so that it is unique for the next member that is added. :param member_type: The party member type, either "Egg" or "Pokemon" :param pokedex_num: The Pokedex number that corresponds with the Pokemon species. :param source: The location that the Pokemon/Egg was acquired. :param nickname: The given name for the Pokemon. :param item: The item that the Pokemon is currently holding. :param ability: The Pokemon's special ability. :return: No return :rtype: None """ self._validate_pokedex_number(pokedex_num) if not nickname: nickname = self._POKEDEX[pokedex_num][0] if member_type == Pokemon.member_type(): self._pc_pokemon[self._ID] = Pokemon(self._ID, pokedex_num, source, nickname=nickname, item=item, ability=ability, json=json) self._ID += 1 elif member_type == Egg.member_type(): self._pc_pokemon[self._ID] = Egg(self._ID, pokedex_num, source, nickname=nickname, item=item, json=json) self._ID += 1 else: raise ValueError(f"{member_type} is not a valid Party Member type") self._write_to_file() return self._ID - 1
def get(self, pokemon): pokemonDetail = Pokemon.getPokemonByIdOrName(pokemon) if not 'pokemon' in pokemonDetail: return {'error': pokemonDetail['error']} if not 'Authorization' in request.headers: return {"msg": "Missing Authorization Header"}, 401 project_secret_key = request.headers.get('Authorization') types = Pokemon.getPokeTypeUserAccess(project_secret_key) if not 'types' in types: return types['error'] for type in pokemonDetail['pokemon']['types']: if type['type']['name'] in types['types']: return {'pokemonDetail': pokemonDetail} return {'error': 'Vous devez ajouté le type du pokemon avant de voir plus d\'informations'}
def test_constructor(self): self.assertIsInstance(self.pokemon, Pokemon) with self.assertRaises(TypeError): p = Pokemon("hi", 10, "BC", "Flyboy", "Wings of Bud", "wings") with self.assertRaises(ValueError): p = Pokemon(0, 10, "BC", "Flyboy", "Wings of Bud", "wings") with self.assertRaises(TypeError): p = Pokemon(self._ID, 10, 0, "Flyboy", "Wings of Bud", "wings") with self.assertRaises(ValueError): p = Pokemon(0, 10, "", "", item="Wings of Bud")
def buildStarter(speciesName): """ Creates a Pokemon with Starter stats """ name = speciesName species = SpeciesFactory.getSpecies(speciesName) level = 5 pkmn = Pokemon(name, level, species) pkmn.id = "" pkmn.ability = Ability(None) pkmn.battleDelegate = PokemonBattleDelegateFactory.buildStarter(pkmn) pkmn.displayDelegate = PokemonDisplayDelegateFactory.buildStarter(species) # pkmn.experienceDelegate = ExperienceDelegateFactory.loadFromXML(pkmn, tree) return pkmn
def client(server_address, local_player): global battle, pokemon_client, pokemon_server, player player = local_player battle = Battle(client = True) pokemon_client = Pokemon.create_pokemon() xml = xml_pokemon.generate(pokemon_client, pokemon_server) response = requests.post('http://' + server_address + ':5000/battle', data = xml, headers={'Content-Type': 'application/xml'}) not_first_round = False while response.status_code == 200: if not_first_round: server_hp = pokemon_server.hp dummy, pokemon_server = xml_pokemon.parse(response.content.decode('utf-8')) print (pokemon_client.name + " inflicted " + str(server_hp - pokemon_server.hp) + " points of damage in " + pokemon_server.name + "!") battle.print_battle_status(pokemon_client, pokemon_server) if battle.battle_ended(pokemon_client, pokemon_server): return client_hp = pokemon_client.hp pokemon_client, dummy = xml_pokemon.parse(response.content.decode('utf-8')) print (pokemon_server.name + " inflicted " + str(client_hp - pokemon_client.hp) + " points of damage in " + pokemon_client.name + "!") battle.print_battle_status(pokemon_client, pokemon_server) if battle.battle_ended(pokemon_client, pokemon_server): return else: pokemon_client, pokemon_server = xml_pokemon.parse(response.content.decode('utf-8')) battle.print_battle_status(pokemon_client, pokemon_server) if player == "user": option = pokemon_client.perform_attack_client() elif player == "ai": option = pokemon_client.perform_attack_client_ai(pokemon_server) xml = xml_pokemon.generate(pokemon_client, pokemon_server) response = requests.post('http://' + server_address + ':5000/battle/attack/' + option, data = xml, headers={'Content-Type': 'application/xml'}) not_first_round = True
def test_update_pokemon_gen12(self): """Test updating special skills of a Pokémon""" p = Pokemon(PokemonType.Pikachu, State.normal) p.level = 81 p.HP_IV = 7 p.HP_EV = 22850 p.attack_IV = 8 p.attack_EV = 23140 p.defense_IV = 13 p.defense_EV = 17280 p.sp_IV = 9 p.sp_EV = 19625 pokemon.update_pokemon_gen2(p) self.assertTrue(p.HP == 189.0 and p.attack == 137.0 and p.defense == 101.0 and p.sp_attack == 128.0 and p.sp_defense == 112.0)
def start_battle(self): try: self.poke_cliente = Pokemon(request.data, xml = True) except etree.XMLSyntaxError as e: print('Erro de sintaxe no XML: ', e) abort(422) if len(sys.argv) == 3: poke = Pokemon(sys.argv[2]) elif len(sys.argv) == 2: poke = Pokemon(sys.stdin) self.poke_server = poke self.battle = Battle() self.ai = AI() first = self.battle.get_first(self.poke_server, self.poke_cliente) if first is self.poke_server: choice = self.battle.make_choice(self.poke_server, self.poke_cliente, self.ai) self.battle.attack(self.poke_server, self.poke_cliente, choice) self.battle.all_alive(self.poke_server, self.poke_cliente) xml = self.poke_cliente.to_XML('<battle_state></battle_state>') xml = self.poke_server.to_XML(xml) else: xml = self.poke_server.to_XML(request.data) return xml, 200
def __init__(self): BaseServer.__init__(self, "Generic") self._pokemon = Pokemon.get_pokemon(self.host_number) print "You chose: " + self._pokemon self.params = [ ("Hostname", self.hostname), ("Pokemon", self._pokemon), ("PrivateIpAddress", self.private_ip), ("SubnetType", self.privacy_setting), ("SubnetRegion", self.subnet["az"]), ("PuppetmasterIP", self.puppetmaster_ip), ("PuppetmasterHostname", self.puppetmaster_hostname), ("InstanceType", self.instance_type), ("SecurityGroupIds", self.security_groups)]
def test_levelball(self): # Example pokemons a = Pokemon(PokemonType.Abomasnow, State.normal) b = Pokemon(PokemonType.Abra, State.normal) a.level = 1 b.level = 2 self.assertEqual(self.catchRate(BallType.LevelBall, a, b), (1, True)) a.level = 3 self.assertEqual(self.catchRate(BallType.LevelBall, a, b), (2, True)) a.level = 5 self.assertEqual(self.catchRate(BallType.LevelBall, a, b), (4, True)) a.level = 9 self.assertEqual(self.catchRate(BallType.LevelBall, a, b), (8, True))
def battle_start(): global battle, pokemon_client, pokemon_server, player if battle == None: battle = Battle(server = True) else: abort(403) xml = request.data.decode('utf-8') pokemon_client, dummy = xml_pokemon.parse(xml) pokemon_server = Pokemon.create_pokemon() battle.print_battle_status(pokemon_client, pokemon_server) if pokemon_server.speed > pokemon_client.speed: if player == "user": option = pokemon_server.perform_attack_server() elif player == "ai": option = pokemon_server.perform_attack_server_ai(pokemon_client) pokemon_server.inflict_and_announce_damage_server(pokemon_client, option) battle.print_battle_status(pokemon_client, pokemon_server) if battle.battle_ended(pokemon_client, pokemon_server): server_shutdown() xml = xml_pokemon.generate(pokemon_client, pokemon_server) return xml
def loadFromXML(tree): """ Loads a Pokemon object from a file """ name = tree.findtext(Tags.nameTag) speciesName = tree.findtext(Tags.speciesTag) species = SpeciesFactory.getSpecies(speciesName) level = int(tree.findtext(Tags.levelTag)) pkmn = Pokemon(name, level, species) pkmn.id = "" pkmn.ability = AbilityFactory.loadFromPkmnXML(tree.find(Tags.abilityTag).text) pkmn.battleDelegate = PokemonBattleDelegateFactory.loadFromXML(pkmn, tree) pkmn.displayDelegate = PokemonDisplayDelegateFactory.loadFromXML(tree.find(Tags.displayTag), pkmn) pkmn.experienceDelegate = ExperienceDelegateFactory.loadFromXML(pkmn, tree) return pkmn
class Server(): _poke_cliente = None _poke_server = None _battle = None _ai = None @property def poke_cliente(self): return self._poke_cliente @property def poke_server(self): return self._poke_server @property def ai(self): return self._ai @property def battle(self): return self._battle @poke_cliente.setter def poke_cliente(self, value): self._poke_cliente = value @poke_server.setter def poke_server(self, value): self._poke_server = value @battle.setter def battle(self, value): self._battle = value @ai.setter def ai(self, value): self._ai = value def start_battle(self): try: self.poke_cliente = Pokemon(request.data, xml = True) except etree.XMLSyntaxError as e: print('Erro de sintaxe no XML: ', e) abort(422) if len(sys.argv) == 3: poke = Pokemon(sys.argv[2]) elif len(sys.argv) == 2: poke = Pokemon(sys.stdin) self.poke_server = poke self.battle = Battle() self.ai = AI() first = self.battle.get_first(self.poke_server, self.poke_cliente) if first is self.poke_server: choice = self.battle.make_choice(self.poke_server, self.poke_cliente, self.ai) self.battle.attack(self.poke_server, self.poke_cliente, choice) self.battle.all_alive(self.poke_server, self.poke_cliente) xml = self.poke_cliente.to_XML('<battle_state></battle_state>') xml = self.poke_server.to_XML(xml) else: xml = self.poke_server.to_XML(request.data) return xml, 200 def compute_attack(self, id): self.battle.attack(self.poke_cliente, self.poke_server, choice = id - 1) print('Oponente escolheu o ataque: ', self.poke_cliente.atks[id - 1].name) if self.battle.all_alive(self.poke_cliente, self.poke_server): choice = self.battle.make_choice(self.poke_server, self.poke_cliente, self.ai) self.battle.attack(self.poke_server, self.poke_cliente, choice) self.battle.all_alive(self.poke_cliente, self.poke_server) battle_state = self.poke_cliente.to_XML('<battle_state></battle_state>') battle_state = self.poke_server.to_XML(battle_state) return battle_state, 200 from flask import request def shutdown_server(self): func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not running with the Werkzeug Server') func() def shutdown(self): self.shutdown_server() return 'You have been terminated'
def play(self): response = self.get_user_input() while True: total_pokemon = 6 user_switch = 0 turns = 1 user_tally = 0 computer_tally = 0 trainer = self.add_trainer() print 'Welcome, {}!'.format(trainer.name) while response != 'r': if response == 'b': choice = self.print_battle_status(turns, total_pokemon) player = Pokemon.randomizer() computer = Pokemon.randomizer() prompt = raw_input('You selected ' + player.name + '. Do you want to keep? (Y/N) ').lower() if prompt == 'y': winner = self.battle(player, computer) if winner == BATTLE_WINNER_COMPUTER: computer_tally += 1 else: user_tally += 1 turns += 1 total_pokemon -= 1 print 'Your score: {}.'.format(user_tally) print 'Opponent score: {}.'.format(computer_tally) if total_pokemon == 0: if trainer.name not in scores: scores[trainer.name] = user_tally else: scores[trainer.name] += user_tally print "Scorez, bitches: {}".format(scores) response = self.get_user_input() break elif prompt == 'n': user_switch += 1 player = Pokemon.randomizer() print 'The new selection is: {}.'.format(player.name) print 'Egotistical narcissistic trainer is ' \ 'getting annoyed! Limit how often you use your re-select!' if user_switch == 3: print 'The egotsitical narcissistic got annoyed and attacked' \ ' you with his/her pokemon. Game over! Choose faster next' \ ' time.' elif response == 'r': break else: print 'Please select a valid keystroke.' if response == 'r': break else: print 'Please enter a valid response.'
def computer(self): return Pokemon.randomizer()
def initialize_pokemons(self): print("Let's create the first POKeMON!") pokemon1 = Pokemon.create_pokemon() print("Let's create the second POKeMON!") pokemon2 = Pokemon.create_pokemon() return pokemon1, pokemon2
class BatalhaTestCase(unittest.TestCase): def setUp(self): """Inicializa os dois Pokémons aleatórios para os testes.""" sys.stdout = open(os.devnull, "w") # Suprime o output de batalha.py sys.stderr = sys.stdout self.a = RandomPoke() self.b = RandomPoke() self.poke1 = Pokemon(self.a.gera()) self.poke2 = Pokemon(self.b.gera()) self.struggle = Ataque(["Struggle", 0, 100, 50, 10]) def test_quem_comeca(self): """Verifica se a função quem_comeca retorna a tupla com o Pokemon de maior SPD primeiro.""" primeiro = (self.poke1 if self.poke1.spd > self.poke2.spd else self.poke2) segundo = self.poke2 if primeiro == self.poke1 else self.poke1 self.assertEqual(quem_comeca(primeiro, segundo), primeiro) self.assertEqual(quem_comeca(segundo, primeiro), primeiro) self.assertRaises(AttributeError, quem_comeca, None, None) self.assertRaises(AttributeError, quem_comeca, self.poke1, None) self.assertRaises(AttributeError, quem_comeca, None, self.poke1) def test_mostra(self): """Apenas verifica se a função levanta erros de atributos.""" self.assertRaises(AttributeError, mostra_pokemons, None, None) self.assertRaises(AttributeError, mostra_pokemons, self.poke1, None) self.assertRaises(AttributeError, mostra_pokemons, None, self.poke1) def test_escolhe_ataque(self): """Faz diversas verificações de input na escolha dos ataques.""" # Primeiro testamos como se nosso pokemons estivesse sem pp. # O comportamento esperado é que utilize Struggle. batalha.input = Mock(return_value="ok") with patch("pokemon.Pokemon.todos_ataques_sem_pp", return_value=True): self.assertEqual(self.poke2.todos_ataques_sem_pp(), True) self.assertEqual((escolhe_ataque(self.poke1, self.poke2)).nome, self.struggle.nome) # Testando se escolhe_ataque está retornando os ataques corretos for i in range(len(self.poke1.ataques)): batalha.input = Mock(return_value=(i+1)) self.assertEqual(escolhe_ataque(self.poke1, self.poke2), self.poke1.ataques[i]) # Nesse ponto o escolhe_ataque receberá de input 4 valores "errados" # e um certo. O comportamento esperado é que a função não levante # exceções com os valores errados e execute normalmente quando chegar # o correto. valores_errados = [self.poke1.nome, random.uniform(-100, 100), 5, -1, 1] batalha.input = Mock(side_effect=valores_errados) self.assertTrue(escolhe_ataque(self.poke1, self.poke2) in self.poke1.ataques) def test_realiza_ataque_e_calcula_dano(self): """Verifica se ataque e suas consequências ocorrem sem problemas.""" batalha.input = Mock(return_value="ok") # Geramos novos Pokémons para podermos realizar vários # testes sem acabar com todo o HP deles. for i in range(100): a = RandomPoke() b = RandomPoke() poke3 = poke1 = Pokemon(a.gera()) poke4 = poke2 = Pokemon(b.gera()) # Assumindo que o ataque sempre vai acertar with patch('batalha.random.uniform', return_value=1.0): # Aqui começa o cálculo do dano lvl = poke1.lvl ataque = Ataque(a.gera_ataque()) if ataque.typ.is_especial: atk = poke1.spc dfs = poke2.spc else: atk = poke1.atk dfs = poke2.dfs pp = ataque.pp hp = poke2.hp base = ataque.pwr eff = efetividade(ataque, poke2, False) dano = (2*lvl + 10)/250 * atk/dfs * base + 2 dano *= (stab(ataque, poke1) * critico(poke1, eff) * eff * aleatorio()) dano = int(dano) #Testa o dano.calcula_dano self.assertEqual(dano, calcula_dano(ataque, poke1, poke2)) if (dano > 0): poke1.remove_hp(dano) if ataque == self.struggle: dano //= 2 poke2.remove(hp.dano) # Verficamos se o Pokemon.realiza_ataque está # aplicando corretamente o dano conforme a fórmula. pokemon.input = Mock(return_value="\n") poke3.realiza_ataque(ataque, poke4) self.assertEquals(pp - 1, ataque.pp) self.assertEquals(poke1.hp, poke3.hp) self.assertEquals(poke2.hp, poke4.hp) def tearDown(self): """Encerra os testes.""" sys.stdout.close() # Fechando o os.devnull sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__
6: Let's trip! 7: Catch the pokemon!!! """) while True: try: opt = int(input()) break except ValueError: print("I asked a number, not else...") if opt == 0: print("Thanks for playing!\nI hope you enjoyd :)") break elif opt == 1: print(player) elif opt == 2: Pokemon.print_pokekodex() elif opt == 3: player.print_pokemons_objects_name() elif opt == 4: City.print_available_cities_with_pokemon() elif opt == 5: player.go_to_sleep() elif opt == 6: available_cities = [bp, kv, hb, db] counter = 0 print("Available cities:\n"+"-"*18) for element in City.available_pokemon_object: print("-", element.name, "[{}]".format(counter)) counter += 1 while True: try:
import requests import sys from pokemon import Pokemon from lxml import etree from battle import Battle from ai import * ai = None if len(sys.argv) == 4: ai = AI() if len(sys.argv) >= 3: poke = Pokemon(sys.argv[2]) elif len(sys.argv) == 2: poke = Pokemon(sys.stdin) # começa a bataha r = requests.post('http://localhost:5000/battle/', data = poke.to_XML( '<battle_state></battle_state>')) while r.status_code != 200: print('status code: ', r.status_code) arq = input('Digite um nome de arquivo valido: ') poke = Pokemon(arq) r = requests.post('http://localhost:5000/battle/', data = poke.to_XML( '<battle_state></battle_state>'))
from pokemon import Pokemon x = Pokemon("Charizard") print(x.getSprites())