Esempio n. 1
0
    def create_pokemon(self, blue_attack, blue_speed, red_attack, red_speed):
        self.move_type = Type(name=Type.NORMAL)
        self.move_type.save()

        self.red_type = Type(name=Type.FIRE)
        self.red_type.save()

        self.blue_type = Type(name=Type.WATER)
        self.blue_type.save()

        self.move = Move(name='Tackle', type=self.move_type, base_power=50)
        self.move.save()

        self.red_pokemon = Pokemon(type1=self.red_type)
        self.red_pokemon.save()

        self.blue_pokemon = Pokemon(name='Squirtle', type1=self.blue_type,
                                    base_hp=44, base_attack=48, base_defence=65, base_special=50, base_speed=43)
        self.blue_pokemon.save()

        self.red_playerpokemon = PlayerPokemon(pokemon=self.red_pokemon, player=self.red,
                                               lead=True, move1=self.move)
        self.red_playerpokemon.save()
        self.blue_playerpokemon = PlayerPokemon(pokemon=self.blue_pokemon, player=self.blue,
                                                lead=True, move1=self.move)
        self.blue_playerpokemon.save()
Esempio n. 2
0
class TestPlayer(TestCase):
    def setUp(self):
        self.type = Type(name=Type.NORMAL)
        self.type.save()

        self.move = Move(name='Tackle', type=self.type, base_power=50)
        self.move.save()

        self.pokemon = Pokemon(name="Charmander", type1=self.type)
        self.pokemon.save()

        self.player_pokemon = PlayerPokemon(pokemon=self.pokemon, move1=self.move)
        self.player_pokemon.save()

        self.red = Player(username='******') # Will need to be changed to use a real Team
        self.red.save()

        self.player_pokemon.player = self.red
        self.player_pokemon.pokemon = self.pokemon
        self.player_pokemon.save()

    def test_get_and_update_usable_pokemon(self):
        self.red.check_usable_pokemon()

        self.assertEqual(self.red.usable_pokemon, 1)

    def test_get_and_update_usable_pokemon_when_one_faints(self):
        self.assertEqual(self.player_pokemon.player.usable_pokemon, 1)

        self.player_pokemon.take_damage(self.player_pokemon.hp)
        self.player_pokemon.player.check_usable_pokemon()

        self.assertEqual(self.player_pokemon.player.usable_pokemon, 0)
Esempio n. 3
0
def get_evolution_chain(identification):
    url = 'https://pokeapi.co/api/v2/evolution-chain/' + str(identification[0])
    response = requests.get(url)
    if response.status_code == 200:
        payload = response.json()
        chain = []
        name_poke = payload.get('chain').get('species').get('name')
        evolutions = payload.get('chain').get('evolves_to')
        pokemon = {'name': name_poke, 'evolutions': evolutions}
        chain.append(pokemon['name'])
        while len(evolutions):
            name_poke = pokemon['evolutions'][0]['species']['name']
            evolutions = pokemon['evolutions'][0]['evolves_to']
            pokemon = {'name': name_poke, 'evolutions': evolutions}
            chain.append(name_poke)
        pokemon_details = []
        for i in range(len(chain)):
            pokemon_details.append(get_pokemon_details(chain[i]))

        for i in range(len(pokemon_details)):
            identification = pokemon_details[i].get('id')
            name_poke = chain[i]
            height_poke = pokemon_details[i].get('height')
            weight_poke = pokemon_details[i].get('weight')
            stats = pokemon_details[i].get('stats')
            print(name_poke)
            x = {
                'pokemon': identification,
                'name': name_poke,
                'height': height_poke,
                'weight': weight_poke
            }
            adding_pokemon = Pokemon(**x)
            adding_pokemon.save()
            for j in range(len(stats)):
                base_stat_poke = stats[j]['base_stat']
                base_stat_name = stats[j]['stat']['name']
                adding_base_stat = BaseStat(name=base_stat_name,
                                            base_stat=base_stat_poke,
                                            pokemon=adding_pokemon)
                adding_base_stat.save()

            for j in range(len(pokemon_details)):
                if i != j:
                    evolution_name = chain[j]
                    evolution_id = pokemon_details[j].get('id')
                    evolution_type_poke = 'preevolution' if j < i else 'evolution'
                    adding_evolution = Evolution(
                        name=evolution_name,
                        pokemon_identification=evolution_id,
                        evolution_type=evolution_type_poke,
                        pokemon_from_identification=adding_pokemon)
                    adding_evolution.save()
def get_pokemon_from_api(id, evolves_from):
    url = 'https://pokeapi.co/api/v2/pokemon/{}'.format(id)
    response = requests.get(url=url)
    if (response.status_code == 404):
        self.stdout.write(
            self.style.ERROR('Pokemon {} does not exist'.format(id)))
        return None
    pokemon = response.json()
    new_pokemon = {
        'id':
        pokemon['id'],
        'name':
        pokemon['name'],
        'height':
        pokemon['height'],
        'weight':
        pokemon['weight'],
        'image':
        pokemon['sprites']['front_default']
        if pokemon['sprites']['front_default'] is not None else
        pokemon['sprites']['back_default']
    }
    if evolves_from is not None:
        pokemon_parent = Pokemon.objects.get(id=evolves_from)
        new_pokemon['evolves_from'] = pokemon_parent
    for stat in pokemon['stats']:
        stat_name = stat['stat']['name'].replace('-', '_')
        new_pokemon[stat_name] = stat['base_stat']
    Pokemon(**new_pokemon).save()
Esempio n. 5
0
def load_data_fromCsv(apps, schema_editor):
    path = django_apps.get_app_config("pokemon").path
    filepath = os.path.join(path, "Data", "pokemon.csv")

    def change_dict_key(key: str):
        key = key.lower()
        key = key.replace(" ", "_")
        key = key.replace(".", "")
        return key

    handlers_all = [
        handle_legendary,
        handle_ghost,
        handle_steel,
        handle_fire,
        handle_bugAndFlying,
        handle_nameStartWithG,
    ]

    with open(filepath, "r") as csv_file:
        csv_reader = csv.DictReader(csv_file, delimiter=',')
        for dict_row in csv_reader:
            # Pop "# key from dict"
            dict_row.pop("#", None)
            # Edit dictionary keys to fit data model
            dict_row = { change_dict_key(k): v for k, v in dict_row.items()}

            p = Pokemon(**dict_row)

            # Check handlers
            is_valid = True
            for handle in handlers_all:
                try:
                    handle(p)
                except ValueError as e:
                    is_valid = False
                    break
                except Exception as e:
                    is_valid = False

            if is_valid:
                p.save()       
Esempio n. 6
0
    def setUp(self):
        self.type = Type(name=Type.NORMAL)
        self.type.save()

        self.move = Move(name='Tackle', type=self.type, base_power=50)
        self.move.save()

        self.pokemon = Pokemon(name="Charmander", type1=self.type)
        self.pokemon.save()

        self.player_pokemon = PlayerPokemon(pokemon=self.pokemon, move1=self.move)
        self.player_pokemon.save()

        self.red = Player(username='******') # Will need to be changed to use a real Team
        self.red.save()

        self.player_pokemon.player = self.red
        self.player_pokemon.pokemon = self.pokemon
        self.player_pokemon.save()
Esempio n. 7
0
class TestRound(TestCase):
    def test_fight(self):
        self.do_setup(red_attack=3, red_speed=10, blue_attack=3, blue_speed=7)

        round1 = Round(battle=self.battle, red=self.red, blue=self.blue)
        round1.save()

        red_team = PlayerPokemon.objects.filter(player=round1.red)
        blue_team = PlayerPokemon.objects.filter(player=round1.blue)

        current_red_pokemon = None
        current_blue_pokemon = None

        for red_pokemon, blue_pokemon in izip(red_team, blue_team):
            if red_pokemon.lead:
                current_red_pokemon = red_pokemon

            if blue_pokemon.lead:
                current_blue_pokemon = blue_pokemon

            if current_red_pokemon and current_blue_pokemon:
                break

        self.assertEqual(self.battle.winner, None)
        self.assertEqual(current_red_pokemon.hp, 18)
        self.assertEqual(current_blue_pokemon.hp, 19)

        round1.red_selected_move = current_red_pokemon.move1
        round1.blue_selected_move = current_blue_pokemon.move1
        round1.save()

        round2 = round1.advance_round()
        round2.save()

        """
        red_team = PlayerPokemon.objects.filter(player=round1.red)
        blue_team = PlayerPokemon.objects.filter(player=round1.blue)

        for red_pokemon, blue_pokemon in izip(red_team, blue_team):
            if red_pokemon.lead:
                current_red_pokemon = red_pokemon
            if blue_pokemon.lead:
                current_blue_pokemon = blue_pokemon

        self.assertEqual(self.battle.winner, None)
        self.assertLess(current_red_pokemon.hp, 18)
        self.assertLess(current_blue_pokemon.hp, 18)

        round3 = round2.advance_round()
        round3.save()

        red_team = PlayerPokemon.objects.filter(player=round1.red)
        blue_team = PlayerPokemon.objects.filter(player=round1.blue)

        for red_pokemon, blue_pokemon in izip(red_team, blue_team):
            if red_pokemon.lead:
                current_red_pokemon = red_pokemon
            if blue_pokemon.lead:
                current_blue_pokemon = blue_pokemon

        self.assertEqual(self.battle.winner, None)
        self.assertEqual(current_red_pokemon.hp, 4)
        self.assertEqual(current_blue_pokemon.hp, 4)

        round4 = round3.advance_round()
        round4.save()

        red_team = PlayerPokemon.objects.filter(player=round4.red)
        blue_team = PlayerPokemon.objects.filter(player=round4.blue)

        for red_pokemon, blue_pokemon in izip(red_team, blue_team):
            if red_pokemon.lead:
                current_red_pokemon = red_pokemon
            if blue_pokemon.lead:
                current_blue_pokemon = blue_pokemon

        self.assertEqual(self.battle.winner, None)
        self.assertEqual(current_red_pokemon.hp, 1)
        self.assertEqual(current_blue_pokemon.hp, 1)

        round5 = round4.advance_round()

        red_team = PlayerPokemon.objects.filter(player=round4.red)
        blue_team = PlayerPokemon.objects.filter(player=round4.blue)

        for red_pokemon, blue_pokemon in izip(red_team, blue_team):
            if red_pokemon.lead:
                current_red_pokemon = red_pokemon
            if blue_pokemon.lead:
                current_blue_pokemon = blue_pokemon

        self.assertEqual(self.battle.winner, self.red)
        self.assertEqual(current_red_pokemon.hp, 1)
        self.assertEqual(current_blue_pokemon.hp, 0)
        """

    def do_setup(self, red_attack, red_speed, blue_attack, blue_speed):
        self.create_players()
        self.create_pokemon(blue_attack, blue_speed, red_attack, red_speed)

        self.battle = Battle(red=self.red, blue=self.blue)
        self.battle.save()

    def create_players(self):
        self.red = Player(username='******')
        self.red.save()
        self.blue = Player(username='******')
        self.blue.save()

    def create_pokemon(self, blue_attack, blue_speed, red_attack, red_speed):
        self.move_type = Type(name=Type.NORMAL)
        self.move_type.save()

        self.red_type = Type(name=Type.FIRE)
        self.red_type.save()

        self.blue_type = Type(name=Type.WATER)
        self.blue_type.save()

        self.move = Move(name='Tackle', type=self.move_type, base_power=50)
        self.move.save()

        self.red_pokemon = Pokemon(type1=self.red_type)
        self.red_pokemon.save()

        self.blue_pokemon = Pokemon(name='Squirtle', type1=self.blue_type,
                                    base_hp=44, base_attack=48, base_defence=65, base_special=50, base_speed=43)
        self.blue_pokemon.save()

        self.red_playerpokemon = PlayerPokemon(pokemon=self.red_pokemon, player=self.red,
                                               lead=True, move1=self.move)
        self.red_playerpokemon.save()
        self.blue_playerpokemon = PlayerPokemon(pokemon=self.blue_pokemon, player=self.blue,
                                                lead=True, move1=self.move)
        self.blue_playerpokemon.save()
def scrape():
    problem_pokemons = []
    base_url = 'https://pokeapi.co/api/v2/'
    generation_num = 5
    for generation in range(1, generation_num + 1):
        gen_obj = Generation(generation_number=generation)
        gen_obj.save()

        result_gen = requests.get(f'{base_url}generation/{generation}').text
        result_gen_json = json.loads(result_gen)
        pokemons = result_gen_json['pokemon_species']

        for countt, pokemon in enumerate(pokemons):
            print(countt)
            # species information
            url = pokemon['url'][:-1]
            pokemon_name = pokemon['name']
            pokemon_id = url[len(url) - url[::-1].index('/'):]
            print('pokemon id: ' + str(pokemon_id) + ', pokemon name: ' +
                  pokemon_name)
            result_species = requests.get(
                f'{base_url}pokemon-species/{pokemon_id}').text
            result_species_json = json.loads(result_species)

            # pokemon information
            result = requests.get(f'{base_url}pokemon/{pokemon_id}').text
            result_json = json.loads(result)

            p_name = result_json['name']
            p_weight = int(result_json['weight'])
            p_height = int(result_json['height'])
            p_base_exp = int(result_json['base_experience'])
            p_capture_rate = int(result_species_json['capture_rate'])
            p_cost = 1000 // p_capture_rate

            # sprites information
            back_default = result_json['sprites']['back_default']
            front_default = result_json['sprites']['front_default']
            svg_sprite = result_json['sprites']['other']['dream_world'][
                'front_default']

            # big sprite extraction
            sprite_page_external_url = f'https://bulbapedia.bulbagarden.net/wiki/{p_name}'
            sprite_bs = BeautifulSoup(
                requests.get(sprite_page_external_url).text, 'html.parser')
            p_name_cap = p_name.capitalize()
            sprite_temp_bs_res = sprite_bs.select(f"img[alt=\"{p_name_cap}\"]")
            if len(sprite_temp_bs_res) > 0:
                sprite_url = sprite_temp_bs_res[0]['src']
                sprite_url = 'http:' + sprite_url
            else:
                problem_pokemons.append(p_name)
                sprite_url = 'http://google.com'

            # sprites object
            sprite_obj = Sprite(name=p_name,
                                back_default=back_default,
                                front_default=front_default,
                                svg_sprite=svg_sprite,
                                big_sprite=sprite_url)
            sprite_obj.save()

            # stat information
            stats = result_json['stats']
            key_name = 'base_stat'
            hp = stats[0][key_name]
            attack = stats[1][key_name]
            defense = stats[2][key_name]
            special_attack = stats[3][key_name]
            special_attack_acc_rounds = (
                (special_attack - attack) / attack) // 0.5 + 1
            special_defense = stats[4][key_name]
            speed = stats[5][key_name]

            # stat object
            stat_obj = Stat(
                name=p_name,
                hp=hp,
                attack=attack,
                defense=defense,
                special_attack=special_attack,
                special_attack_acc_rounds=special_attack_acc_rounds,
                special_defense=special_defense,
                speed=speed)
            stat_obj.save()

            p_obj = Pokemon(idd=pokemon_id,
                            name=p_name,
                            weight=p_weight,
                            height=p_height,
                            base_exp=p_base_exp,
                            cost=p_cost,
                            user_defined=False,
                            generation=gen_obj,
                            sprites=sprite_obj,
                            stat=stat_obj)
            p_obj.save()

            for type_n in result_json['types']:
                name = type_n['type']['name']

                type_obj = Type.objects.get(name=name)
                p_obj.types.add(type_obj)
    with open('data.json', 'w') as f:
        json.dump(problem_pokemons, f)
Esempio n. 9
0
def import_pokemon(request):
    headers = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'
    }

    import_names = True
    import_forms = True
    import_regions = True

    # Import Pokemons from their names
    if import_names:
        json_url = "https://birkoss.com/pokemon_names.json"
        r = Request(url=json_url, headers=headers)
        with urllib.request.urlopen(r) as url:
            pokemons = json.loads(url.read().decode())
            for national_number in pokemons:
                pokemon = Pokemon.objects.filter(number=national_number)
                if len(pokemon) == 0:
                    data = {}
                    data['number'] = national_number
                    for mlid in ('names/en', 'names/fr', 'names/jp',
                                 'names/de', 'names/kr'):
                        if mlid in pokemons[national_number]:
                            data[mlid.replace(
                                "s/", "_")] = pokemons[national_number][mlid]

                    # Create the new Pokemon
                    pokemon = Pokemon(**data)
                    pokemon.save()
                    print("Created Pokemon: " + national_number)

    # Import Forms
    if import_forms:
        json_url = "https://birkoss.com/pokemon_forms.json"
        r = Request(url=json_url, headers=headers)

        with urllib.request.urlopen(r) as url:
            pokemons = json.loads(url.read().decode())
            for single_pokemon in pokemons:
                pokemon = Pokemon.objects.filter(
                    number=single_pokemon['number'])
                if len(pokemon) == 0:
                    data = {}
                    data['number'] = single_pokemon['number']
                    data['variant'] = Pokemon.objects.filter(
                        number=single_pokemon['national']).first()
                    for mlid in ('names/en', 'names/fr', 'names/jp',
                                 'names/de', 'names/kr'):
                        if mlid in single_pokemon:
                            data[mlid.replace("s/",
                                              "_")] = single_pokemon[mlid]

                    # Create the new Forms
                    pokemon = Pokemon(**data)
                    pokemon.save()
                    print("Created Form: " + single_pokemon['number'])

    if import_regions:
        json_url = "https://birkoss.com/pokemon_regions.json"
        r = Request(url=json_url, headers=headers)

        with urllib.request.urlopen(r) as url:
            regions = json.loads(url.read().decode())
            for single_region in regions:
                region = Region.objects.filter(slug=single_region).first()
                print(region)
                if region != None:
                    for single_pokemon in regions[single_region]:
                        pokemon = Pokemon.objects.filter(
                            number=single_pokemon['national']).first()
                        if pokemon != None:
                            pokemon_region = PokemonRegion.objects.filter(
                                pokemon=pokemon, region=region).first()
                            if pokemon_region == None:
                                pokemon_region = PokemonRegion(
                                    pokemon=pokemon,
                                    region=region,
                                    number=single_pokemon['regional'])
                                pokemon_region.save()
                                print("Created regional: " + single_region +
                                      " #" + single_pokemon['regional'])

    return HttpResponse("<p>Done</p>")
Esempio n. 10
0
 def create_pokemon(self, data):
     return Pokemon(name=data['identifier'])