#๐ How do i add save/load to my game?
455 messages ยท Page 1 of 1 (latest)
@static sedge
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.
- what vars
- why txt file
- can u share code ?
!pastebin
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.
u can do a json or less safe but simpler is pickle
!d json.load
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).
!d json.dump
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.
lets not get ahead of ourselves, we havent seen their code, they might be a beginner who hasnt learned import yet

true
cash wood stone axe pickaxe
thats the only thing i thought of
my codes to long how do i do paste bin (im dumb)
!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.
also if you can save it all to a dict and load it from that dict adding the json save to file is easy
dict?
but json can only store list, dict, tuple, str, int... the basic types
dict is a list where instead of indexes the elements are referenced by names
yup this the kind of code i was expecting when i said "lets not get ahead of ourselves"
oh
lol
its not a bad thing
but ye they starting out 
@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')
:white_check_mark: Your 3.12 eval job has completed with return code 0.
somefile.txt
some text
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.
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 
what would be saved in the file?
u can see the bot output
it shows created files in output
as an addded bouns it makes sure to close it even if an error is raised
very cool feature 
so couple things u need to learn from that code which are the arguments of open
can u guess what 1st one means ? 
Yk what's pass? , if yes you should've used it in buying anyways my brain ain't braining
it just doesnt run the code
It's really useful for when you're trying to test something but this other thing isn't finished
Well that exactly what you did with buy func hence I was asking
!e
def buy():
pass
buy()
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
as u can see this just works
yeah
anyways that aside
can you remind me, the first one of what?
!e
with open('somefile.txt', 'w') as file:
file.write('some text')
:white_check_mark: Your 3.12 eval job has completed with return code 0.
somefile.txt
some text
thats open itself
eh also wrong
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 
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
would i do this?
file.write("id put my vars here")
thats a string
inside there
the 1st argument is the file path and name.extension of file
that simple
Instead of Bad clear and 100 blank lines you should use sys(clr) ๐ฅฒ
the w tells if its needed to make file or not
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
ive been useing an online ide ill switch later
if you go really simple than yes but that makes it hard to load we will use the json module when we get there
true
brother switch now, u will thank urself
i recommend thonny for beginners but vsc is the most popular choice
NO i dont wanna
I started with Pycharm and I gotta say the best decision ever , still I use thonny if I don't understand anything.
pycharm is not a good starting ide
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
back on topic how do i load the data with this file?
when i saw it at school i was scared couldnt find anything and just downloaded vsc after 5 minutes
thats where 2nd argument comes in
!d open
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`.)
?
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
ohhhhhhh
r+ to do woth
woth?
both sorry
package installing, venv creation, line completion suggestions, project handling , etc. @still remnant since u asked for examples
there is prob more i just dont know it all cause it just does so much fucking shit behind scenes
He deleted the messages ๐
i saw it and was replying to it before he deleted so im finish typing it
ยฏ_(ใ)_/ยฏ
try to incorporate with in ur code and come back if u struggle
ok brb
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
I dmed him so it doesn't clutter the thread
its not clutter if guy learns from it and stays away from pycharm 
should I stop using pycharm then? (I'm beginner as well) I've Pycharm VS Code and Thonny all installed
its
with open('somefile.txt', 'w') as file:
file.write('some text')
to write
but how does it change to read?
I think use r instead of w
onelineide pro
change 2nd argument (the mode) from write to read
definetly, it does way too much shit that even i cant list all, why u need something u dont know what is doing
vsc is popular choice but thonny is prob best for beginners
and def stay away from ai tools
https://www.onlineide.pro/
ive been useing it and i think its good
just def dont use replit
yeah but it's annoying to save files in directories when I could do that automatically with VSC or Pycharm , usually only use it when I don't understand something in code
What's the issue with replit (other than that it's expensive ๐)
last time i used replit i didnt spend a cent
u should NEVER use online ide period
I used it and it kinda sucks , I would prefer offline
did u change this from write mode ? 
why
cause they fucking suck
They don't have features ๐
my only complaynt is that it times you out in like 30 secs
brother if u run code locally u dont even wait 0.1s for it to run
no like if you dont respond in 30s it stops the code
also not a thing locally
ยฏ_(ใ)_/ยฏ
so i did
elif act == "file":
with open('somefile.txt', 'w') as file:
file.write('some text')
and nothing happend
that shitty website u running wont allow files created by code to be viewed
what do you want me to use then?
Btw isn't it better to make a file for functions and import that file?
run it locally
for something at this scale and simplicity ? nah
A quick walkthrough of installing the Linux subsystem and VSCode onto a Chromebook or ChromeOS Flex computer.
"its not supported for your cromebook"
(โฏยฐโกยฐ)โฏ๏ธต โปโโป
if u open terminal does python work
https://support.google.com/chromebook/answer/9145439?hl=en also u might need to follow this
Linux is a feature that lets you develop software using your Chromebook. You can install Linux command line tools, code editors, and IDEs (integrated development environments) on your Chromebook. Thes
crosh doesnt support python
.
u need to enable linux on it
watever the fuck thats supposed to mean
chromebooks weird me out
yeah no i cant + the developers part in settings is hidden to
i have to use an online ide
):
was this given to u for school or some shit
i boght it ยฏ_(ใ)_/ยฏ
we can make a work around im sure
why did u willingly buy a chromebook
i thought i would be good
i was wrong
bro I can't believe someone will buy it
*crome broseing
games are fun online
and discord
and youtube
its not that limiting
is it a chromebook flex
no
we shold make a workaround for the file thing
its more of a hassle than enabling dev mode
ctrl alt T
shell
does that work
in a lot of online games you can export a save as a string of numbers + letters, its on you to save it tho
NO THATS CROSH
wat
crosh can die alone in a hole with 36 worms and 17 spiders
what the fuck is crosh
i just want to know if shell works
issue is the wood_save part
bruh
I keep writing dumb stuff
its ok
its not dumb u just missed 1 detail
Obviously it won't be saved when I closed the program
do u have another 50 bucks to spare or something
just to buy a freaking rpi
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
so before u do that
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
well we dont need it to be big
we can simplify this approach and get rid of encode/decode part
but then what is accepted will be a lot more specific
elif act == "save":
print(cash, wood, stone, axe, pickaxe)
thats for export
ye now try loading

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
the only reason its huge is cause the amount of data that needs to be saved fyi
):
they dont make it big to make it big
do u know for
guys 5 is big
ur game is 1000x simpler than any game that uses system u described 
do u know while
yeah
for is another loop just like it
ik
except this one we dont itearte given a condition
we iterate over a iterable
!e
for i in range(10):
print(i)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
the most basic example
its ezer to read
not right now
in here range(10) is a iterable that contains the numbers 0 to 9 once each
and every iteration one of those numbers is assigned to i one by one
makes sense ?
yeah
well first we need to assign it to a variable
str or int
we can but range is not the only iterable that exists
well what u think 
str?
why not int
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
What are you currently stuck on?
making a load/save for his game when he cant use file cause he using an online ide cause he on a chromebook who cant turn on dev mode or shell on cli
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
yeah that's a good idea
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
current delimiter is just
but for a local game, that's fine
json isn't really that much more secure against cheating
what do the semicolons mean?
they're just meant as a symbol to make it easy to separate out the values
ok
!e
load_string = '100;12;8;1;0'
values = load_string.split(';')
print(values)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
['100', '12', '8', '1', '0']
the cheating thing wont be too much of an issue
it doesnt realy matter anyways
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
?
thats the hard part for me
i dont know how
Which part are you unsure of?
split the data
Here is how you split a string
is load_string a var?
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
do u know what list means ? or indexing ?
yeah
a list isn't a type of variable. It's a type of data
that makes sense
A list is a type of data that contains other data inside it
so like a var if it held other vars inside?
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
a var holds a value, a list holds many values is how i think about it
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
OH
so then what were the ; about then?
it's to encode the list into a string that you can copy and paste
That provided an easy way for us to convert a string into a list
Splitting a string always results in a list
and joining a list always results in a string
so from 1;3;4;6;9 to a list containing 1,3,4,6,9?
yes
okay
we could have used any symbol really. ; is just a nice obvious separator
i understand now
okay
if we want to specify a specific item within the list, we use "indexing"
continue?
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
so if i have
inport_list = [4, 7, 92, 4]
2 is 92?
yes exactly ๐
import_list[2] is 92 to be more exact
to access it, we use [] around the index number
this is the indexing syntax
!e
shopping_list = ['apples', 'eggs', 'milk']
print(shopping_list[0])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
apples
how are you doing the !e?
!code
!code
print("eheheh")
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
yeah i dont need that tho
#cash
#wood
#stone
#axe
#pickaxe
inventory = [23, 12, 5, 1, 0]
we will in a sec for loading
have a look at this list
okay so for exporting just print the list?
this says we have 23 cash, 12 wood, 5 stone, 1 axe, 0 pickaxe
i understand
so how would we print it?
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=';')
:white_check_mark: Your 3.12 eval job has completed with return code 0.
23;12;5;1;0
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=';')
:white_check_mark: Your 3.12 eval job has completed with return code 0.
23;12;5;1;0
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)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
23 12 5 1 0
sep lets us change how print works to override what character gets printed between each value
separator
!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 ')
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 23...12...5...1...0
002 | 23 and 12 and 5 and 1 and 0
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
elif act == "save":
print(cash, wood, stone, axe, pickaxe, sep=;)
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
okay how do we split the string?
!e
load_string = '23;12;5;1;0' # This would come from input()
inventory_values = load_string.split(';')
print(inventory_values)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
['23', '12', '5', '1', '0']
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?
?
inventory_values[]
that's the list name, yes
but remember how to get the individual value from the list?
[]
yes, so what would cash be?
23?
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"
[0]
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
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()
cash = load_list[0]
load = input("input your data")
Yes, there's one minor issue still though
?
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])
its in the code already
at the start i have
cash = 0
wood = 0
stone = 0
axe = 0
pickaxe = 0
yes, but when loading the data, you need to make sure they remain ints
okay?
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
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?
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
yeah i learned 4 things today
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
or classes
would you like to try the simple game?
yes, share a link
I need to get going now, but I can see how it runs from the code
Keep going with it ๐
you're missing global cash at the start of the function
you have global wood, stone, axe, pickaxe
if u type vim does it work
no
welp i tried my last ditch effort
witch one?
the function that deals with saving and loading
just those 5 vars, yes
oh i see what your talking about i didnt update it when i added the shop beore
i should all be working now!
it works, well done
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.