Save/Load Script

I wrote these scripts to save and load my game. I was wondering mainly if this is the correct usage of readlines(). Is this right, or is the usage different, and if so, how would I get it to work?


#Save Script

import Gamelogic

cont = GameLogic.getCurrentController()
obj = cont.getOwner()

position = obj.getPosition
score = obj.Score
health = obj.Health

toWrite = """%d
%d
%d
%d
%d""" % (position[0],position[1],position[2],score,health)


f = file('save.txt', 'w')
f.write(toWrite)
f.close()

and


#Load Script

import Gamelogic

cont = GameLogic.getCurrentController()
obj = cont.getOwner()

f = file('save.txt', 'r') # Open for loading
f.readline() = posX
f.readline() = posY
f.readline() = posZ
f.readline() = Score
f.readline() = Health
f.close() # close the file

obj.Score = Score
obj.Health = Health
obj.setPosition([posX,posY,posZ])

The files are stored as strings so you’ll need to type cast the input. Also, try truncating the file before writing to it, that removes any chance of ‘old data’ from cluttering up your file. Not sure if thats the right way to use readlines, I just use one line with a dictionary on it to store multiple values then eval the input.

I was looking through the Internet, and found a module called cPickle. Supposedly it lets you save variables, lists, strings, etc. and recall them. I tried using it as a replacement for the above scripts. Does anyone know why this would not work? If not, is there a different way to accomplish this? And how exactly does the save global.dict work? Is it a better way?


import Gamelogic 
import cPickle as p 
 
cont = GameLogic.getCurrentController() 
obj = cont.getOwner() 
 
 
f = file('save.data') 
toLoad = p.load(f) 
toLoad[0] = posX 
toLoad[1] = posY 
toLoad[2] = posZ 
toLoad[3] = Score 
f.close()
 
obj.Score = Score 
obj.setPosition([posX,posY,posZ])


import Gamelogic 
import cPickle as p 
 
cont = GameLogic.getCurrentController() 
obj = cont.getOwner() 
 
 
f = file('save.data') 
toLoad = p.load(f) 
toLoad[0] = posX 
toLoad[1] = posY 
toLoad[2] = posZ 
toLoad[3] = Score 
f.close() # close the file 
 
obj.Score = Score 
obj.setPosition([posX,posY,posZ])

Hi,
There’s some good info on using globalDict here
http://www.tutorialsforblender3d.com/GameModule/GameLogicModule_20.html
Once you have stuff in the globalDict you can load and save it to a file using the game actuator. http://www.tutorialsforblender3d.com/GameDoc/LogicBricks/Actuator_12D.html

I made some examples here: Save/Load the Properties of Objects
Here’s an examble using cPickle
Save


#-----[ Save ]--------------------------------------------------------------
# saveLoad.dat <-- GameLogic.globalDict <-- Object.name <-- Object's stuff

import cPickle, shelve
import GameLogic

obj = GameLogic.getCurrentController().owner

# Get a list of the object's properties    
# e.g. health, ammo.
propNames = obj.getPropertyNames()
propList = []
for p in propNames:
    val = obj[p]
    propList.append(val)                

                    
stuff = {     "propList" : propList,
            "position" : obj.localPosition,
            "orientation" : obj.localOrientation    }
                
GameLogic.globalDict[obj.name] = stuff
    
                        
pickle_file = open("saveLoad.dat", "w")    
cPickle.dump(GameLogic.globalDict, pickle_file)    
pickle_file.close()
    

Load


#-----[ Load ]----------------------------------------------
import cPickle, shelve
import GameLogic

obj = GameLogic.getCurrentController().owner

    
try:
    pickle_file = open("saveLoad.dat", "r")
    GameLogic.globalDict = cPickle.load(pickle_file)
    pickle_file.close()


# If the file does not exist:    
except(IOError), e:    
    print """
ERROR: You've got to save the bloody file first before 
you can load it! or as python would say:

""", e

    
# If the file does exist:    
else:
    theStuff = GameLogic.globalDict.get(obj.name)
            
    # Replace the object's properties with the saved ones.
    savedProps = theStuff["propList"]    
    objProps = obj.getPropertyNames()        
    for x in range(0,len(savedProps)):
         obj[objProps[x]] = savedProps[x]
                
    # Load the position and orientation
    obj.position = theStuff["position"]    
    obj.localOrientation = theStuff["orientation"]    
        

It might be pointless to use globalDict in the above examples, a regular
dictionary would probably work fine because your just saving it to a file.

I really recommend this book if you want to learn python.

Thank you for the information.
Although it may seem like it, I’m not an absolute noob. I have created several basic programs. However, my weak points has always been file manipulation. Unfortunately, that’s just what my game required. Sorry if I sound indignant. Thanks again for your time.

I’m sorry, I didn’t mean mean to imply that your a noob by pointing to a beginner book,:no: or by giving allot of info.
Its just that I own the book and it was written by a game developer, I found it to have invaluable reference that applies directly to games that I cant find on the web (a whole chapter on file manipulation.)

anyway, I didn’t know how much you know, so I just gave as much info as I could (I’m still learning.)

Linxgl also made some save/load scripts if you want to see how he saved the file.

Good Luck:)
Phil