0

我对 Python 还是很陌生,所以对此我深表歉意。无论如何,我已经成功编写了一个数字猜谜游戏,玩家必须在指定的猜测次数内从 1 到 100 猜出正确的数字,这是由掷骰子产生的(例如,掷出 4 会给玩家 4 次尝试)。该程序一切顺利,但是,我希望能够在每个游戏结束时将游戏统计信息保存到一个文本文件,最好称为“statistics.txt”,格式如下:

Username | status | number of guesses

这是我制作的程序的代码:

import random



###Is this where I should place an open("statisitics.txt", "a") function?###

print("Welcome to the guessing game! What is your name?: ")
userName = input()
print("Hello " +userName+"! \nLets see if you can guess the number between"
                         "\n1 and 100! What you roll on the dice becomes"
                         "\nyour amount of guesses!")

theNumber = random.randint(1, 100)
diceNum = random.randint(1,6)
guess_limit = diceNum
guess_count = 0
out_of_guess = False
loopcounter = 0

userRoll = input("\nPress enter to begin the dice roll!: ")
if userRoll == "":
    print("You have "+str(diceNum)+" guesse(s)! Use them wisely!")
else:
    print("You have " + str(diceNum) + " guesse(s)! Use them wisely!")



while loopcounter < diceNum:
    print("Make a guess: ")
    guessNumber = input()
    guessNumber = int(guessNumber)
    loopcounter = loopcounter + 1

    if guessNumber < theNumber:
        print("Higher!")
    elif guessNumber > theNumber:
        print("Lower!")
    else:
        loopcounter = str(loopcounter)
        print("YOU WIN " +userName.upper() + "!!! You guessed the number " +loopcounter+ " times!")
        break

if guessNumber != theNumber:
    theNumber = str(theNumber)
    print("You lose! The number was " +theNumber +"! Better luck next time!")
###Or is this where I should place an open("statisitics.txt", "a") function?###

如果这看起来令人困惑,请再次道歉。任何建议将不胜感激。

4

2 回答 2

0

好吧,我想通了,现在我觉得很愚蠢,哈哈。

我所要做的就是将一个 open() 函数放入一个变量(我刚才称之为“f”)中,然后输入:f.write("\n" + userName + " | Loss | " + str(loopcounter))

尽管几乎没有什么变化,但我将向您展示它现在的样子:

import random

print("Welcome to the guessing game! What is your name?: ")
userName = input()
print("Hello " +userName+"! \nLets see if you can guess the number between"
                         "\n1 and 100! What you roll on the dice becomes"
                         "\nyour amount of guesses!")

theNumber = random.randint(1, 100)
diceNum = random.randint(1,6)
guess_limit = diceNum
guess_count = 0
out_of_guess = False
loopcounter = 0
f = open("statisitics.txt", "a")

userRoll = input("\nPress enter to begin the dice roll!: ")
if userRoll == "":
    print("You have "+str(diceNum)+" guesse(s)! Use them wisely!")
else:
    print("You have " + str(diceNum) + " guesse(s)! Use them wisely!")



while loopcounter < diceNum:
    print("\nMake a guess: ")
    guessNumber = input()
    guessNumber = int(guessNumber)
    loopcounter = loopcounter + 1

    if guessNumber < theNumber:
        print("Higher!")
    elif guessNumber > theNumber:
        print("Lower!")
    else:
        loopcounter = str(loopcounter)
        print("YOU WIN " +userName.upper() + "!!! You guessed the number in " +loopcounter+ " times!")
        f.write("\n" + userName + " | Win | " + str(loopcounter))
        break

if guessNumber != theNumber:
    theNumber = str(theNumber)
    print("You lose! The number was " +theNumber +"! Better luck next time!")
    f.write("\n" + userName + " | Loss | " + str(loopcounter))

这是测试多个游戏后“statistics.txt”文件的输出:

Cass | Loss | 3
Jacob | Loss | 3
Edward | Loss | 6
Bob | Loss | 1
Brody | Loss | 3
Harry | Loss | 4
Gary| Loss | 3
Seb | Loss | 1
Fred | Win | 5

无论如何,非常感谢@Jason Yang 和@alfasin 的额外帮助 :)

于 2020-06-17T06:26:11.593 回答
0

对于小数据,我更喜欢使用 json 文件,它可以在文件和变量之间快速轻松地转换。您可以找到以下代码的步骤:

from pathlib import Path
import json

# If database exist, load file to data, else create an empty data.
database = 'path for your database json file'  # like 'd:/guess/database.json'
if Path(database).is_file():
    with open(database, 'rt') as f:
        data = json.load(f)
else:
    data = {}

# if you have data for someome, like 'Michael Jackson', score, guesses.
name = 'Michael Jackson'
if name in data:
    score, guesses = data[name]['score'], data[name]['guesses']
else:
    data[name] = {}
    score, guesses = 0, 0

# During process, score, guesses updated, and program to exit.
data[name]['score'], data[name]['guesses'] = score, guesses

# dictionary updated, then save to json file.
with open(database, 'wt') as f:
    json.dump(data, f)

# That's all

对于文本文件的请求,我只是使用 text = str(dictionary) 来保存文本和 dictionary = eval(text) 方便。

from pathlib import Path

# If database exist, load file to data, else create an empty data.
database = 'path for your database txt file'  # like 'd:/guess/database.txt'
if Path(database).is_file():
    with open(database, 'rt') as f:
        text = f.read()
        data = eval(text)
else:
    data = {}

# if you have data for someome, like 'Michael Jackson', score, guesses.
name = 'Michael Jackson'
if name in data:
    score, guesses = data[name]['score'], data[name]['guesses']
else:
    data[name] = {}
    score, guesses = 0, 0

# During process, score, guesses updated, and program to exit.
data[name]['score'], data[name]['guesses'] = score, guesses

# dictionary updated, then save to json file.
with open(database, 'wt') as f:
    f.write(str(data))

# That's all
于 2020-06-16T09:04:18.000 回答