JustCaptain kod-buduschego
fe9c6c08be73ce67e8771ed2945bb1d512df3ae4
Перейти к файлу
Код
kod-buduschego Python 2025-20263.6. Работа с файламиpracticeschatgpttask_6main.py
anc update c70a58f 8 октября 2026 г.
main.py
"""
6. Инвентарь выживших после апокалипсиса
Контекст: склад ресурсов.

Файл: inventory.json

Пример:

{
"water": 12,
"food": 5,
"ammo": 80
}

Задачи:

- Уменьшить количество ресурсов после “дня”.
- Добавить новые предметы.
- Проверить, чего осталось меньше 10.
- Сохранить изменения.

"""

import json


class InventoryAPI:
    def __init__(self, path_file: str) -> None:
        self.path: str = path_file

    def add_item(self, key: str, value: int) -> None:
        data: dict[str, int] = self.__load()
        if data.get(key):
            data[key] += value
        else:
            data[key] = value
        self.__save(data=data)

    def reduce_after_the_day(self) -> None:
        data: dict[str, int] = self.__load()
        if data.get("food") and data["food"] > 0:
            data["food"] -= 1
        if data.get("water") and data["water"] > 0:
            data["water"] -= 1

    def check(self, less: int) -> dict[str, int]:
        data: dict[str, int] = self.__load()
        result: dict[str, int] = {}
        for key, value in data.items():
            if value <= less:
                result[key] = value
        return result

    def __save(self, data: dict[str, int]) -> None:
        with open(file=self.path, mode="w", encoding="utf-8") as file:
            json.dump(obj=data, fp=file, ensure_ascii=False, indent=2)

    def __load(self) -> dict[str, int]:
        with open(file=self.path, mode="r", encoding="utf-8") as file:
            data: dict[str, int] = json.load(fp=file)
        return data


player_inventory = InventoryAPI(path_file="inventory.json")
print(player_inventory.check(less=20))
player_inventory.add_item(key="food", value=18)
print(player_inventory.check(less=25))