#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Felix Muzny 11/22/2022 DS 2000 Lecture 21 - APIs and JSON Write a program, pokemon.py, that defines a Pokemon class then instantiates two Pokemon and has them battle each other. """ import random import requests import json class Pokemon: def __init__(self, health, attack_power, name): """ Create a new Pokemon Parameters ---------- health : int Starting life for this Pokemon. Returns ------- None. """ # set the class attribute of health # to the value of the parameter health self.health = health self.power = attack_power self.name = name def is_conscious(self): """ Returns whether or not this Pokemon is still conscious Returns ------- bool True if the health of this Pokemon is over 0 """ # bool - True if conscious # False otherwise return self.health > 0 def attack(self, other_pokemon): """ Have this pokemon attack another one, reducing its health! Parameters ---------- other_pokemon : Pokemon the pokemon being attacked Returns ------- None. """ # the other pokemon's health should be # reduced other_pokemon.health -= (self.power * 0.25) + random.randint(-2, 2) def __str__(self): # this function MUST *return* (NOT print) # a string s = self.name + "\n" s += "Health: " + str(self.health) + "\n" s += "Attack: " + str(self.power) + "\n" return s def create_pokemon_api(name): r = requests.get('https://pokeapi.co/api/v2/pokemon/' + name) poke_dict = json.loads(r.text) health = 0 attack = 0 for statistics in poke_dict["stats"]: stat = statistics["base_stat"] # access the dictionary that is the value # of the stat key name_of_stat = statistics["stat"]["name"] if name_of_stat == "hp": health = stat elif name_of_stat == "attack": attack = stat poke_obj = Pokemon(health, attack, name) return poke_obj def main(): print("Pokemon battle") poke1_name = input("pokemon 1? ") poliwrath = create_pokemon_api(poke1_name) # by default, printing an object will print # its type and where in your computer's memory it # is stored # print(str(poliwrath)) print(poliwrath) print() bulbasaur = create_pokemon_api("bulbasaur") print(bulbasaur) print() while poliwrath.is_conscious() and bulbasaur.is_conscious(): poliwrath.attack(bulbasaur) bulbasaur.attack(poliwrath) print(poliwrath) print(bulbasaur) print("+++++++++") print("Poliwrath consciousness:", poliwrath.is_conscious()) print("Bulbasaur consciousness:", bulbasaur.is_conscious()) if __name__ == "__main__": main()