carmella diaz
carmella diaz

Reputation: 39

Storing Python game results in .txt file till next program run? (Python 3.8)

First of all, let me apologize for the title because I was not sure how to properly ask/state what I am trying to do. So let me get straight to explaining.

I am writing a Python dice program, where the user makes a bet (starting bet is $500) and chooses a number between 2 and 12. The user gets three rolls of the dice to match their number in which depending on the roll count, they add to their wage, win their wage, or subtract from their wage (bank amount). This continues till

  1. they exceed the bet limit, 500.
  2. Enter a 0 (zero) as the bet amount, in which 0 (zero) terminates the program.
  3. The user has lost all their money, thus the bank amount reaches 0 (zero).

This all works exactly as I need it to. However, I want to store the value of the bank amount to a .txt file so that, for example, if I quit the game with a total of $300, then next time I open and run the program I will start with $300 instead of the default $500. So I need to create this file and figure out how/where to incorporate it into my written program.

This is my code for the program so far:

import random

def rollDice(rcnt):
    die1 = random.randint(1,6)
    die2 = random.randint(1,6)
    x = int(die1 + die2)
    print('Roll #', rcnt, 'was', x)
    return x

def prog_info():
    print("You have three rolls of the dice to match a number you select.")
    print("Good Luck!!")
    print("---------------------------------------------------------------")
    print(f'You will win 2 times your wager if you guess on the 1st roll.')
    print(f'You will win 1 1/2 times your wager if you guess on the 2nd roll.')
    print(f'You can win your wager if you guess on the 3rd roll.')
    print("---------------------------------------------------------------")

def total_bank(bank):
    bet = 0
    while bet <= 0 or bet > min([500,bank]):
        print(f'You have ${bank} in your bank.')
        get_bet = input('Enter your bet (or 0 to quit): ')
        bet = int(get_bet)
        if get_bet == '0':
            print('Thanks for playing!')
            return bank, bet
        return bank, bet

def get_guess():
    guess = 0
    while (guess < 2 or guess > 12):
        try:
            guess = int(input('Choose a number between 2 and 12: '))
        except ValueError:
            guess = 0
        return guess

prog_info()
bank = 500
guess = get_guess
rcnt = 1
bet = 1  

while rcnt < 4 and bet:
    rcnt = 0
    bank,bet = total_bank(bank)
    if not bet: continue
    guess = get_guess()
    if guess == rollDice(rcnt+1):
        bank += bet * 2
    elif guess == rollDice(rcnt+2):
        bank += bet * 1.5
    elif guess == rollDice(rcnt+3):
        bank = bank
    else:
        if bet:
            bank = bank - bet
            if bank == 0:
                print(f'You have ${bank} saved in your bank.')
                print('Thanks for playing!')

Upvotes: 1

Views: 599

Answers (2)

ericl16384
ericl16384

Reputation: 364

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://www.w3schools.com/python/python_json.asp

This will write to (and overwrite) a file:

import json

saveData = {
    "var 1": 1234,
    "foo": "hello world",
    10: "in the morning"
}

# Saving
with open("save.txt", "w") as f: # Write
    # Remove the indent if you want it all on one line
    print(json.dumps(saveData, indent=4), file=f)

del saveData

# Loading
with open("save.txt", "r") as f: # Read
    saveData = json.loads(f.read())

print(saveData)
# Or, print with JSON to make it look good
print(json.dumps(saveData, indent=4))

WARNING: This only works with default Python objects. You will need to convert (serialize) any custom objects before dumping them to a file. Here is an example of serializing your objects:

class myClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def save(self):
        return {
            "x": self.x,
            "y": self.y
        }

    def load(self, data):
        self.x = data["x"]
        self.y = data["y"]

obj = myClass(1234, 5678)
objData = obj.save()

print(objData)
del obj

obj = myClass(None, None)
obj.load(objData)

Upvotes: 0

corvelk
corvelk

Reputation: 171

There's a built-in python function called open(): https://www.w3schools.com/python/python_file_write.asp

At the start of your program, you should have your program check for any saved progress by finding the file. If there is no file, your program should make one when one wants to stop playing.

A way of doing this can be:

try:
    f=open("winnings.txt","r") # reads the file for any saved progress, if it exists
    bank = int(f.readline())
    f.close() # closes the connection. important, as the file might be lost if you don't close it after using it

except IOError: # if the file doesn't exist
     bank = 500

...your code here...

f=open("winnings.txt","w") # overwrites the previous save
f.write(str(bank))
f.close()

Upvotes: 2

Related Questions