如何将猜谜游戏中的统计信息保存在外部文本文件中

2024-09-27 07:27:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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?###

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


Tags: ofthetxtyou游戏numberif数字
2条回答

对于小数据,我更喜欢使用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

好吧,我设法想出来了,现在我觉得自己很傻,哈哈

我所要做的就是将一个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:)

相关问题 更多 >

    热门问题