pokedex_cli/command_catch.go

64 lines
1.6 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
)
func commandCatch(p *PokedexConfig, a *string) error {
if *a == "" {
return fmt.Errorf("you need to specify a Pokemon to catch")
}
var pokemonName string
var baseUrl string
for _, encounter := range p.LocalPokemons.PokemonEncounters {
if encounter.PokemonSummary.Name == *a {
pokemonName = *a
baseUrl = encounter.PokemonSummary.DataUrl
}
}
if pokemonName == "" {
baseUrl = "https://pokeapi.co/api/v2/pokemon/" + *a
}
// if pokemonName != *a {
// fmt.Println("this pokemon is not present in the current area")
// return nil
// }
body, exists := p.Cache.Get(baseUrl)
if !exists {
client := http.Client{}
resp, err := client.Get(baseUrl)
if err != nil {
return fmt.Errorf("could not make request to Pokedex API! Err: %w", err)
}
body, err = io.ReadAll(resp.Body)
defer resp.Body.Close()
if resp.StatusCode > 299 {
return fmt.Errorf("request returned non-200 code! Code: %v Body: %v", resp.StatusCode, body)
}
if err != nil {
return fmt.Errorf("could not read request body! Err: %w", err)
}
p.Cache.Add(baseUrl, body)
}
var pokemon PokemonDetails
if err := json.Unmarshal(body, &pokemon); err != nil {
return fmt.Errorf("could not unmarshal Pokemon data! err: %w", err)
}
fmt.Printf("Throwing a Pokeball at %s...\n", *a)
catchSuccess := rand.Intn(pokemon.BaseExperience)
if 2*catchSuccess >= pokemon.BaseExperience {
fmt.Printf("%s was caught!\n", pokemon.Name)
p.CaughtPokemon = append(p.CaughtPokemon, pokemon)
return nil
}
fmt.Printf("%s escaped!\n", *a)
return nil
}