-# pokedex.py
+#!/usr/bin/env python3
+
import requests
-import json
import sys
API_SERVER = "https://www.ida.liu.se/~TDDE44/pokeapi/"
def main():
+ """Mainloop
+
+ Raises:
+ ValueError: Script is not run with mandatory pokemon and language argument
+ """
data = get_json_as_dict(API_SERVER + "api/v2/pokemon/")
pokemons = data.get("results")
try:
request_name = sys.argv[1]
except IndexError:
- raise ValueError("Must specify pokemon to request data of")
+ raise ValueError("Must specify pokemon and language")
abilities = get_abilities(request_name, pokemons)
print_info(request_name, abilities)
def get_json_as_dict(url):
+ """Fetch data from url in JSON-format
+
+ Args:
+ url (str): API url
+
+ Raises:
+ requests.RequestException: data request unsuccessful
+
+ Returns:
+ dict: data in JSON-format
+ """
r = requests.get(url)
if r.status_code != 200:
raise requests.RequestException("Request unsuccessful")
def get_abilities(pokemon, pokemon_data_list):
+ """Get abilities of named pokemon from lookup list
+
+ Args:
+ pokemon (str): Requested pokemon
+ pokemon_data_list (list): lookup list of all pokemons
+
+ Raises:
+ ValueError: Pokemon requested not found in the given list
+
+ Returns:
+ list: Abilities of pokemon
+ """
+ # Linear search for the requested pokemon and get the pokemon-url
poke_url = None
for poke in pokemon_data_list:
if poke.get("name") == pokemon:
raise ValueError(f"No pokemon named {pokemon}")
pokemon_data = get_json_as_dict(API_SERVER + poke_url)
-
return pokemon_data.get("abilities")
def print_info(name, abilities, language="en"):
- print(f"{name} has {len(abilities)}.\n")
+ """Print the name and abilities of the pokemon
+
+ Args:
+ name (str): Name of pokemon
+ abilities (list): list of abilities of the pokemon
+ language (str, optional): Language to print in. Defaults to "en".
+ """
+ print(f"{name} has {len(abilities)} abilities.\n")
+ # Repeat for every ability
for ability in abilities:
abil = ability.get("ability")
abil_url = abil.get("url")
if __name__ == "__main__":
- main()
+ main()
\ No newline at end of file
-#!/usr/bin/env python
+#!/usr/bin/env python3
#
# A text-based adventure game, based on
# https://github.com/codinggrace/text_based_adventure_game
from pictures import *
from gamedata import *
-
+# Moves to next state basted on current state and choice
def get_next_state(curr_state):
+
+ # Get next states
succ = ADVENTURE_TREE.get(curr_state)
+
+ # If there is more than one possible next state, let the user decide
if len(succ) > 1:
for i, s in enumerate(succ):
- print(f"{i + 1} {OPTIONS.get(s)}")
+ print(f"{i + 1} {OPTIONS[s]}")
inp = input()
return succ[int(inp) - 1]
+
return succ[0]
-
+
+# Finds the destricption to current state and prints it
def print_desc(curr_state):
print(DESCRIPTIONS.get(curr_state))
+# Prints the current states picture
def print_pic(curr_state):
pic = PICTURES.get(curr_state)
if pic is not None:
pic()
-
+
+# Mainloop
def main():
+
name = input("What's your name?\n>> ")
print("Welcome {} to the adventure of your life. Try to survive and find \
the treasure!".format(name.upper()))
current_state = "Start"
+
+ # Gameloop, move through states
while current_state != "End":
print_pic(current_state)
print_desc(current_state)
current_state = get_next_state(current_state)
+
# Non-refractored code
def main_old():
current_state = "Start"
+# Load lines from csv-file
def load_csv(filename):
our_file = open(filename, "r")
file_read = our_file.readlines()
from pictures import *
+# State tree, Start -> End
ADVENTURE_TREE = {
"Start": ["Blue", "Red"],
"Blue": ["Chest", "Guard"],
"Steal_axe": ["Die"]
}
+# Functions pointer to current states picture
PICTURES = {
"Start": print_doors,
"Sneak": print_guard,
"Win": print_win
}
+# Desciption of a state
DESCRIPTIONS = {
"Start": """You enter a room, and you see a blue door to your left and a \
red door to your right.
"Steal_axe": "The axe is glued to the guard and he wakes up, u ded!"
}
+# Flavor text of every state
OPTIONS = {
"Blue": "Blue",
"Red": "Red",
+#!/usr/bin/env python3
+
import common
import sys
import matplotlib
import matplotlib.pyplot as plt
+# Mainloop
def main():
+
+ # matplotlib setup
matplotlib.use('AGG')
plt.figure()
+
try:
csv_file_path = sys.argv[1]
except IndexError:
raise ValueError("Need csv file argument")
+
data = common.load_csv(csv_file_path)
x, y = prepare_data2(data)
draw_diagram2([x, y], csv_file_path[4:])
+
plt.ylabel("Antal koppar")
plt.xlabel("Koppar kaffe per dag")
plt.legend(loc='upper left', bbox_to_anchor=(1, 0, 1, 1))
plt.savefig("uppgift_2.png", bbox_inches="tight")
-
-
+# Format the data into relevant axis
def prepare_data2(d):
+
days = d[0].split(';')
cups_per_day = [0] * 7
data = d[1:]
+
+ # Convert data from str to int and sum it up into y-values
for line in data:
for day_i, cups in enumerate(line.split(';')[1:]):
cups_per_day[day_i] += int(cups)
+
+ # Remove empty string and remove unwanted newlines
days.pop(0)
days = [day.strip() for day in days]
+
return [days, cups_per_day]
-
+# Uses data as arguments and draws it onto axis
def draw_diagram2(values, name):
plt.plot(values[0], values[1], label=name)
+#!/usr/bin/env python3
+
import common
import uppgift_1
import uppgift_2
import matplotlib.pyplot as plt
import sys
-matplotlib.use("AGG")
-plt.figure()
-
+# Mainloop
def main():
+
+ # matplotlib setup
+ matplotlib.use("AGG")
+ plt.figure()
+
+ # Accept multiple csv-files
arg_len = len(sys.argv) - 1
csv_files = list()
for i in range(arg_len):
csv_files.append(sys.argv[i + 1])
+ # load and plot the data for every csv-file
for filer in csv_files:
data = common.load_csv(filer)
# uppgift_1.draw_diagram(uppgift_1.prepare_data(data))
uppgift_2.draw_diagram2(uppgift_2.prepare_data2(data), filer[4:])
+ # Adds labels and info about current functions
plt.xlabel("Dagar")
plt.ylabel("Antal koppar")
plt.legend(loc='upper left', bbox_to_anchor=(1, 0, 1, 1))