#๐Ÿ”’ How do i add save/load to my game?

455 messages ยท Page 1 of 1 (latest)

static sedge
#

im makeing a game in python and i need to save all the vars to a txt file then load them back.
im not sure on how to do this.

elfin hillBOT
#

@static sedge

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.

stone raft
#

!pastebin

elfin hillBOT
#
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.

storm ether
#

u can do a json or less safe but simpler is pickle

stone raft
#

i find json to be best and simplest

#

given json exists

storm ether
#

!d json.load

elfin hillBOT
#

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* to a Python object using the [JSON-to-Python conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).
storm ether
#

!d json.dump

elfin hillBOT
#

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [Python-to-JSON conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).

Note

Unlike [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) and [`marshal`](https://docs.python.org/3/library/marshal.html#module-marshal), JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to [`dump()`](https://docs.python.org/3/library/json.html#json.dump) using the same *fp* will result in an invalid JSON file.
stone raft
#

lets not get ahead of ourselves, we havent seen their code, they might be a beginner who hasnt learned import yet

static sedge
storm ether
#

!paste

elfin hillBOT
#
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.

static sedge
storm ether
#

also if you can save it all to a dict and load it from that dict adding the json save to file is easy

static sedge
#

dict?

storm ether
#

but json can only store list, dict, tuple, str, int... the basic types

storm ether
stone raft
stone raft
#

its not a bad thing

#

but ye they starting out pithink

#

@static sedge so to do file work with python, u must first open a file then close it, althought we can do it manually with open() and .close() there is a better solution called with

#

!e

with open('somefile.txt', 'w') as file:
    file.write('some text')
elfin hillBOT
still remnant
# stone raft its not a bad thing

I'm not saying it's bad I'm just saying that, I'm not a person who'll write so much stuff , unless I'm actually intermediate, I would rather do loads of exercises as a beginner.

stone raft
#

as u can see this creates a file, opens it, writes some text to it then closes file automatically for us

#

thats why with is nice pithink

static sedge
stone raft
#

it shows created files in output

storm ether
stone raft
#

very cool feature pithink

stone raft
#

can u guess what 1st one means ? pithink

still remnant
static sedge
#

It's really useful for when you're trying to test something but this other thing isn't finished

still remnant
elfin hillBOT
stone raft
#

as u can see this just works

static sedge
#

yeah

stone raft
#

anyways that aside

static sedge
#

can you remind me, the first one of what?

stone raft
#

!e

with open('somefile.txt', 'w') as file:
    file.write('some text')
elfin hillBOT
stone raft
#

in this code we passing 2 arguments to open

#

can u guess what 1st one means

static sedge
#

well i think its telling python to make the file

#

the second is filling the file?

storm ether
stone raft
#

the w doing that part

#

w telling python to make the file if it doesnt already exist and open is handling actual creation

#

bit of a difference there pithink

storm ether
# stone raft eh also wrong

the args describe how to do it. no?
open tells to make (if needed) the file the args describe what file and for what reason

static sedge
#

would i do this?
file.write("id put my vars here")

stone raft
#

inside there

stone raft
#

that simple

still remnant
#

Instead of Bad clear and 100 blank lines you should use sys(clr) ๐Ÿฅฒ

stone raft
#

if u do r it doesnt create file for example

#

and if u do x it creates file but freaks out if file already exists

static sedge
storm ether
storm ether
stone raft
#

i recommend thonny for beginners but vsc is the most popular choice

static sedge
still remnant
stone raft
#

its a good ide for production/experienced folks

#

but it just hides way too much shit from beginner who should be learning the shit it hid

static sedge
#

back on topic how do i load the data with this file?

storm ether
stone raft
#

!d open

elfin hillBOT
#

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
Open *file* and return a corresponding [file object](https://docs.python.org/3/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) is raised. See [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.

*file* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)
static sedge
#

?

stone raft
#

as u can see the 2nd argument is called mode

#

thats how we tell it to open it to read or write

#

r for read, w for write

static sedge
#

ohhhhhhh

stone raft
#

u dont need to worry about the other modes

storm ether
#

r+ to do woth

static sedge
storm ether
stone raft
#

there is prob more i just dont know it all cause it just does so much fucking shit behind scenes

static sedge
stone raft
#

ยฏ_(ใƒ„)_/ยฏ

stone raft
static sedge
#

ok brb

stone raft
#

dont worry about variables just simple save to file and read from

#

if u can do that then its just 1 step away from what u need

still remnant
stone raft
still remnant
static sedge
#

its
with open('somefile.txt', 'w') as file:
file.write('some text')
to write
but how does it change to read?

still remnant
stone raft
stone raft
#

vsc is popular choice but thonny is prob best for beginners

#

and def stay away from ai tools

static sedge
#

https://www.onlineide.pro/
ive been useing it and i think its good
just def dont use replit

Online IDE Pro is a powerful online IDE that allows you to code, compile, and share your code instantly.

still remnant
still remnant
stone raft
#

last time i used replit i didnt spend a cent

static sedge
#

my freind was useing it and he told me to NEVER use it

#

idk

stone raft
#

u should NEVER use online ide period

still remnant
stone raft
static sedge
stone raft
still remnant
static sedge
#

my only complaynt is that it times you out in like 30 secs

stone raft
#

brother if u run code locally u dont even wait 0.1s for it to run

static sedge
stone raft
#

also not a thing locally

static sedge
#

ยฏ_(ใƒ„)_/ยฏ

#

so i did
elif act == "file":
with open('somefile.txt', 'w') as file:
file.write('some text')
and nothing happend

stone raft
#

that shitty website u running wont allow files created by code to be viewed

static sedge
#

what do you want me to use then?

still remnant
stone raft
static sedge
#

i got a crome book

#

๐Ÿ’€

stone raft
stone raft
static sedge
#

(โ•ฏยฐโ–กยฐ)โ•ฏ๏ธต โ”ปโ”โ”ป

stone raft
stone raft
static sedge
stone raft
#

u need to enable linux on it

#

watever the fuck thats supposed to mean

#

chromebooks weird me out

static sedge
#

i have to use an online ide

#

):

stone raft
static sedge
#

we can make a work around im sure

stone raft
#

why did u willingly buy a chromebook

static sedge
#

i was wrong

stone raft
#

the only thing it can do well is mircosoft word and web browsing

#

and even then idfk

still remnant
static sedge
#

*crome broseing

#

games are fun online

#

and discord

#

and youtube

#

its not that limiting

stone raft
static sedge
#

we shold make a workaround for the file thing

stone raft
#

ctrl alt T

#

shell

#

does that work

static sedge
#

NO THATS CROSH

stone raft
static sedge
#

crosh can die alone in a hole with 36 worms and 17 spiders

stone raft
#

what the fuck is crosh

#

i just want to know if shell works

#

issue is the wood_save part

static sedge
#

bruh

still remnant
#

I keep writing dumb stuff

static sedge
stone raft
#

its not dumb u just missed 1 detail

still remnant
#

Obviously it won't be saved when I closed the program

stone raft
#

the logic is flawless

#

well ig was

stone raft
#

just to buy a freaking rpi

static sedge
#

okay what if it just exported numbers and the user just needs to save that somewhare (its thair job now)

#

the only hard part would be reading it to put the vars back

#

and that cant be too hard

stone raft
#

eh pithink

#

u understimating that approach

#

but go ahead

stone raft
#

lets understand tf that approach is

#

save all data into a huge string -> encode it somehow -> give it to user to copy

#

thats saving

#

loading would be

#

user gives huge string -> we decode it -> programn continues to run

static sedge
#

well we dont need it to be big

stone raft
#

we can simplify this approach and get rid of encode/decode part

#

but then what is accepted will be a lot more specific

static sedge
#

thats for export

stone raft
static sedge
#

uhhhhhhh

#

gimme a sec

#

elif act == "load":
print("input your data")
input()
next we brake it appart char by char
i dont know how to do that

stone raft
static sedge
#

):

stone raft
#

they dont make it big to make it big

static sedge
#

i know what is does

stone raft
stone raft
static sedge
#

yeah

stone raft
#

for is another loop just like it

static sedge
#

ik

stone raft
#

except this one we dont itearte given a condition

#

we iterate over a iterable

#

!e

for i in range(10):
    print(i)
elfin hillBOT
stone raft
#

the most basic example

static sedge
stone raft
#

there is times u still need while

#

so pithink

static sedge
#

not right now

stone raft
#

and every iteration one of those numbers is assigned to i one by one

#

makes sense ?

static sedge
#

okay we can do
for i in range(5):

#

but how do you read itt?

stone raft
#

read what

#

the input ?

static sedge
#

yeah

stone raft
#

well first we need to assign it to a variable

static sedge
#

str or int

stone raft
stone raft
static sedge
#

str?

stone raft
#

why not int

static sedge
#

well i guess you could use both

#

first int to make sure its number (use try) then str to read

#

elif act == "load":
print("input your data")
load = input()
print(load)

#

the print part is for testing

tall blade
#

What are you currently stuck on?

stone raft
#

their current idea is to literally just print a string and have user copy it to save it, then paste it to load it (using input and they stuck on this part)

#

this latest code they shared

tall blade
#

it could be something very simple like each of the values with a delimiter

#

maybe with ;?

#

100;12;8;1;0

#

that represents cash, wood, stone, axe, pickaxe

#

it's not very secure and would be really easy to cheat by changing the values

stone raft
tall blade
#

but for a local game, that's fine

#

json isn't really that much more secure against cheating

static sedge
tall blade
static sedge
#

ok

tall blade
#

!e

load_string = '100;12;8;1;0'

values = load_string.split(';')
print(values)
elfin hillBOT
static sedge
#

it doesnt realy matter anyways

tall blade
#

well there's your answer then

#

have the user paste in a "save string" like this as an example

#

then split the data and assign

static sedge
#

?

static sedge
#

i dont know how

tall blade
#

Which part are you unsure of?

static sedge
#

split the data

tall blade
static sedge
#

is load_string a var?

tall blade
#

the name isn't important

#

the .split(':') is the important bit

#

it doesn't matter where the string comes from

#

from input, from a file, from random data, etc

#

a string is a string

stone raft
static sedge
#

not rlly

#

ive only ever done things with one var at a time

dull pivot
#

a list is a type of variable

#

do you know what types are?

static sedge
#

yeah

tall blade
static sedge
tall blade
#

A list is a type of data that contains other data inside it

static sedge
#

so like a var if it held other vars inside?

tall blade
#

It doesn't hold vars. It holds data

#

Variables are simply names that we assign to data so we can refer back to it later

dull pivot
#

a var holds a value, a list holds many values is how i think about it

stone raft
#
some_list = [1,2,3,4]
# some_list a variable
# 1,2,3,4 are the 4 values inside the list assigned to some_list, in this case they are all of data type int
stone raft
#

, is how u separate entries in a list

#

if that wasnt clear

static sedge
#

so then what were the ; about then?

dull pivot
#

it's to encode the list into a string that you can copy and paste

tall blade
#

That provided an easy way for us to convert a string into a list

#

Splitting a string always results in a list

dull pivot
#

and joining a list always results in a string

static sedge
#

so from 1;3;4;6;9 to a list containing 1,3,4,6,9?

dull pivot
#

yes

static sedge
#

okay

tall blade
#

we could have used any symbol really. ; is just a nice obvious separator

static sedge
#

i understand now

tall blade
#
shopping_list = ['apples', 'eggs', 'milk']
#

have a look at this simple list

static sedge
#

okay

tall blade
#

if we want to specify a specific item within the list, we use "indexing"

static sedge
#

continue?

tall blade
#

basically, python assigns a number to every item inside the list, and we can use that number to lookup what's in that position

#

indexing starts from 0, so if we ask the list to display the item at index 0, it would be "apples"

#

index 1 is eggs

#

index 2 is milk

static sedge
#

so if i have
inport_list = [4, 7, 92, 4]
2 is 92?

tall blade
#

yes exactly ๐Ÿ™‚

stone raft
#

import_list[2] is 92 to be more exact

tall blade
#

to access it, we use [] around the index number

stone raft
#

this is the indexing syntax

tall blade
#

!e

shopping_list = ['apples', 'eggs', 'milk']
print(shopping_list[0])
elfin hillBOT
static sedge
#

how are you doing the !e?

stone raft
#

!code

elfin hillBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

stone raft
#

make a code block and preappend it with !e

#

bot will run it

static sedge
#

!code
print("eheheh")

tall blade
#

so if we're smart about this, we can keep a list and make sure the order matches the items in the game

#

it's !e that makes it evaluate

tall blade
#
#cash
#wood
#stone
#axe
#pickaxe

inventory = [23, 12, 5, 1, 0]
tall blade
#

have a look at this list

static sedge
#

okay so for exporting just print the list?

tall blade
#

this says we have 23 cash, 12 wood, 5 stone, 1 axe, 0 pickaxe

static sedge
tall blade
#

to save it, we want a nice string the user can copy like this

#

23;12;5;1;0

static sedge
#

so how would we print it?

tall blade
#

we can use a really nice trick to do this easily

#

!e

#cash
#wood
#stone
#axe
#pickaxe

inventory = [23, 12, 5, 1, 0]
print(*inventory, sep=';')
elfin hillBOT
static sedge
#

?

#

whats with the * and sep

tall blade
#

but, you don't have a list

#

!e

cash = 23
wood = 12
stone = 5
axe = 1
pickaxe = 0

print(cash, wood, stone, axe, pickaxe, sep=';')
elfin hillBOT
tall blade
#

so you can just print the variables you want to save

#

when you print multiple things at once like this, python usually uses a space between each thing

#

!e

cash = 23
wood = 12
stone = 5
axe = 1
pickaxe = 0

print(cash, wood, stone, axe, pickaxe)
elfin hillBOT
tall blade
#

sep lets us change how print works to override what character gets printed between each value

stone raft
#

separator

tall blade
#

!e

cash = 23
wood = 12
stone = 5
axe = 1
pickaxe = 0

print(cash, wood, stone, axe, pickaxe, sep='...')
print(cash, wood, stone, axe, pickaxe, sep=' and ')
elfin hillBOT
tall blade
#

we can use any string we want for some fun results

#

so saving is quite easy. We just display the string we want the user to copy

static sedge
#

elif act == "save":
print(cash, wood, stone, axe, pickaxe, sep=;)

tall blade
#

but for loading, we need to read a similar string, and chop it back into its parts, then assign them to the correct variable

#
load_string = '23;12;5;1;0' # This would come from input()
#

I'm just going to use this string as an example, but you would simply change this in your code to use input()

#

so here we want to

Split the string at the ;
Assign each separate number to the correct variable

#

That's really only 2 steps. Not that bad

static sedge
#

okay how do we split the string?

tall blade
#

!e

load_string = '23;12;5;1;0' # This would come from input()
inventory_values = load_string.split(';')
print(inventory_values)
elfin hillBOT
tall blade
#

using .split(';')

#

Look at the result. It's a list!

#

Now, we just need to assign values based on the index

#

remember cash is the first value, then wood, then stone, then axe, then pickaxe

#

so how would you index this?

#

?

static sedge
#

inventory_values[]

tall blade
#

that's the list name, yes

#

but remember how to get the individual value from the list?

static sedge
#

[]

tall blade
#

yes, so what would cash be?

static sedge
#

23?

tall blade
#

no, that's not the index

#

we only care about the position of the value in the list

#

not the actual value

#

we just want to tell python "go get the first value"

static sedge
tall blade
#

yes

#

so you can do cash = inventory_values[0]

static sedge
#

okie lemme do that for the vars

#

so hows this

#

elif act == "save":
print(cash, wood, stone, axe, pickaxe, sep=";")
elif act == "load":
print("input your data")
load = input()
load_list = load.split(";")
print(load_list)
load_list[0] = cash

#

ive only done it for cash

tall blade
#

you have it backwards

#

it should be cash = ...

#

also, you can simplify where you use print and input together

#
print("input your data")
load = input()
static sedge
#

cash = load_list[0]

tall blade
#
load = input("input your data")
tall blade
static sedge
#

?

tall blade
#

you want these values to be int

#

When you split a string, the resulting list will always contain strings

#

so you actually need cash = int(load_list[0])

static sedge
#

at the start i have
cash = 0
wood = 0
stone = 0
axe = 0
pickaxe = 0

tall blade
static sedge
#

okay?

tall blade
#

just because you initially assigned them to int, doesn't mean that can't change later in the code

#

other languages are stricter about this stuff

#

but not python

static sedge
#

ohh i see now

#

elif act == "save":
print(cash, wood, stone, axe, pickaxe, sep=";")
elif act == "load":
print("input your data")
load = input()
load_list = load.split(";")
print(load_list)
cash = int(load_list[0])
wood = int(load_list[1])
stone = int(load_list[2])
axe = int(load_list[3])
pickaxe = int(load_list[4])

#

like this right?

tall blade
#

yup!

#

there's other ways we could simplify this, but it's ok how it is for a beginner

dull pivot
#

When you use load = input() the input will be of type string, not int

#

that's why you can use .split() on it

#

you can't .split() ints

static sedge
tall blade
#

as you learn more advanced techniques, it could look something like this

load_string = '23;12;5;1;0' # This would come from input()
cash, wood, stone, axe, pickaxe = map(int, load_string.split(';'))
#

although as this program gets more advanced, you'd probably end up with a better data structure for storing your inventory, like a dictionary

stone raft
#

or classes

static sedge
#

would you like to try the simple game?

dull pivot
#

yes, share a link

tall blade
#

I need to get going now, but I can see how it runs from the code

#

Keep going with it ๐Ÿ™‚

static sedge
#

just use the code in an ide

#

or somthing

tall blade
#

you're missing global cash at the start of the function

stone raft
#

im curious

#

ctrl alt T

tall blade
#

you have global wood, stone, axe, pickaxe

stone raft
#

if u type vim does it work

static sedge
stone raft
#

welp i tried my last ditch effort

static sedge
tall blade
#

the function that deals with saving and loading

static sedge
#

id need to global everything?

#

right

tall blade
#

just those 5 vars, yes

static sedge
#

oh i see what your talking about i didnt update it when i added the shop beore

#

i should all be working now!

dull pivot
#

it works, well done

elfin hillBOT
#
Python help channel closed for inactivity

This help channel has been closed. 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.