view skaapsteker/gamestate.py @ 479:fb9258d66137

New Main Menu
author Stefano Rivera <stefano@rivera.za.net>
date Sat, 09 Apr 2011 21:59:59 +0200
parents 95527fd29872
children b48c194c4af9
line wrap: on
line source

import os
import json

from . import data
from .sprites.base import find_sprite


class StateProxy(object):

    def __init__(self, data):
        self.__dict__['_data'] = data # should be a dict

    def __getattr__(self, key):
        try:
            value = self._data[key]
        except KeyError:
            raise AttributeError
        if isinstance(value, dict):
            return StateProxy(value)
        else:
            return value

    def __setattr__(self, key, value):
        self._data[key] = value

    def __iter__(self):
        return self._data.iterkeys()

    def __contains__(self, key):
        return key in self._data

    def copy(self):
        return self._data.copy()


class GameState(object):

    def __init__(self, game_file):
        self._game_file = game_file
        self.world = None

    def can_resume(self):
        return os.path.exists(self._game_file)

    def load_game(self, game_file=None):
        if game_file is None:
            game_file = self._game_file
        raw_data = open(game_file, "rb").read()
        self.data = json.loads(raw_data)
        self.world = StateProxy(self.data)

    def new_game(self):
        self.load_game(data.filepath("game.json"))
        self.save_game()

    def save_game(self):
        if self.world is None:
            return
        save_dir, _ = os.path.split(self._game_file)
        if not os.path.exists(save_dir):
            try:
                os.makedirs(save_dir)
            except:
                print "Cannot create save game directory."
                return
        try:
            json.dump(self.data, open(self._game_file, "wb"))
        except:
            print "Cannot create save game file."

    def create_sprites(self, level):
        sprites = []
        for stype, key in [
            ('items', 'items'),
            ('npcs', 'npcs')]:
            for sprite_name, sprite_dict in self.data[key].items():
                sprite_dict = sprite_dict.copy()
                sprite_dict['name'] = sprite_name
                sprite_dict['world'] = self.world
                if sprite_dict.pop('level') == level:
                    sprites.append(find_sprite(sprite_dict, stype))
        return sprites