473,811 Members | 2,963 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating a save function

7 New Member
Expand|Select|Wrap|Line Numbers
  1. def save():
  2.     try:
  3.         saves.append(str(level))
  4.         saves.append(str(stre))
  5.         saves.append(str(spd))
  6.         saves.append(str(hp))
  7.         saves.append(str(maxhp))
  8.         saves.append(str(exp))
  9.         saves.append(str(maxexp))
  10.         saves.append(str(gp))
  11.         saves.append(str(sword))
  12.         save = open('gamesave.txt', 'r+')
  13.         for s in saves:
  14.             save.write(s)
  15.             save.write('\n')
  16.             saves.remove(s)
  17.             print s
  18.         print "Save successful."
  19.         save.close()
  20.     except ValueError: print "Save unsuccessful."
  21.  
This should append all of those values, all of which are numbers, into the saves list. Then it should open gamesave.txt, and write them into it, and remove them from the list one by one. As it goes through, only a few are actually sent through, and the last 4 are left.

The attachment shows this. The top line is the saves list. The numbers below it are the ones that are written to the text file.

Anyone know why it won't get all the way through the list?

[link removed]
Jul 12 '07 #1
5 2220
bvdet
2,851 Recognized Expert Moderator Specialist
Expand|Select|Wrap|Line Numbers
  1. def save():
  2.     try:
  3.         saves.append(str(level))
  4.         saves.append(str(stre))
  5.         saves.append(str(spd))
  6.         saves.append(str(hp))
  7.         saves.append(str(maxhp))
  8.         saves.append(str(exp))
  9.         saves.append(str(maxexp))
  10.         saves.append(str(gp))
  11.         saves.append(str(sword))
  12.         save = open('gamesave.txt', 'r+')
  13.         for s in saves:
  14.             save.write(s)
  15.             save.write('\n')
  16.             saves.remove(s)
  17.             print s
  18.         print "Save successful."
  19.         save.close()
  20.     except ValueError: print "Save unsuccessful."
  21.  
This should append all of those values, all of which are numbers, into the saves list. Then it should open gamesave.txt, and write them into it, and remove them from the list one by one. As it goes through, only a few are actually sent through, and the last 4 are left.

The attachment shows this. The top line is the saves list. The numbers below it are the ones that are written to the text file.

Anyone know why it won't get all the way through the list?
During the iteration, items are being removed from the list. Do something like this instead:
Expand|Select|Wrap|Line Numbers
  1. >>> myList = [1,2,3,4,5,6,7,8,9,0]
  2. >>> for item in myList:
  3. ...     print item
  4. ...     myList.remove(item)
  5. ...     
  6. 1
  7. 3
  8. 5
  9. 7
  10. 9
  11. >>> myList
  12. [2, 4, 6, 8, 0]
  13. >>> 
  14. >>> myList = [1,2,3,4,5,6,7,8,9,0]
  15. >>> for item in myList[:]:
  16. ...     print item
  17. ...     myList.remove(item)
  18. ...     
  19. 1
  20. 2
  21. 3
  22. 4
  23. 5
  24. 6
  25. 7
  26. 8
  27. 9
  28.  
  29. >>> myList
  30. []
Jul 12 '07 #2
xZaft
7 New Member
During the iteration, items are being removed from the list. Do something like this instead:
Expand|Select|Wrap|Line Numbers
  1. >>> myList = [1,2,3,4,5,6,7,8,9,0]
  2. >>> for item in myList:
  3. ...     print item
  4. ...     myList.remove(item)
  5. ...     
  6. 1
  7. 3
  8. 5
  9. 7
  10. 9
  11. >>> myList
  12. [2, 4, 6, 8, 0]
  13. >>> 
  14. >>> myList = [1,2,3,4,5,6,7,8,9,0]
  15. >>> for item in myList[:]:
  16. ...     print item
  17. ...     myList.remove(item)
  18. ...     
  19. 1
  20. 2
  21. 3
  22. 4
  23. 5
  24. 6
  25. 7
  26. 8
  27. 9
  28.  
  29. >>> myList
  30. []
Thanks that worked very well =]

I have another concern though. I have the game set up in functions so that the switch is easier to read.

Expand|Select|Wrap|Line Numbers
  1. while c != 'q':
  2.     main()
  3.     c = raw_input("[A]ttack [S]tore S[t]ats [L]oad Sa[v]e [Q]uit ").lower()
  4.     clear()
  5.     if c == 'a':
  6.         attack()
  7.     elif c == 's':
  8.         store()
  9.     elif c == 't':
  10.         stats()
  11.     elif c == 'l':
  12.         load()
  13.     elif c == 'v':
  14.         save()
  15.     else:
  16.         if c == 'q':
  17.             gb = raw_input("Goodbye! Press [Enter]")
  18.         else:
  19.             print "Invalid Choice."
  20.  
main has all of the basic variables already defined for later use. When going to attack I get the error:
Expand|Select|Wrap|Line Numbers
  1. Traceback (most recent call last):
  2.   File "C:\Python25\Tools\custom\game.py", line 210, in <module>
  3.     attack()
  4.   File "C:\Python25\Tools\custom\game.py", line 52, in attack
  5.     if hp > 0:
  6. UnboundLocalError: local variable 'hp' referenced before assignment
  7.  
but all the code up to that point in attack was already defined:

Expand|Select|Wrap|Line Numbers
  1. def attack():
  2.     monName = _choice(monsterName)
  3.     print "You are attacking a %s" % monName
  4.     monIndex = monsterName.index(monName)
  5.     monHP = monsterHP[monIndex]
  6.     monExp = monsterExp[monIndex]
  7.     monStr = monsterStr[monIndex]
  8.     monSpd = monsterSpd[monIndex]
  9.     monMin = monsterMin[monIndex]
  10.     monMax = monsterMax[monIndex]
  11.  
  12.     if sword == 1:
  13.         stre += 4
  14.         spd += 3
  15.     if hp > 0:
  16.  
Why does that error come up?
Jul 12 '07 #3
elbin
27 New Member
main has all of the basic variables already defined for later use. When going to attack I get the error:
Expand|Select|Wrap|Line Numbers
  1. Traceback (most recent call last):
  2.   File "C:\Python25\Tools\custom\game.py", line 210, in <module>
  3.     attack()
  4.   File "C:\Python25\Tools\custom\game.py", line 52, in attack
  5.     if hp > 0:
  6. UnboundLocalError: local variable 'hp' referenced before assignment
  7.  
but all the code up to that point in attack was already defined:

Expand|Select|Wrap|Line Numbers
  1. def attack():
  2.     monName = _choice(monsterName)
  3.     print "You are attacking a %s" % monName
  4.     monIndex = monsterName.index(monName)
  5.     monHP = monsterHP[monIndex]
  6.     monExp = monsterExp[monIndex]
  7.     monStr = monsterStr[monIndex]
  8.     monSpd = monsterSpd[monIndex]
  9.     monMin = monsterMin[monIndex]
  10.     monMax = monsterMax[monIndex]
  11.  
  12.     if sword == 1:
  13.         stre += 4
  14.         spd += 3
  15.     if hp > 0:
  16.  
Why does that error come up?
Hp is NOT defined for your attack function, that is, it is not defined in it OR as a global variable in the file/module. So you get an error. If it IS defined globally, try:

Expand|Select|Wrap|Line Numbers
  1. if global hp > 0:
  2.  
Jul 12 '07 #4
xZaft
7 New Member
Expand|Select|Wrap|Line Numbers
  1. if global hp > 0:
  2.  
When I try and run that, it says it is invalid syntax.
Jul 12 '07 #5
bartonc
6,596 Recognized Expert Expert
Expand|Select|Wrap|Line Numbers
  1. if global hp > 0:
  2.  
When I try and run that, it says it is invalid syntax.
You'll need to post more of your program in order to get the scope of your variables worked out. Please start a new thread regarding "creating an RPG" or something like that.

Thanks.
Jul 12 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2486
by: Oci-One Kanubi | last post by:
Everything works fine in Access, but when I double-click on the resultant Excel files the first one opens correctly, but subsequent ones, and any other Excel files I try to open, fail to display at all; I get the Excel window frame with corrupted contents. The only way I can get decent functionality from Excel is to open Excel from the Start menu, open each of these new files from the Excel File menu, and save each one. Thereafter Excel...
0
1653
by: James Fortune | last post by:
Here is an example of Access creating a single page PDF file. The text in the textbox is scaled to fit horizontally into a grey box 100 pixels wide that is fontsize pixels high. Clicking the command button creates the pdf file. Be sure to close Acrobat Reader before creating another file with the same name. Form code is followed by module code. No stream compression or pdf linearization is used in this example. Note that the special...
0
500
by: musicloverlch | last post by:
I used to be able to create PDFs, automatically save them to a file, and mail them out to people. This was on Access 97 with Windows NT. We've changed to Windows XP and Access 2003. Doesn't work anymore. Part of the problem is that the users have no access to the registry and can only save files on the C:\ drive to their My Documents folder. I found this code on the web, but it doesn't work either. The files continue to print out of my...
9
3099
by: Patrick.O.Ige | last post by:
I have a code below and its a PIE & BAR CHART. The values now are all static but I want to be able to pull the values from a database. Can you guys give me some ideas to do this? Thanks Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Declare your object variables
2
1929
by: asad | last post by:
Hello friends, how ru all, i have some problem about saving created thumbnail, following is the code i use for creating thumbnail but thumbnail was not saved it is on memory which method is used to store created thumbnail in to hard disk <%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" %> <%@ Import Namespace="System.Drawing.Imaging"%>
7
2322
by: Nathan Sokalski | last post by:
I am having a problem saving an image with the same name it originally had. I have two similar versions of my code, one in which I close the FileStream used to open the original image before saving, the other in which I close the FileStream afterwards, although both return the same error. Here are the two versions of the code and the errors they each return (NOTE: I rebooted immediately before running each of these versions so that I knew they...
3
6107
by: Kim | last post by:
Im making a config file to a C# program in XML. I have save and load functions, but these require a base XML file with its structure to exsist (Im new to XML, so this was the way I it to work). Now I want to extend that, so if the base XML file doesnt exsist a function will make the structure. However this way seem somewhat troublesome to do it, but it works. Is there an easier way? Also is it allowed to use space in the element name ?
4
5149
by: grant | last post by:
Well, I just downloaded SQL 2005 Express to have a play. Good old Bill says "up and running in 20 minutes" Well 5 hrs, 5 reboots and 4 full un-install and re-install later I have finally got it working. About what I expected really. Anyway, my question relates to creating user defined functions. I've 10 yrs exp in MS Access and VB, and user ent Manager to create views on the work server, but havnt done much with functions.
3
2101
by: xZaft | last post by:
#Game by Todd Lunter from random import choice as _choice import random as r c = 'a' level = 1 stre = 2 spd = 2 exp = 0
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10644
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10124
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4334
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.