changeset 88:74ce25ec2073

Autosave & load support
author Neil Muller <drnlmuller@gmail.com>
date Wed, 09 May 2012 20:07:14 +0200
parents d93e1ea2bd0d
children 5dd66c1d8f26
files gamelib/game_base.py gamelib/gamegui.py gamelib/main.py gamelib/mainmenu.py
diffstat 4 files changed, 71 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/gamelib/game_base.py	Wed May 09 20:06:44 2012 +0200
+++ b/gamelib/game_base.py	Wed May 09 20:07:14 2012 +0200
@@ -1,3 +1,5 @@
+import sys
+import os
 
 
 def get_subclasses(base_class, leaf_only=True):
@@ -10,6 +12,26 @@
     return subclasses
 
 
+def get_save_filename():
+    """Determine the base filename for auto saves"""
+    app = "sypikslang"
+    if sys.platform.startswith('win'):
+        if "APPDATA" in os.environ:
+            base = os.path.join(os.environ["APPDATA"], app)
+        else:
+            base = os.path.join(os.path.expanduser("~"), "." + app)
+    elif 'XDG_DATA_HOME' in os.environ:
+        base = os.path.join(os.environ["XDG_DATA_HOME"], app)
+    else:
+        base = os.path.join(os.path.expanduser("~"), ".local", "share", app)
+    if not os.path.exists(base):
+        os.makedirs(base, mode=0770)
+    if os.path.isdir(base):
+        return os.path.join(base, 'gamestate.json')
+    print 'save game directory is not a directory %s' % base
+    return None
+
+
 class Science(object):
     NAME = None
     PREREQUISITES = ()
--- a/gamelib/gamegui.py	Wed May 09 20:06:44 2012 +0200
+++ b/gamelib/gamegui.py	Wed May 09 20:07:14 2012 +0200
@@ -4,8 +4,15 @@
 """Gui for the actual game"""
 
 from pygame import image
+try:
+    import simplejson
+    json = simplejson
+except ImportError:
+    import json
+
 
 from gamelib.data import filepath
+from gamelib.game_base import get_save_filename
 from gamelib.gui_base import Window, TextLabel, font_small, font_medium
 from gamelib.gui import BigButton, ImageDrawable
 from gamelib.engine import PopWindow, AddWindow
@@ -441,16 +448,17 @@
 class LabWindow(Window):
     """Window for the research lab"""
 
-    def __init__(self, screen):
+    def __init__(self, screen, game_dict):
         super(LabWindow, self).__init__(screen)
         self.screen = screen
-        self.game = Game()
+        self.game = Game(game_dict)
         exit = ExitGameButton()
         self.add_child(exit)
         end_turn = EndTurnButton(self)
         self.add_child(end_turn)
         reset = ResetButton(self)
         self.add_child(reset)
+        self.autosave = get_save_filename()
 
         self.points = ValueLabel((10, 75), 'Available Human Resources')
         self.add_child(self.points)
@@ -501,6 +509,11 @@
         self.update_widgets()
         self.develop.update_widgets()
         self.activity.update_widgets()
+        game_data = self.game.save_data()
+        if self.autosave:
+            savefile = open(self.autosave, 'w')
+            json.dump(game_data, savefile)
+            savefile.close()
         AddWindow.post(results)
 
     def update(self):
--- a/gamelib/main.py	Wed May 09 20:06:44 2012 +0200
+++ b/gamelib/main.py	Wed May 09 20:07:14 2012 +0200
@@ -21,6 +21,9 @@
     parser.add_option('--no-sound', action="store_false", default=True,
             dest="sound", help="disable sound")
 
+    parser.add_option('--load', type="string", default=None,
+            dest="load", help="Save game to load")
+
     return parser.parse_args(args)
 
 
@@ -32,5 +35,5 @@
         pygame.mixer.init(FREQ, BITSIZE, CHANNELS, BUFFER)
     screen = pygame.display.set_mode(SCREEN)
     engine = Engine(screen)
-    window = MainMenu(screen)
+    window = MainMenu(screen, opts.load)
     engine.run(window)
--- a/gamelib/mainmenu.py	Wed May 09 20:06:44 2012 +0200
+++ b/gamelib/mainmenu.py	Wed May 09 20:07:14 2012 +0200
@@ -4,8 +4,15 @@
 """The main menu"""
 
 import pygame
+import os
 from pygame import image
 
+try:
+    import simplejson
+    json = simplejson
+except ImportError:
+    import json
+
 from gamelib import data
 from gamelib.gui_base import Window
 from gamelib.gui import BigButton
@@ -13,6 +20,7 @@
 from gamelib.gamegui import LabWindow
 
 from gamelib.constants import WIDTH, HEIGHT
+from gamelib.game_base import get_save_filename
 
 
 class MainMenuButton(BigButton):
@@ -57,7 +65,7 @@
 
 class MainMenu(Window):
 
-    def __init__(self, screen):
+    def __init__(self, screen, savefile):
         super(MainMenu, self).__init__(screen)
         self.game_window = None
         self.resume = None
@@ -68,14 +76,33 @@
         self.add_child(button1)
         button2 = QuitButton()
         self.add_child(button2)
+        if savefile:
+            self.load_game(savefile)
+        else:
+            # See if we have an autosave file
+            savefile = get_save_filename()
+            if os.path.exists(savefile):
+                self.load_game(savefile)
 
     def start_new_game(self):
-        self.game_window = LabWindow(self.screen)
+        self.game_window = LabWindow(self.screen, None)
+        self.add_resume()
+        AddWindow.post(self.game_window)
+
+    def load_game(self, savefile):
+        if os.access(savefile, os.R_OK):
+            f = open(savefile, 'r')
+            game_data = json.load(f)
+            f.close()
+            self.game_window = LabWindow(self.screen, game_data)
+            self.add_resume()
+        # We stay at the main menu, so the user can can to continue or not
+
+    def add_resume(self):
         if not self.resume:
             # Add the resume button
             self.resume = ResumeGameButton(self)
             self.add_child(self.resume)
-        AddWindow.post(self.game_window)
 
     def resume_game(self):
         AddWindow.post(self.game_window)