os.makedirs(location)
+class SaveGame(object):
+ def __init__(self, slot_num):
+ self.slot_num = slot_num
+
+ def save_path(self):
+ return save_path('slot_%s.json' % (self.slot_num,))
+
+ def get_game_data(self):
+ try:
+ with open(self.save_path(), 'r') as save_file:
+ return json.load(save_file)
+ except IOError:
+ return None
+ except Exception as e:
+ print "Error reading savegame in slot %s: %s" % (self.slot_num, e)
+ return None
+
+ def save(self, state):
+ ensure_save_path_exists()
+ save_data = {
+ 'timestamp': datetime.now().ctime(),
+ 'data': state.gameboard.export(),
+ }
+ with open(self.save_path(), 'w') as save_file:
+ json.dump(save_data, save_file)
+
+ def load(self):
+ game_data = self.get_game_data()
+ if game_data is None:
+ return
+ return GameState.load(game_data['data'])
+
+
class LoadSaveGameBase(Scene):
def __init__(self, state):
super(LoadSaveGameBase, self).__init__(state)
self.slots[slot_num] = slot
selector.add(slot)
- def save_path(self, slot_num):
- return save_path('slot_%s.json' % (slot_num,))
-
- def get_game_data(self, slot_num):
- try:
- with open(self.save_path(slot_num), 'r') as save_file:
- return json.load(save_file)
- except IOError:
- return None
- except Exception as e:
- print "Error reading savegame in slot %s: %s" % (slot_num, e)
- return None
-
def make_slot_widget(self, slot_num):
- game_data = self.get_game_data(slot_num)
+ game_data = SaveGame(slot_num).get_game_data()
y_offset = 74 * slot_num
slot = SaveSlotWidget((100, y_offset), slot_num, game_data)
slot.add_callback('click', lambda event: self.perform_action(slot_num))
def succeed(self):
raise NotImplementedError("Success not implemented.")
- from naja.scenes.menu import MenuScene
- sound.play_sound('chirp.ogg', volume=0.5)
- SceneChangeEvent.post(MenuScene)
def perform_action(self, slot_num):
raise NotImplementedError("Nothing to see here.")
class SaveGameScene(LoadSaveGameBase):
def perform_action(self, slot_num):
- save_data = {
- 'timestamp': datetime.now().ctime(),
- 'data': self.state.gameboard.export(),
- }
try:
- ensure_save_path_exists()
- with open(self.save_path(slot_num), 'w') as save_file:
- json.dump(save_data, save_file)
+ SaveGame(slot_num).save(self.state)
except Exception as e:
print "Error saving game in slot %s: %s" % (slot_num, e)
self.fail()
class LoadGameScene(LoadSaveGameBase):
def perform_action(self, slot_num):
- game_data = self.get_game_data(slot_num)
- if game_data is not None:
- state = GameState.load(game_data['data'])
+ state = SaveGame(slot_num).load()
+ if state is not None:
LoadGameEvent.post(state)
self.succeed()
else: