From: NilsForssen Date: Mon, 7 Mar 2022 09:32:58 +0000 (+0100) Subject: update X-Git-Url: https://gitweb.forssennils.se/?a=commitdiff_plain;h=c4af805c7650523fbdb57dc9baa22e89b11dda59;p=TDDE44.git update --- diff --git a/laboration3/pokedex.py b/laboration3/pokedex.py old mode 100644 new mode 100755 index aa86950..22c4288 --- a/laboration3/pokedex.py +++ b/laboration3/pokedex.py @@ -1,24 +1,40 @@ -# 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") @@ -27,6 +43,19 @@ def get_json_as_dict(url): 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: @@ -36,13 +65,20 @@ def get_abilities(pokemon, pokemon_data_list): 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") @@ -67,4 +103,4 @@ def print_info(name, abilities, language="en"): if __name__ == "__main__": - main() + main() \ No newline at end of file diff --git a/laboration4/__pycache__/common.cpython-38.pyc b/laboration4/__pycache__/common.cpython-38.pyc index 3d2861e..a1b86be 100644 Binary files a/laboration4/__pycache__/common.cpython-38.pyc and b/laboration4/__pycache__/common.cpython-38.pyc differ diff --git a/laboration4/__pycache__/gamedata.cpython-38.pyc b/laboration4/__pycache__/gamedata.cpython-38.pyc index af7b35d..2a6371f 100644 Binary files a/laboration4/__pycache__/gamedata.cpython-38.pyc and b/laboration4/__pycache__/gamedata.cpython-38.pyc differ diff --git a/laboration4/adventure.py b/laboration4/adventure.py old mode 100644 new mode 100755 index 29157dd..eeb9c34 --- a/laboration4/adventure.py +++ b/laboration4/adventure.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # # A text-based adventure game, based on # https://github.com/codinggrace/text_based_adventure_game @@ -27,34 +27,46 @@ 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" diff --git a/laboration4/common.py b/laboration4/common.py index 91ab5bf..4eb091e 100644 --- a/laboration4/common.py +++ b/laboration4/common.py @@ -1,4 +1,5 @@ +# Load lines from csv-file def load_csv(filename): our_file = open(filename, "r") file_read = our_file.readlines() diff --git a/laboration4/gamedata.py b/laboration4/gamedata.py index 85503d9..e47cf8e 100644 --- a/laboration4/gamedata.py +++ b/laboration4/gamedata.py @@ -1,5 +1,6 @@ from pictures import * +# State tree, Start -> End ADVENTURE_TREE = { "Start": ["Blue", "Red"], "Blue": ["Chest", "Guard"], @@ -21,6 +22,7 @@ ADVENTURE_TREE = { "Steal_axe": ["Die"] } +# Functions pointer to current states picture PICTURES = { "Start": print_doors, "Sneak": print_guard, @@ -33,6 +35,7 @@ PICTURES = { "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. @@ -72,6 +75,7 @@ Do you flee for your life or attack it with your bare hands?""", "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", diff --git a/laboration4/uppgift_1.py b/laboration4/uppgift_1.py old mode 100644 new mode 100755 diff --git a/laboration4/uppgift_2.py b/laboration4/uppgift_2.py index 025a68e..d735629 100644 --- a/laboration4/uppgift_2.py +++ b/laboration4/uppgift_2.py @@ -1,37 +1,50 @@ +#!/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) diff --git a/laboration4/uppgift_3.py b/laboration4/uppgift_3.py index d5dc260..458a41d 100644 --- a/laboration4/uppgift_3.py +++ b/laboration4/uppgift_3.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python3 + import common import uppgift_1 import uppgift_2 @@ -5,20 +7,26 @@ import matplotlib 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))