72 lines
2.0 KiB
Python
72 lines
2.0 KiB
Python
"""Item entities: weapons, armor, potions, scrolls.
|
|
|
|
An ``Item`` is both a world object (it sits on a floor tile until picked up)
|
|
and an inventory object (it carries the stats/effect the player uses). The
|
|
``category`` field is the single dispatch key: equipment slots accept only
|
|
"weapon"/"armor", quaffing accepts only "potion", reading accepts only "scroll".
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, field
|
|
|
|
from data.constants import COLORS
|
|
from data.items import ITEMS
|
|
|
|
__all__ = ["Item", "make_item"]
|
|
|
|
_VALID_CATEGORIES = ("weapon", "armor", "potion", "scroll")
|
|
|
|
# Roguelike-conventional glyphs/colors per category, used when an ITEMS entry
|
|
# does not override them.
|
|
_CATEGORY_GLYPHS = {
|
|
"weapon": "/",
|
|
"armor": "[",
|
|
"potion": "!",
|
|
"scroll": "?",
|
|
}
|
|
_CATEGORY_COLORS = {
|
|
"weapon": COLORS["weapon"],
|
|
"armor": COLORS["armor_item"],
|
|
"potion": COLORS["potion"],
|
|
"scroll": COLORS["scroll"],
|
|
}
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class Item:
|
|
name: str
|
|
category: str
|
|
x: int
|
|
y: int
|
|
stats: dict = field(default_factory=dict)
|
|
effect: dict = field(default_factory=dict)
|
|
glyph: str = "?"
|
|
color: tuple = (200, 200, 200)
|
|
blocks: bool = False
|
|
is_alive: bool = True
|
|
|
|
|
|
def make_item(name: str, x: int, y: int) -> Item:
|
|
"""Construct an ``Item`` from the ``ITEMS`` catalog.
|
|
|
|
``stats``/``effect`` are copied so per-instance mutation (e.g. a cooldown
|
|
scribbled onto an equipped item) never leaks back into the catalog.
|
|
"""
|
|
spec = ITEMS.get(name)
|
|
if spec is None:
|
|
raise KeyError(f"unknown item: {name!r}")
|
|
category = spec["category"]
|
|
if category not in _VALID_CATEGORIES:
|
|
raise ValueError(f"{name!r} has invalid category {category!r}")
|
|
return Item(
|
|
name=name,
|
|
category=category,
|
|
x=x,
|
|
y=y,
|
|
stats=dict(spec.get("stats", {})),
|
|
effect=dict(spec.get("effect", {})),
|
|
glyph=spec.get("glyph", _CATEGORY_GLYPHS[category]),
|
|
color=tuple(spec.get("color", _CATEGORY_COLORS[category])),
|
|
)
|