From 0fc0fc33da927af90945dd515a4e0698ba09334e Mon Sep 17 00:00:00 2001 From: alwayscompiling Date: Sat, 30 Jul 2022 23:12:40 -0400 Subject: [PATCH] Filled out to and from dict functions and a few others. --- data/category.py | 62 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 55 insertions(+), 7 deletions(-) diff --git a/data/category.py b/data/category.py index 894be21..bf5c7e5 100644 --- a/data/category.py +++ b/data/category.py @@ -1,17 +1,35 @@ """File for Category class.""" -from data.score import Score # pylint: disable=import-error +from typing import Optional + +from data.score import Score, ScoreTime # pylint: disable=import-error class Category: """Stores a category's information and relative scores.""" - def __init__(self, name: str, ascending: bool, time_record: bool) -> None: - self._name = name - self._ascending = ascending - self._time_record = time_record + def __init__( + self, + name: str, + ascending: Optional[bool] = False, + time_record: Optional[bool] = False, + ) -> None: + self._name: str = name + self._ascending: bool = ascending + self._time_record: bool = time_record self._scores: dict(Score) = {} + def __str__(self) -> str: + """Creates a string from the class.""" + ret_str = f"{self.name}\n" + ret_str += f"ascending: {self.ascending}\n" + ret_str += f"time_record: {self.time_record}" + + for score in self.scores: + ret_str += f"{score}\n" + + return ret_str + @property def ascending(self) -> bool: """Getter for ascending bool.""" @@ -33,13 +51,43 @@ class Category: return self._scores.values() def add_score(self, score: Score) -> None: - """Adds a score to dictionary storage. Sorts dictionary by score value.""" + """Adds a score to dictionary storage. Then sorts dictionary by score value.""" + if score.user in self._scores: + del self._scores[score.user] self._scores[score.user] = score self._scores = dict( sorted(self._scores.items(), key=lambda x: x[1].score, reverse=not self.ascending) ) + def from_dict(self, data: dict) -> None: + """Fills out category from passed dictionary""" + + self._ascending = data["ascending"] + self._time_record = data["time_record"] + for user, score in data["scores"].items(): + if self.time_record: + self.add_score(ScoreTime(user, score)) + else: + self.add_score(Score(user, score)) + + def get_user_score(self, user: str) -> Score: + """Gets a user's score. None if doesn't exist.""" + if user in self.scores: + return self._scores[user] + return None + def remove_score(self, score: Score) -> None: """Removes a score from dictionary storage.""" - self._scores.pop(score.user) + score = self._scores.pop(score.user) + del score + + def to_dict(self) -> dict: + """Saves category data as a python dictionary.""" + data = {} + data["ascending"] = self.ascending + data["time_record"] = self.time_record + for score in self.scores: + data["scores"][score.user] = score.score + + return data