#๐Ÿ”’ Saving files

130 messages ยท Page 1 of 1 (latest)

nimble robinBOT
#

@maiden holly

Python help channel opened

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.

maiden holly
#

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

thorn girder
maiden holly
#

oh yeah sure

#

er how do u do that ๐Ÿ˜ญ

thorn girder
#

!paste

nimble robinBOT
#
Pasting large amounts of code

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.

maiden holly
#

like that?

thorn girder
#

yup perfect, just looking at it now

maiden holly
#

alright

thorn girder
#

I'd really consider a different format other than txt file for this

#

json would be perfect

maiden holly
#

unfortunately it has to be txt file

thorn girder
#

you can technically save json to a txt file lemon_wink

maiden holly
#

lecturer said specifically not to import json ๐Ÿ’”

thorn girder
#

ahh alright then, haha

#

so is the issue with saving or loading?

maiden holly
#

loading

thorn girder
#

Does the file look like you expect it to when you save?

#

Can you show what the file looks like?

maiden holly
#

it looks smth like that

thorn girder
#

well this already seems like a problem here

#

I take it you didn't mean to split up your house like this?

maiden holly
#

i didnt mean to but it works when i load the file

#

since its in a grid

thorn girder
#

it wouldn't

#

it's definitely wrong

maiden holly
#

what does it affect? cos it looks fine when i load it

thorn girder
#

but you just said you had issues loading

#

it affects not matching the format of your grid

maiden holly
#

but it appears to be the same?

#

main issue im having rn is loading the contents of the bag

thorn girder
#

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

maiden holly
#

ic, how should i have gone abt fixing it

thorn girder
#

you're mapping each cell to a string, which will unpack your house string

#

!e

text = 'house'

print(list(map(str, text)))
nimble robinBOT
thorn girder
#

don't use map

#

you should be fine just using str(cell)

maiden holly
#

hmm ok gotchu

maiden holly
thorn girder
#

what about it makes you think that it's wrong?

maiden holly
#

because the loading part for the seeds dont work

thorn girder
#

yes but what makes you think that? Is there an error?

#

"Doesn't work" doesn't really tell us much

maiden holly
#

oh, it just prints that you have no seeds rather than actually printing the quantities

#

mb

thorn girder
#

have you tried printing out the state at the end of the loading logic?

maiden holly
#

shouldnt the return state have done that?

thorn girder
#

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

maiden holly
#

ah

#

it returns the bag and seeds as wmpty and 0

thorn girder
#

can you paste your save file to a paste link?

#

where did you put the print btw?

maiden holly
thorn girder
#

it's possible it's triggering the "file not found" and you aren't realizing

maiden holly
thorn girder
#

can you show?

maiden holly
#

where the return was

thorn girder
#

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

maiden holly
thorn girder
#

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

maiden holly
thorn girder
#

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?

maiden holly
#

yeah, it is

#

sorry im tryna process

#

ok i think i get it, but ill need to update the loading portion right?

thorn girder
#

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

maiden holly
#

ok, thanks for the help ๐Ÿ™ i gotta submit this in like 30 mins lol

maiden holly
#

got any more pointers?

thorn girder
#

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

maiden holly
#

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

thorn girder
#

show what the text file looks like

maiden holly
#

ight hold on

#

like that

thorn girder
#

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

maiden holly
#

oh yeah ok

thorn girder
#

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 ]

maiden holly
#

so i just replace the check for [] with :?

thorn girder
#

Yes. Take a moment to think about what you actually want to do

nimble robinBOT
#
Python help channel closed

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.