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 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 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 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_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 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 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 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 __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 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 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 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 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 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 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_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 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.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 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 main(): pikashu = Pokemon(nome="Pikashu", poder=400, tipo="elétrico") charmander = Pokemon(nome="Charmander", poder=300, tipo="fogo") snorlax = Pokemon(nome="Snorlax", poder=100, tipo="normal") arrayDePokemonsAsh = [pikashu, charmander, snorlax] arrayDePokemonsMisty = [pikashu, snorlax, snorlax] ash = Treinador(nome="Ash catchup", idade=20, pokemonArray=arrayDePokemonsAsh) misty = Treinador(nome="Misty", idade=23, pokemonArray=arrayDePokemonsMisty) RegaraDoJogo().Lutar(ash, misty)
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 pokemon(self): if not self._elements: return [] pokedex = Pokedex() encounters = [] for element in self._elements: try: id = element.get_attribute('data-pokeid') lat = element.get_attribute('data-lat') lng = element.get_attribute('data-lng') name = pokedex.name(id) expiration_ts = element.find_element_by_class_name( 'remainingtext').get_attribute('data-expire') except Exception, e: print 'pokemon disappears...' expiration = float(expiration_ts) / 1000 spawn = '' encounter_id = '' pokemon = Pokemon(id, name) encounters.append( PokemonEncounter(pokemon, lat, lng, expiration, spawn, encounter_id))
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 pokemon(self): if not self._elements: return [] pokedex = Pokedex() encounters = [] for element in self._elements: try: id = element.get_attribute('data-pokeid') lat = element.get_attribute('data-lat') lng = element.get_attribute('data-lng') name = pokedex.name(id) expiration_ts = element.find_element_by_class_name( 'remainingtext').get_attribute('data-expire') except Exception, e: print 'pokemon disappears...' continue pokemon_spot = (lat, lng) if vincenty(self._search_spot, pokemon_spot).km > MAX_RANGE_KM: continue expiration = float(expiration_ts) / 1000 spawn = '' hash_text = '%s%s%s' % (id, lat, lng) encounter_id = hashlib.sha1( hash_text.encode("UTF-8")).hexdigest()[:10] pokemon = Pokemon(id, name) encounters.append( PokemonEncounter(pokemon, lat, lng, expiration, spawn, encounter_id))
def get_pokemon_training_dataset(batch_size, resize_h, resize_w, use_multilabel): train_dataset = Pokemon(POKEMON_DIR, resize_h, resize_w, mode='train', use_multilabel=use_multilabel) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=CPU_CORES) print('Successfully load pokemon training dataset') return train_loader
def get_pokemon_test_dataset(batch_size, resize_h, resize_w, use_multilabel): test_dataset = Pokemon(POKEMON_DIR, resize_h, resize_w, mode='test', use_multilabel=use_multilabel) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=CPU_CORES) print('Successfully load pokemon test dataset') return test_loader
def main(): args = getArgs() if args.pokemonNames == None: print("Incorrect amount of data provided, please " + "enter name(s) or id(s) of the Pokemon you wish " + "to compare.") return pokemonList = [] for i in range(len(args.pokemonNames)): response = requests.post(PokeAPI + \ "pokemon/" + args.pokemonNames[i].lower()) jsonData = json.loads(response.text) try: name = jsonData["forms"][0]["name"] except: print("Invalid data entered. Please enter " + "valid name(s) or id(s) of the Pokemon you " + "wish to compare.") return typesObject = jsonData["types"] types = parseTypes(typesObject) damageRelations = \ getDamageRelationsForTypes(typesObject) baseStats = parseBaseStats(jsonData["stats"]) pokemon = Pokemon(name, types, damageRelations, baseStats) pokemonList.append(pokemon) favouredPokemon = \ getFavouredPokemonBasedOnType(pokemonList) if len(favouredPokemon) > 1: bestStatsPokemon = \ getFavouredPokemonBasedOnStats(favouredPokemon) print(bestStatsPokemon) else: print(favouredPokemon[0].getName())
def main_menu(): """Provide interface for finding and viewing pokemon details""" select_pokemon = "" pokemon_stats = "" # Read pokedex from JSON file and parse as list of dictioaries pokedex_json = open("pokedex.dat", encoding="utf-8").read() pokedex = json.loads(pokedex_json)["pokemon"] os.system("cls") print("\n \033[1mWelcome to the Pokédex!\x1b[0m") print("\n Generation I (Kanto Reigon)") print(" #001 - #151") # Loop until user provides pokemon name that exists in pokedex while pokemon_stats == "": select_pokemon = input( "\n\nWhich Pokémon would you like to see details for?: ").title() try: pokemon_stats = next(stats for stats in pokedex if stats["name"] == select_pokemon) except: print("\nNo Pokémon found with the name \"{}\"\n".format( select_pokemon)) # If a valid pokemon matched, display details if pokemon_stats != "": active_pokemon = Pokemon(pokemon_stats) os.system("cls") print(active_pokemon) input("\n\x1b[6;30;47m << Back to main menu \x1b[0m") main_menu()
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()