我对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?###
如果这看起来令人困惑,请再次道歉。如有任何建议,将不胜感激
对于小数据,我更喜欢使用json文件,它可以快速方便地在文件和变量之间进行转换。您可以找到如下代码所示的步骤:
对于文本文件的请求,我只使用text=str(dictionary)来保存文本,使用dictionary=eval(text)来方便地保存文本
好吧,我设法想出来了,现在我觉得自己很傻,哈哈
我所要做的就是将一个open()函数放入一个变量(我刚才称之为“f”),然后键入:
f.write("\n" + userName + " | Loss | " + str(loopcounter))
我将向您展示它现在的样子,尽管事实上变化不大:
下面是测试多个游戏后“statistics.txt”文件的输出:
无论如何,非常感谢您的额外帮助@Jason Yang和@alfasin:)
相关问题 更多 >
编程相关推荐