Search in sources :

Example 1 with Pokemon

use of com.pokegoapi.api.pokemon.Pokemon in project PokeGOAPI-Java by Grover-c13.

the class Battle method beginDefenderBattle.

/**
	 * Starts this battle with an individual defender
	 *
	 * @param handler to handle this battle
	 * @throws RequestFailedException if an exception occurred while sending requests
	 */
private void beginDefenderBattle(final BattleHandler handler) throws RequestFailedException {
    lastRetrievedAction = null;
    queuedActions.clear();
    battleState = BattleState.STATE_UNSET;
    lastServerTime = api.currentTimeMillis();
    lastSendTime = lastServerTime;
    sentActions = false;
    List<Pokemon> attackers = new ArrayList<>();
    for (Pokemon pokemon : team) {
        if (!faintedPokemon.contains(pokemon.getId())) {
            attackers.add(pokemon);
        }
    }
    if (attackers.size() > 0 && defenderIndex < defenderCount) {
        StartGymBattleMessage.Builder builder = StartGymBattleMessage.newBuilder().setPlayerLatitude(api.getLatitude()).setPlayerLongitude(api.getLongitude()).setGymId(gym.getId()).setDefendingPokemonId(gym.getDefendingPokemon().get(defenderIndex).getId());
        for (Pokemon pokemon : attackers) {
            builder.addAttackingPokemonIds(pokemon.getId());
            if (pokemon.getStamina() < pokemon.getMaxStamina()) {
                throw new IllegalArgumentException("Pokemon must have full stamina to battle in a gym!");
            } else {
                String deployedFortId = pokemon.getDeployedFortId();
                if (pokemon.getFromFort() && deployedFortId != null && deployedFortId.length() > 0) {
                    throw new IllegalArgumentException("Cannot deploy Pokemon that is already in a gym!");
                }
            }
        }
        try {
            StartGymBattleMessage message = builder.build();
            ServerRequest request = new ServerRequest(RequestType.START_GYM_BATTLE, message);
            api.getRequestHandler().sendServerRequests(request);
            StartGymBattleResponse response = StartGymBattleResponse.parseFrom(request.getData());
            if (response.getResult() == StartGymBattleResponse.Result.SUCCESS) {
                battleId = response.getBattleId();
                attacker = response.getAttacker();
                defender = response.getDefender();
                activeDefender = new BattlePokemon(defender.getActivePokemon());
                activeAttacker = new BattlePokemon(attacker.getActivePokemon());
                updateLog(handler, response.getBattleLog());
            }
            sendActions(handler);
            handler.onStart(api, this, response.getResult());
        } catch (InvalidProtocolBufferException e) {
            battleId = "";
            throw new RequestFailedException(e);
        }
    } else {
        active = false;
    }
}
Also used : StartGymBattleResponse(POGOProtos.Networking.Responses.StartGymBattleResponseOuterClass.StartGymBattleResponse) RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) ArrayList(java.util.ArrayList) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) StartGymBattleMessage(POGOProtos.Networking.Requests.Messages.StartGymBattleMessageOuterClass.StartGymBattleMessage) Pokemon(com.pokegoapi.api.pokemon.Pokemon) ServerRequest(com.pokegoapi.main.ServerRequest)

Example 2 with Pokemon

use of com.pokegoapi.api.pokemon.Pokemon in project PokeGOAPI-Java by Grover-c13.

the class FightGymExample method main.

/**
	 * Fights gyms in the nearby area.
	 */
public static void main(String[] args) {
    OkHttpClient http = new OkHttpClient();
    final PokemonGo api = new PokemonGo(http);
    try {
        //Login and set location
        HashProvider hasher = ExampleConstants.getHashProvider();
        api.login(new PtcCredentialProvider(http, ExampleConstants.LOGIN, ExampleConstants.PASSWORD), hasher);
        api.setLocation(ExampleConstants.LATITUDE, ExampleConstants.LONGITUDE, ExampleConstants.ALTITUDE);
        List<Pokemon> pokemons = api.getInventories().getPokebank().getPokemons();
        //List to put all pokemon that can be used in a gym battle
        List<Pokemon> possiblePokemon = new ArrayList<>();
        for (Pokemon pokemon : pokemons) {
            //Check if pokemon has full health and is not deployed in a gym
            if (pokemon.getDeployedFortId().length() == 0) {
                if (pokemon.getStamina() < pokemon.getMaxStamina()) {
                    healPokemonFull(api, pokemon);
                    if (!(pokemon.isInjured() || pokemon.isFainted())) {
                        possiblePokemon.add(pokemon);
                    }
                    Thread.sleep(1000);
                } else {
                    possiblePokemon.add(pokemon);
                }
            } else {
                System.out.println(pokemon.getPokemonId() + " already deployed.");
            }
        }
        //Sort by highest CP
        Collections.sort(possiblePokemon, new Comparator<Pokemon>() {

            @Override
            public int compare(Pokemon primary, Pokemon secondary) {
                return Integer.compare(secondary.getCp(), primary.getCp());
            }
        });
        //Pick the top 6 pokemon from the possible list
        final Pokemon[] attackers = new Pokemon[6];
        for (int i = 0; i < 6; i++) {
            attackers[i] = possiblePokemon.get(i);
        }
        //Sort from closest to farthest
        MapObjects mapObjects = api.getMap().getMapObjects();
        List<Gym> gyms = new ArrayList<>(mapObjects.getGyms());
        Collections.sort(gyms, new Comparator<Gym>() {

            @Override
            public int compare(Gym primary, Gym secondary) {
                double lat = api.getLatitude();
                double lng = api.getLongitude();
                double distance1 = MapUtil.distFrom(primary.getLatitude(), primary.getLongitude(), lat, lng);
                double distance2 = MapUtil.distFrom(secondary.getLatitude(), secondary.getLongitude(), lat, lng);
                return Double.compare(distance1, distance2);
            }
        });
        for (Gym gym : gyms) {
            //Check if gym is attackable, and check if it is not owned by your team
            if (gym.isAttackable() && gym.getOwnedByTeam() != api.getPlayerProfile().getPlayerData().getTeam()) {
                //Walk to gym; Documented pathing in TravelToPokestopExample
                Point destination = new Point(gym.getLatitude(), gym.getLongitude());
                Path path = new Path(api.getPoint(), destination, 50.0);
                System.out.println("Traveling to " + destination + " at 50KMPH!");
                path.start(api);
                try {
                    while (!path.isComplete()) {
                        Point point = path.calculateIntermediate(api);
                        api.setLatitude(point.getLatitude());
                        api.setLongitude(point.getLongitude());
                        System.out.println("Time left: " + (int) (path.getTimeLeft(api) / 1000) + " seconds.");
                        Thread.sleep(2000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Beginning battle with gym.");
                //Create battle object
                Battle battle = gym.battle();
                //Start battle
                battle.start(new FightHandler(attackers));
                while (battle.isActive()) {
                    handleAttack(battle);
                }
                //Heal all pokemon after battle
                for (Pokemon pokemon : possiblePokemon) {
                    if (pokemon.getStamina() < pokemon.getMaxStamina()) {
                        healPokemonFull(api, pokemon);
                        Thread.sleep(1000);
                    }
                }
                //If prestige reaches 0, deploy your pokemon
                if (battle.getGym().getPoints() <= 0) {
                    Pokemon best = possiblePokemon.get(0);
                    System.out.println("Deploying " + best.getPokemonId() + " to gym.");
                    battle.getGym().deployPokemon(best);
                }
            }
        }
    } catch (RequestFailedException | InterruptedException e) {
        // failed to login, invalid credentials, auth issue or server issue.
        Log.e("Main", "Failed to login, captcha or server issue: ", e);
    }
}
Also used : Path(com.pokegoapi.util.path.Path) PtcCredentialProvider(com.pokegoapi.auth.PtcCredentialProvider) OkHttpClient(okhttp3.OkHttpClient) ArrayList(java.util.ArrayList) Point(com.pokegoapi.api.map.Point) MapObjects(com.pokegoapi.api.map.MapObjects) Point(com.pokegoapi.api.map.Point) Battle(com.pokegoapi.api.gym.Battle) RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) PokemonGo(com.pokegoapi.api.PokemonGo) HashProvider(com.pokegoapi.util.hash.HashProvider) Gym(com.pokegoapi.api.gym.Gym) Pokemon(com.pokegoapi.api.pokemon.Pokemon)

Example 3 with Pokemon

use of com.pokegoapi.api.pokemon.Pokemon in project PokeGOAPI-Java by Grover-c13.

the class TransferMultiplePokemon method main.

/**
	 * Transfers all bad pokemon from the player's inventory.
	 */
public static void main(String[] args) {
    OkHttpClient http = new OkHttpClient();
    PokemonGo api = new PokemonGo(http);
    try {
        HashProvider hasher = ExampleConstants.getHashProvider();
        api.login(new PtcCredentialProvider(http, ExampleConstants.LOGIN, ExampleConstants.PASSWORD), hasher);
        api.setLocation(ExampleConstants.LATITUDE, ExampleConstants.LONGITUDE, ExampleConstants.ALTITUDE);
        PokeBank pokebank = api.getInventories().getPokebank();
        List<Pokemon> pokemons = pokebank.getPokemons();
        List<Pokemon> transferPokemons = new ArrayList<>();
        //Find all pokemon of bad types or with IV less than 25%
        for (Pokemon pokemon : pokemons) {
            PokemonId id = pokemon.getPokemonId();
            double iv = pokemon.getIvInPercentage();
            if (iv < 90) {
                if (id == PokemonId.RATTATA || id == PokemonId.PIDGEY || id == PokemonId.CATERPIE || id == PokemonId.WEEDLE || id == PokemonId.MAGIKARP || id == PokemonId.ZUBAT || iv < 25) {
                    transferPokemons.add(pokemon);
                }
            }
        }
        System.out.println("Releasing " + transferPokemons.size() + " pokemon.");
        Pokemon[] transferArray = transferPokemons.toArray(new Pokemon[transferPokemons.size()]);
        Map<PokemonFamilyId, Integer> responses = pokebank.releasePokemon(transferArray);
        //Loop through all responses and find the total amount of candies earned for each family
        Map<PokemonFamilyId, Integer> candies = new HashMap<>();
        for (Map.Entry<PokemonFamilyId, Integer> entry : responses.entrySet()) {
            int candyAwarded = entry.getValue();
            PokemonFamilyId family = entry.getKey();
            Integer candy = candies.get(family);
            if (candy == null) {
                //candies map does not yet contain the amount if null, so set it to 0
                candy = 0;
            }
            //Add the awarded candies from this request
            candy += candyAwarded;
            candies.put(family, candy);
        }
        for (Map.Entry<PokemonFamilyId, Integer> entry : candies.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue() + " candies awarded");
        }
    } catch (RequestFailedException e) {
        // failed to login, invalid credentials, auth issue or server issue.
        Log.e("Main", "Failed to login. Invalid credentials, captcha or server issue: ", e);
    }
}
Also used : PtcCredentialProvider(com.pokegoapi.auth.PtcCredentialProvider) PokeBank(com.pokegoapi.api.inventory.PokeBank) OkHttpClient(okhttp3.OkHttpClient) PokemonId(POGOProtos.Enums.PokemonIdOuterClass.PokemonId) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PokemonFamilyId(POGOProtos.Enums.PokemonFamilyIdOuterClass.PokemonFamilyId) RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) PokemonGo(com.pokegoapi.api.PokemonGo) HashProvider(com.pokegoapi.util.hash.HashProvider) Pokemon(com.pokegoapi.api.pokemon.Pokemon) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with Pokemon

use of com.pokegoapi.api.pokemon.Pokemon in project PokeGOAPI-Java by Grover-c13.

the class TransferOnePidgeyExample method main.

/**
	 * Transfers one pidgey from the player's inventory.
	 */
public static void main(String[] args) {
    OkHttpClient http = new OkHttpClient();
    PokemonGo api = new PokemonGo(http);
    try {
        HashProvider hasher = ExampleConstants.getHashProvider();
        api.login(new PtcCredentialProvider(http, ExampleConstants.LOGIN, ExampleConstants.PASSWORD), hasher);
        api.setLocation(ExampleConstants.LATITUDE, ExampleConstants.LONGITUDE, ExampleConstants.ALTITUDE);
        List<Pokemon> pidgeys = api.getInventories().getPokebank().getPokemonByPokemonId(PokemonIdOuterClass.PokemonId.PIDGEY);
        if (pidgeys.size() > 0) {
            Pokemon pest = pidgeys.get(0);
            // print the pokemon data
            pest.debug();
            ReleasePokemonResponseOuterClass.ReleasePokemonResponse.Result result = pest.transferPokemon();
            Log.i("Main", "Transfered Pidgey result:" + result);
        } else {
            Log.i("Main", "You have no pidgeys :O");
        }
    } catch (RequestFailedException e) {
        // failed to login, invalid credentials, auth issue or server issue.
        Log.e("Main", "Failed to login. Invalid credentials, captcha or server issue: ", e);
    }
}
Also used : PtcCredentialProvider(com.pokegoapi.auth.PtcCredentialProvider) OkHttpClient(okhttp3.OkHttpClient) RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) PokemonGo(com.pokegoapi.api.PokemonGo) HashProvider(com.pokegoapi.util.hash.HashProvider) Pokemon(com.pokegoapi.api.pokemon.Pokemon)

Example 5 with Pokemon

use of com.pokegoapi.api.pokemon.Pokemon in project PokeGOAPI-Java by Grover-c13.

the class Inventories method updateInventories.

/**
	 * Updates the inventories with the latest data.
	 *
	 * @param response the get inventory response
	 */
public void updateInventories(GetInventoryResponse response) {
    lastInventoryUpdate = api.currentTimeMillis();
    for (InventoryItemOuterClass.InventoryItem inventoryItem : response.getInventoryDelta().getInventoryItemsList()) {
        InventoryItemDataOuterClass.InventoryItemData itemData = inventoryItem.getInventoryItemData();
        // hatchery
        PokemonData pokemonData = itemData.getPokemonData();
        if (pokemonData.getPokemonId() == PokemonId.MISSINGNO && pokemonData.getIsEgg()) {
            hatchery.addEgg(new EggPokemon(pokemonData));
        }
        // pokebank
        if (pokemonData.getPokemonId() != PokemonId.MISSINGNO) {
            pokebank.addPokemon(new Pokemon(api, inventoryItem.getInventoryItemData().getPokemonData()));
        }
        // items
        if (itemData.getItem().getItemId() != ItemId.UNRECOGNIZED && itemData.getItem().getItemId() != ItemId.ITEM_UNKNOWN) {
            ItemData item = itemData.getItem();
            if (item.getCount() > 0) {
                itemBag.addItem(new Item(api, item, itemBag));
            }
        }
        // candyjar
        if (itemData.getCandy().getFamilyId() != PokemonFamilyIdOuterClass.PokemonFamilyId.UNRECOGNIZED && itemData.getCandy().getFamilyId() != PokemonFamilyIdOuterClass.PokemonFamilyId.FAMILY_UNSET) {
            candyjar.setCandy(itemData.getCandy().getFamilyId(), itemData.getCandy().getCandy());
        }
        // player stats
        if (itemData.hasPlayerStats()) {
            api.getPlayerProfile().setStats(new Stats(itemData.getPlayerStats()));
        }
        // pokedex
        if (itemData.hasPokedexEntry()) {
            pokedex.add(itemData.getPokedexEntry());
        }
        if (itemData.hasEggIncubators()) {
            EggIncubators eggIncubators = itemData.getEggIncubators();
            for (EggIncubatorOuterClass.EggIncubator incubator : eggIncubators.getEggIncubatorList()) {
                EggIncubator eggIncubator = new EggIncubator(api, incubator);
                synchronized (this.lock) {
                    incubators.remove(eggIncubator);
                    incubators.add(eggIncubator);
                }
            }
        }
        if (itemData.hasAppliedItems()) {
            AppliedItems appliedItems = itemData.getAppliedItems();
            for (AppliedItem appliedItem : appliedItems.getItemList()) {
                this.appliedItems.put(appliedItem.getItemId(), appliedItem);
            }
        }
        Set<ItemId> stale = new HashSet<>();
        for (Map.Entry<ItemId, AppliedItem> entry : appliedItems.entrySet()) {
            ItemId itemId = entry.getKey();
            AppliedItem applied = entry.getValue();
            if (api.currentTimeMillis() >= applied.getExpireMs()) {
                stale.add(itemId);
            } else {
                Item item = itemBag.getItem(itemId);
                item.setApplied(applied);
                itemBag.addItem(item);
            }
        }
        for (ItemId item : stale) {
            appliedItems.remove(item);
            itemBag.getItem(item).removeApplied();
        }
    }
}
Also used : InventoryItemOuterClass(POGOProtos.Inventory.InventoryItemOuterClass) EggIncubators(POGOProtos.Inventory.EggIncubatorsOuterClass.EggIncubators) EggIncubatorOuterClass(POGOProtos.Inventory.EggIncubatorOuterClass) ItemId(POGOProtos.Inventory.Item.ItemIdOuterClass.ItemId) AppliedItem(POGOProtos.Inventory.AppliedItemOuterClass.AppliedItem) EggPokemon(com.pokegoapi.api.pokemon.EggPokemon) InventoryItemDataOuterClass(POGOProtos.Inventory.InventoryItemDataOuterClass) AppliedItems(POGOProtos.Inventory.AppliedItemsOuterClass.AppliedItems) EggPokemon(com.pokegoapi.api.pokemon.EggPokemon) Pokemon(com.pokegoapi.api.pokemon.Pokemon) PokemonData(POGOProtos.Data.PokemonDataOuterClass.PokemonData) HashMap(java.util.HashMap) Map(java.util.Map) AppliedItem(POGOProtos.Inventory.AppliedItemOuterClass.AppliedItem) ItemData(POGOProtos.Inventory.Item.ItemDataOuterClass.ItemData) HashSet(java.util.HashSet)

Aggregations

Pokemon (com.pokegoapi.api.pokemon.Pokemon)7 RequestFailedException (com.pokegoapi.exceptions.request.RequestFailedException)5 PokemonGo (com.pokegoapi.api.PokemonGo)3 PtcCredentialProvider (com.pokegoapi.auth.PtcCredentialProvider)3 HashProvider (com.pokegoapi.util.hash.HashProvider)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 OkHttpClient (okhttp3.OkHttpClient)3 PokemonFamilyId (POGOProtos.Enums.PokemonFamilyIdOuterClass.PokemonFamilyId)2 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)2 PokeBank (com.pokegoapi.api.inventory.PokeBank)2 Point (com.pokegoapi.api.map.Point)2 ServerRequest (com.pokegoapi.main.ServerRequest)2 Map (java.util.Map)2 PokemonData (POGOProtos.Data.PokemonDataOuterClass.PokemonData)1 PokemonId (POGOProtos.Enums.PokemonIdOuterClass.PokemonId)1 AppliedItem (POGOProtos.Inventory.AppliedItemOuterClass.AppliedItem)1 AppliedItems (POGOProtos.Inventory.AppliedItemsOuterClass.AppliedItems)1 Candy (POGOProtos.Inventory.CandyOuterClass.Candy)1 EggIncubatorOuterClass (POGOProtos.Inventory.EggIncubatorOuterClass)1