roomloader.py 1.71 KB

import json
import utils

class RoomLoader(object):

  def __init__(self, directory):
    self.directory = directory

  def _get_room_file(self, room_name):
    filename = self.directory + '/' + room_name + ".txt"
    room_data = utils.load_object_from_file(filename)
    if room_data is None:
      print("Error opening room file: {}".format(room_name))
      return {}
    return room_data

  def _save_room_file(self, room_name, room_data):
    filename = self.directory + '/' + room_name + ".txt"
    utils.save_object_to_file(room_data, filename)

  def get_title(self, room_name):
    return self._get_room_file(room_name).get('title', None)

  def get_description(self, room_name):
    return self._get_room_file(room_name).get('description', None)

  def get_exits(self, room_name):
    return self._get_room_file(room_name).get('exits', None)

  def get_look_items(self, room_name):
    return self._get_room_file(room_name).get('look_items', None)

  def get_inventory(self, room_name):
    return self._get_room_file(room_name).get('inventory', None)

  def add_to_inventory(self, room_name, item_name, quantity):
    room_data = self._get_room_file(room_name)
    if item_name in room_data['inventory']:
      room_data['inventory'][item_name] += quantity
    else:
      room_data['inventory'][item_name] = 1
    self._save_room_file(room_name, room_data)
    return True

  def remove_from_inventory(self, room_name, item_name, quantity):
    room_data = self._get_room_file(room_name)
    if item_name in room_data['inventory']:
      room_data['inventory'][item_name] -= quantity
    if room_data['inventory'][item_name] <= 0:
      del room_data['inventory'][item_name]
    self._save_room_file(room_name, room_data)
    return True