1/23
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
from typing import Dict, Tuple
Imports specific names from a module. Here it pulls Dict
and Tuple
from typing
for type hints.
class GameCharacter:
Defines a class named GameCharacter
.
def init( self, character_id: str, resources: Dict[str, Dict[str, float]] | None = None, x_pos: int = 0, y_pos: int = 0, ) -> None:
Defines the constructor for the class with type hints. It sets up character ID, resources, and position.
self.character_id: str = character_id
Creates/assigns the instance attribute character_id
with a type hint.
if resources is None:
Checks whether a variable is None
to decide whether to set default values.
resources = { "HP": {"current": 3500.0, "max": 3500.0}, "MP": {"current": 100.0, "max": 100.0}, "stamina": {"current": 100.0, "max": 100.0}, }
Creates a dictionary literal of default resources.
self.resources: Dict[str, Dict[str, float]] = {}
Initializes the self.resources
dictionary attribute with a type hint.
for name, vals in resources.items():
Starts a for-loop iterating over all resource entries.
cur = float(vals.get("current", 0.0))
Fetches a value from a dictionary with a default and converts it to float.
mx = float(vals.get("max", cur))
Gets the maximum allowed value for the resource, defaulting to current if missing.
cur = max(0.0, min(cur, mx))
Clamps a value within a lower and upper bound using min
/max
.
self.resources[name] = {"current": cur, "max": mx}
Writes a normalized resource entry into the resources dictionary.
self.inventory: Dict[str, int] = {}
Initializes an empty inventory dictionary with type hints.
def move_up(self) -> None:
Defines a method to move the character up.
self.y_pos += 1
Moves up by increasing the y coordinate.
def move_down(self) -> None:
Defines a method to move the character down.
self.y_pos -= 1
Moves down by decreasing the y coordinate.
def move_left(self) -> None:
Defines a method to move the character left.
self.x_pos -= 1
Moves left by decreasing the x coordinate.
def move_right(self) -> None:
Defines a method to move the character right.
self.x_pos += 1
Moves right by increasing the x coordinate.
if num_items < 1:
Validates input; returns early if the quantity is less than 1.
self.inventory[item] = self.inventory.get(item, 0) + int(num_items)
Increments an item's count in the inventory, using 0 when the key is missing.
if name == "__main__":
Main-guard: runs the script’s main()
only when executed directly.