update
authorNilsForssen <forssennils@gmail.com>
Mon, 7 Mar 2022 09:32:58 +0000 (10:32 +0100)
committerNilsForssen <forssennils@gmail.com>
Mon, 7 Mar 2022 09:32:58 +0000 (10:32 +0100)
laboration3/pokedex.py [changed mode: 0644->0755]
laboration4/__pycache__/common.cpython-38.pyc
laboration4/__pycache__/gamedata.cpython-38.pyc
laboration4/adventure.py [changed mode: 0644->0755]
laboration4/common.py
laboration4/gamedata.py
laboration4/uppgift_1.py [changed mode: 0644->0755]
laboration4/uppgift_2.py
laboration4/uppgift_3.py

old mode 100644 (file)
new mode 100755 (executable)
index aa86950..22c4288
@@ -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
index 3d2861ef0863c5426f4b3d8ab1b14201a50928a0..a1b86be9f2ad89f5a751d8e4213662e8df1055eb 100644 (file)
Binary files a/laboration4/__pycache__/common.cpython-38.pyc and b/laboration4/__pycache__/common.cpython-38.pyc differ
index af7b35d5026af8b1473b3764c1788e01884aaa36..2a6371ff1f0c7a0fe168c9b5f615258f1466bd84 100644 (file)
Binary files a/laboration4/__pycache__/gamedata.cpython-38.pyc and b/laboration4/__pycache__/gamedata.cpython-38.pyc differ
old mode 100644 (file)
new mode 100755 (executable)
index 29157dd..eeb9c34
@@ -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
 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"
index 91ab5bff78d3798afe1abf1c022fdd451f57d0f4..4eb091e3e55df32984fbf3f057e488e4c083efcf 100644 (file)
@@ -1,4 +1,5 @@
 
+# Load lines from csv-file
 def load_csv(filename):
     our_file = open(filename, "r")
     file_read = our_file.readlines()
index 85503d9b38258a818637c18f6a88073d87eb657e..e47cf8ebafaac2207d761db9f9d68225c0a4842f 100644 (file)
@@ -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",
old mode 100644 (file)
new mode 100755 (executable)
index 025a68efd6a5ad02e759fa96f3549f038f5cdcc7..d7356292896f1eee9a9fc037ba2787ac9fd55c9f 100644 (file)
@@ -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)
 
index d5dc26023dd9c3bc92483ef86d95993fa86e6ca6..458a41d9f31e6d2b1580c10f8be55c0b0ee51f21 100644 (file)
@@ -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))