| | |
Passing varyables through a text file
![]() |
I'm making a text game and im making a save() and load() function i'v got the save function to work but i dont know how to change varyables in the program depending on the varyables in the text files.
heres the code for the functions:
any help would be apreciated
heres the code for the functions:
python Syntax (Toggle Plain Text)
def save(): openfile = open('save_file', 'r+') openfile.seek(0, 0) openfile.write(player.exp, '/n', player.level, '/n', player.health, '/n', new_monster.health, '/n', new_monster, '/n', new_monster.name, ) def load(): openfile = open('save_file', 'r') openfile.read << this is where im stuck
any help would be apreciated
...
•
•
Join Date: Mar 2007
Posts: 110
Reputation:
Solved Threads: 31
To load the values, you could do something like this:
Example config file:
Tom
10
9.7
[1,2,3]
To write the variables to disk, you must pass a string argument to the file write() method.
Example config file:
Tom
10
9.7
[1,2,3]
Python Syntax (Toggle Plain Text)
fn = 'config.txt' f = open(fn) vartypes = [str,int,float,eval] varnames = ['name','exp','score','other'] dd = {} for i,line in enumerate(f): dd[varnames[i]] = vartypes[i](line.strip()) globals().update(dd) f.close()
Python Syntax (Toggle Plain Text)
>>> name 'Tom' >>> other [1, 2, 3] >>>
Python Syntax (Toggle Plain Text)
f = open('config1.txt', 'w') f.write('\n'.join([str(item) for item in [name,exp,score,other]])) f.close()
you can also use eval or exec on the text file if it was like this:
if you had this in your program
That will then set up all of your variables.
Hope that helps
•
•
•
•
t = 1
variable2 = 10
string = 'hello'
python Syntax (Toggle Plain Text)
f = open('variables.txt') for line in f: eval(line) #or exec(line)
Hope that helps
Make it idiot proof and someone will make a better idiot.
Check out my Site | and join us on IRC | Python Specific IRC
Check out my Site | and join us on IRC | Python Specific IRC
Nah that doesnt work, heres the code as it is now:
python Syntax (Toggle Plain Text)
#the save function def save(): save_varyables = [player.level, player.health, new_monster.health, new_monster, new_monster.name] file = open('save_varyables') pickle.dump(save_varyables, file) file.close() #the load function def load(): f = open('save_file') for line in f: eval(line)
...
•
•
Join Date: Mar 2007
Posts: 110
Reputation:
Solved Threads: 31
Well, of course it won't work. If you pickle.dump() some data to disk, you need to pickle.load() to get the data from disk. Example:
Python Syntax (Toggle Plain Text)
>>> dd = {'s3': 'This is a string', 'r3': 1.5, 'i3': 1} >>> f = open('test.txt', 'w') >>> import pickle >>> pickle.dump(dd, f) >>> f.close() >>> f = open('test.txt') >>> dd1 = pickle.load(f) >>> dd1 {'s3': 'This is a string', 'i3': 1, 'r3': 1.5} >>>
I think that will work but i cant tell unless the save function works, i dont know why it works, i tell it to ask the user if he\she wants to save and when they type yes, it dosnt work because when it saves it is supposed to quit and i went and chacked the text file that it is supposed to save in and it hasnt dumped anything there, any ideas?
here is the code yet again:
here is the code yet again:
python Syntax (Toggle Plain Text)
#the save function def save(): save_game_varyables = [new_monster.attack, new_monster.health, new_monster.defense, new_monster,name] file = open('save_file') pickle.dump(save_game_varyables, file) file.close() loop = 0 #the load function def load(): f = open('save_file') pickle.load(f) for line in f: eval(line)
...
For starters you shouldnt use the word "file" as a variable. That is a keyword in python.
Make it idiot proof and someone will make a better idiot.
Check out my Site | and join us on IRC | Python Specific IRC
Check out my Site | and join us on IRC | Python Specific IRC
I think the error is how call the class in the main() function can anyone help?
heres the code:
heres the code:
python Syntax (Toggle Plain Text)
#!/usr/bin/env python #The main file with all the game logic and the player class #import the necessary files import random import pickle from monsters import * from weapons import * try: import cPickle as pickle except: import pickle as pickle class Packet: def __init__(self, data): self.data = data def save(self): #save data = pickle.dumps(Packet(data)) savefile = open('save_file','w') savefile.write(data) savefile.close() def load(self): #load data = pickle.loads(buf).data openfile = open('save_file','r') data = openfile.read() if IOError: print 'No save file to load!' loop = 0 #Player class class player(): def __init__(self): self.health = 30 self.damage = 5 weapon = random.randrange(1,3) if weapon == 1: self.weapon = sword() print 'The weapon that you are using\'s attributes are:' print self.weapon.GetAttributesInfo() elif weapon == 2: self.weapon = axe() print 'The weapon that you are using\'s attributes are:' print self.weapon.GetAttributesInfo() elif weapon == 3: self.weapon = spear() print 'The weapon that you are using\'s attributes are:' print self.weapon.GetAttributesInfo def attack(self, monster): dam = self.weapon.GetDamage() if dam > monster.defense: monster.health = monster.health - dam print 'You hit him for %d damage!' %dam else: print 'You did\'nt do any damage...' #The main() function, for executing the actuall game def main(): loop = 1 new_monster = random.randrange(1, 5) if new_monster == 1: new_monster = orc() elif new_monster == 2: new_monster = troll() elif new_monster == 3: new_monster = dragon() elif new_monster == 4: new_monster = goblin() elif new_monster == 5: new_monster = spider() saving_and_loading = Packet('save_file') P = player() start = 1 while start == 1: print 'Your options are:' print '1)New game' print '2)Load' print '3)Quit' print 'You can type \'save\' at any time during the game to save your game(saving quits)' choice = input('What do you want to do:') if choice == 1: print 'The attacking monster\'s attributes are:' print new_monster.GetAttributesInfo() P.attack(new_monster) elif choice == 2: Packet.load() print 'The attacking monster\'s attributes are:' print new_monster.GetAttributesInfo() P.attack(new_monster) elif choice == 3: loop = 0 start = 0 loop = 1 while loop == 1: #The game logic connected to all the varyables if new_monster.health <= 0: print 'You killed the ', new_monster.name, '!' loop = 0 elif new_monster.health > 0: choice = raw_input('Do you want to attack again:') if choice == 'yes' or 'y': print 'The monster\'s health is now:', new_monster.health P.attack(new_monster) elif choice == 'no': loop = 0 elif choice == 'save': Packet.save() else: print 'You\'re just talking jiberish now' #Initalize the main function, since __name__ is always == '__main__' if __name__ == '__main__': main()
...
![]() |
Other Threads in the Python Forum
- Previous Thread: executing scripts via command line
- Next Thread: Classes vs Functions
| Thread Tools | Search this Thread |
accessdenied advanced apache application argv array beginner book change command converter countpasswordentry csv curved dan08 def dictionary dynamic edit enter event examples file float format function google gui homework import inches input jaunty java keyboard lapse library line lines linux list lists loop microphone mouse movingimageswithpygame mysqlquery newb number numbers numeric obexftp output parameters parsing path phonebook plugin port prime programming projects py2exe pygame pygtk pyopengl python random recursion redirect remote return reverse scrolledtext session simple skinning software sprite statictext string strings syntax terminal text threading time tlapse trick tuple tutorial ubuntu unicode unit urllib urllib2 variable voip wordgame wxpython





