#๐ Saving files
130 messages ยท Page 1 of 1 (latest)
@maiden holly
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
ive been trying to load items tht ive stored in a text file after i saved them but it doesnt seem to work? need someone to explain why its not working
Initialize game state
def initial_game_state():
return {
'day': 1,
'energy': 10,
'money': 20,
'bag': {},
'seeds': 0,
}
seed_list = ['LET', 'POT', 'CAU']
seeds = {
'LET': {'name': 'Lettuce', 'price': 2, 'growth_time': 2, 'crop_price': 3},
'POT': {'name': 'Potato', 'price': 3, 'growth_time': 3, 'crop_price': 6},
'CAU': {'name': 'Cauliflower', 'price': 5, 'growth_time': 6, 'crop_price': 14},
}
farm = [[None, None, None, None, None],
[None, None, None, None, None],
[None, None, 'House', None, None],
[None, None, None, None, None],
[None, None, None, None, None]]
#save da game
def save_game(game_vars):
with open(SAVE_FILE, 'w') as file:
file.write(f"day:{game_vars['day']}\n")
file.write(f"energy:{game_vars['energy']}\n")
file.write(f"money:{game_vars['money']}\n")
file.write("bag:" + ','.join(f"{code}:{quantity}" for code, quantity in game_vars['bag'].items()) + '\n')
file.write("farm:" + ','.join(
'None' if cell is None else ','.join(map(str, cell)) for row in farm for cell in row) + '\n')
print("Game saved!")
Load the game state from a file
def load_game():
if os.path.exists(SAVE_FILE):
state = initial_game_state() # Start with initial game state
farm = [[None, None, None, None, None],
[None, None, None, None, None],
[None, None, 'House', None, None],
[None, None, None, None, None],
[None, None, None, None, None]]
with open(SAVE_FILE, 'r') as file:
lines = file.readlines()
for line in lines:
if line.startswith('day:'):
state['day'] = int(line.split(':')[1].strip())
elif line.startswith('energy:'):
state['energy'] = int(line.split(':')[1].strip())
elif line.startswith('money:'):
state['money'] = int(line.split(':')[1].strip())
elif line.startswith('bag:'):
bag_items = line.split(':')[1].strip().split(',')
for item in bag_items:
if item: # Check if item is not empty
parts = item.split(':')
if len(parts) == 2:
code, quantity = parts
state['bag'][code] = int(quantity)
elif line.startswith('farm:'):
farm_items = line.split(':')[1].strip().split(',')
index = 0
for r in range(5):
for c in range(5):
value = farm_items[index]
if value == 'None':
farm[r][c] = None
else:
parts = value.split(',')
if len(parts) == 2:
seed_code, growth_time = parts
farm[r][c] = [seed_code, int(growth_time)]
else:
farm[r][c] = None
index += 1
return state
else:
print('No saved game found. Starting a new game.')
return initial_game_state()
this is what i have rn
Can you paste the code using a paste link please?
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
yup perfect, just looking at it now
alright
I'd really consider a different format other than txt file for this
json would be perfect
unfortunately it has to be txt file
you can technically save json to a txt file 
lecturer said specifically not to import json ๐
loading
Does the file look like you expect it to when you save?
Can you show what the file looks like?
it looks smth like that
well this already seems like a problem here
I take it you didn't mean to split up your house like this?
what does it affect? cos it looks fine when i load it
but you just said you had issues loading
it affects not matching the format of your grid
but it appears to be the same?
main issue im having rn is loading the contents of the bag
this is a common "fix a problem that you caused" situation
the way it's saved is definitely not correct, but you've somehow forced a solution when loading it, when really, you should have avoided the saving issue in the first place
ic, how should i have gone abt fixing it
you're mapping each cell to a string, which will unpack your house string
!e
text = 'house'
print(list(map(str, text)))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
['h', 'o', 'u', 's', 'e']
hmm ok gotchu
is there anything else wrong here that makes it so the seeds and their quantities dont load when i load the game?
what about it makes you think that it's wrong?
because the loading part for the seeds dont work
yes but what makes you think that? Is there an error?
"Doesn't work" doesn't really tell us much
oh, it just prints that you have no seeds rather than actually printing the quantities
mb
despite having seeds
have you tried printing out the state at the end of the loading logic?
shouldnt the return state have done that?
return and print are not the same thing
you can use prints to help debug your code
if it's not working as you expect, then print the data to see if it's what you expect it to be
if it isn't, then you can work your way back through the code to see where the logic has an inconsistency
it's possible it's triggering the "file not found" and you aren't realizing
at the end of the loading part
can you show?
ahh
bag_items = line.split(':')[1].strip().split(',')
it's because of this
your line is bag:LET:2
when you do line.split(':')[1], you're only taking LET
if you want everything AFTER the first split, you can do this instead
bag_items = line.split(':', 1)[1].strip().split(',')
you need the extra 1 there to tell it to only split once at the first :
but also notice how there's no farm in your state
{'day': 1, 'energy': 7, 'money': 13, 'bag': {'LET': 2}, 'seeds': 0}
because that also isn't being saved properly
oh nm farm is separate
[[None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]
either way I get this for farm
is that why if i quit the program, the crops dont save either?
I'm not sure how you intended on saving the crops
oh, into the farm grid?
file.write("farm:" + ','.join(
'None' if cell is None else ','.join(map(str, cell)) for row in farm for cell in row) + '\n')
in general, I would avoid these crazy one liners
they're hard to debug
yeah
I would start by creating a separate function for returning a string that represents your farm
farm:None,None,None,None,None,None,None,None,None,None,None,None,H,o,u,s,e,None,None,None,None,POT,3,None,None,None,None,None,None,None
this makes it very difficult to see where each row of the farm starts
perhaps introduce a different character to separate each row
so | could separate the rows, and , could separate the items in the rows
None,None,None,None,None|None,None,None,None,None|None,None,House,None,None|None,None,None,None,None|None,None,None,None,None
def farm_to_string(farm):
data = []
for row in farm:
data.append(','.join(map(str, row)))
return '|'.join(data)
then all you need to do is file.write(farm_to_string(farm))
isn't that much cleaner?
yeah, it is
sorry im tryna process
ok i think i get it, but ill need to update the loading portion right?
give it a try and see yes, you'll need to so you can include the logic of splitting |
print is your absolute best friend to start debugging
print out lines, print out variables
before you print, think about what you expect the result to be
if it doesn't match, work backwards and figure out why
ok, thanks for the help ๐ i gotta submit this in like 30 mins lol
yo sorry i uh couldnt figure out how to do the loading part ๐ญ it still doesnt save the crops when i kill the program and try to load the save
got any more pointers?
start by making sure the save looks correct
don't start on the loading feature until the save text file looks exactly how it should
the save correctly splits it up, but since there are [] for the crops, i put an if statement to get what was inside them
the map prints properly still but the crops just dont appear
show what the text file looks like
you'll need to come up with a better way to store things that are lists
so perhaps if it's a list, you could store it as POT:3 instead of ['POT', 3]
you're also missing the : after your farm
it says farmNone right now
oh yeah ok
https://paste.pythondiscord.com/77OQ
this is what ive been trying to use for the load now
ok so now you can check if the cell has : in it
and if it does, you know it will need to be split up
you no longer will need to check for [ or ]
so i just replace the check for [] with :?
Yes. Take a moment to think about what you actually want to do
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.