将 Python 游戏结果存储在 .txt 文件中直到下一个程序 运行? (Python 3.8)

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

首先,让我为标题道歉,因为我不确定如何正确 ask/state 我想做的事情。那么让我直接解释吧。

我正在编写一个 Python 骰子程序,用户在其中下注(起始赌注为 500 美元)并选择 2 到 12 之间的数字。用户获得三卷骰子以匹配他们的数字其中,根据掷骰数,他们会增加工资、赢得工资或从工资中减去(银行金额)。这一直持续到

  1. 他们超过了下注限额 500。
  2. 输入0 (zero)作为下注金额,其中0 (zero)终止程序。
  3. 用户输光了所有的钱,银行存款达到0 (zero)

这一切都完全符合我的需要。但是,我想将银行金额的值存储到 .txt 文件中,这样,例如,如果我退出游戏时总共有 300 美元,那么下次我打开并 运行 程序时我将从 300 美元开始,而不是默认的 500 美元。所以我需要创建这个文件并找出 how/where 以将其合并到我编写的程序中。

到目前为止,这是我的程序代码:

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

有一个名为 open() 的内置 python 函数:https://www.w3schools.com/python/python_file_write.asp

在你的程序开始时,你应该让你的程序通过查找文件来检查任何保存的进度。如果没有文件,当你想停止播放时,你的程序应该制作一个。

一种方法可以是:

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

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

这将写入(并覆盖)一个文件:

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

警告:这仅适用于默认 Python 对象。在将它们转储到文件之前,您需要转换(序列化)任何自定义对象。这是序列化对象的示例:

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)