pythonpython-3.8file-writingstoring-data

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!')

Solution

  • 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()