#๐Ÿ”’ Saving user records

58 messages ยท Page 1 of 1 (latest)

wintry garnet
#

is it possible to save a user's name, age, XP, level, gender in a seperate file?

crystal dirgeBOT
#

@wintry garnet

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.

fervent ledge
#

can you show your current code

#

@wintry garnet hi

wintry garnet
#

it's not finished ok?

fervent ledge
#

it's fine

wintry garnet
#

k

fervent ledge
#

i really just need to know how you are storing the game state

tawny perch
wintry garnet
# fervent ledge i really just need to know how you are storing the game state
# Minecraft Terminal version

player_infos = {
    "name": "",
    "gender": "",
    "age": 0,
}

stats = {
    "lives": 3,
    "hp": 100,
    "shield": 0,
    "level": 0,
    "XP": 0
}

def gain_xp(amount):
    if stats["level"] < 100:
        stats["XP"] += amount
        while stats["XP"] >= 100 and stats["level"] < 100:
            stats["XP"] -= 100
            stats["level"] += 1
            print("")
            print(f"You leveled up! Current level: {stats['level']}")
        
        if stats["level"] == 100:
            stats["XP"] = 0


def create_player():
    print(" ")
    print("--- Create Your Character ---")
    name = ""
    gender = ""
    age = -1

    while name == "" or len(name) > 12:
        name = input("Insert your character's name: ").strip()

    while gender != "male" and gender != "female":
            gender = input("Insert your character's gender (male/female): ").lower()
    while age < 0:
        try:
            age = int(input("Insert your character's age: "))
        except ValueError:
            print("Error: age is invalid")

    player_infos["name"] = name
    player_infos["gender"] = gender
    player_infos["age"] = age


def stats_player():
    print(" ")
    print("--- STATS ---")
    print(f"Player name: {player_infos['name']}; Age: {player_infos['age']}; Gender: {player_infos['gender']}")
    print(f"{player_infos['name']}: {stats['lives']} lives")
    print(f"Hp: {stats['hp']}")
    print(f"Shield: {stats['shield']}")
    print(f"Level: {stats['level']}")


def fighting_mobs():
    pass


def explore():
    pass


def sleep():
    print(" ")
    print("--- SLEEP ---")
    if stats["hp"] > 80:
        print(f"{player_infos['name']} cannot go to sleep since hp is full")
    else:
        gain_xp(10)
        stats["hp"] += 20
        player_infos["age"] += 1
        print("Congratulations, you just earned 10 XP and received 20 hp")
        print(f"{player_infos['name']} is now {player_infos['age']} years old!")


choices = {
    "1": explore,
    "2": stats_player,
    "3": sleep
}

create_player()

while True:
    print(" ")
    print("--- Main Game ---")
    print("1. Explore")
    print("2. Take a look at your stats")
    print("3. Sleep (gain 10 XP and heal yourself)")
    print("4. QUIT")

    choice = input("Choose what you want to do next: ")

    if choice == "4":
        stop = input("Are you sure you want to quit? (Y/N): ").upper()
        if stop == "Y":
            print("Goodbye!")
            break
        else:
            continue

    elif choice not in choices:
        print("Error: action is not valid")

    else:
        choices[choice]()
#

oh my bad

fervent ledge
#

so you have

player_infos = {
    "name": "",
    "gender": "",
    "age": 0,
}

stats = {
    "lives": 3,
    "hp": 100,
    "shield": 0,
    "level": 0,
    "XP": 0
}

storing the game state right

wintry garnet
#

I know BUT, if the user exit the game, all the stats will be gone

fervent ledge
#

i know

wintry garnet
#

oh

fervent ledge
#

this can be reasonably serialized into a json string

#

{"name": "", "gender": "", "age": 0} is our json string

wintry garnet
#

can it be reused?

fervent ledge
#

json.loads will deserialize our string back into an object

#

so far so good?

#

json is a built-in python module

#

it has the functions dumps that serializes an object into a json string and loads that deserializes it back into a python object, which in this case is a dict

#

@wintry garnet you there?

wintry garnet
#

yes

fervent ledge
#

so we have a string that will we can store right?

#

we store this string in a file

#

and we can recover the game state later on

#

right?

#

you following so far?

wintry garnet
#

uhm

#

yes

fervent ledge
#

you can just ask

wintry garnet
#

no I was just reading

#

so I typed uhm because I didn't know what to type

#

my bad

fervent ledge
#

do you know how to write a file yet?

wintry garnet
#

what do you mean by write a file?

fervent ledge
wintry garnet
#

ok thank you!

#

I gotta go now

#

cya

fervent ledge
#

for when you get back:

from pathlib import Path

with Path("test.json").open("w") as f:
    f.write("test")
#

will create a file called test.json

wintry garnet
#

oh

fervent ledge
#

containing the string "test"

#

though in this case what we want to store is not test

#

but rather the json string from earlier

fervent ledge
#

obviously im not giving you the full answer key, but i think you should be able to synthesize these information that i have given you to write a function that writes your game state into a file

#

and to write a function that reads the file

#

and recover the game state from the string that we wrote

#

if you have any questions you can ask them

crystal dirgeBOT
#
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.