我正在为学校制作一个Python猜谜游戏。 游戏本身运行良好,但我需要添加一个外部分数文件(.txt) 我尝试了很多不同的方法来实现这一点,但我遇到的问题是; 如果文件中存在用户名,如何更新该用户名的分数线
最后一个方法(在代码中)只是一个测试,如果找不到新用户名,则将其添加到文件中。这似乎覆盖了文件,没有添加新的用户名
# Import random library
import random
import os
# Welcome User to the game
print("Welcome to the game")
# Collect user details
userName = input("Please enter your Name: ")
# Roll the die for the number of guesses
print("Rolling the Dice!")
diceRoll = random.randint(1,6)
print("You have %d Guesses: " %diceRoll)
# Random picks the number to guess
number = random.randint(1,99)
guesses = 0
win = 0
lose = 0
# Loop checks the users input against the randint and supplies a hint, or breaks if correct
while guesses < diceRoll:
guess = int(input("Enter a number from 0 to 99: "))
guesses += 1
print("This is guess %d " %guesses)
if guess > 100:
print("Number out of range. Lose a turn")
if guess < number:
print("You guessed to low")
elif guess > number:
print("you guessed to high")
elif guess == number:
guesses = str(guesses)
print("You Win! you guessed the right number in",guesses + " turns")
win = +1
break
# If the user cannot guess the number in time, they receive a message
if guess !=number:
number = str(number)
print("You Lose. The number was: ",number)
lose = +1
with open('scoreList.txt', 'r') as scoreRead:
with open('scoreList.txt', 'w') as scoreWrite:
data = scoreRead.readlines()
for line in data:
if userName not in line:
scoreWrite.write(userName + "\n")
scoreRead.close()
scoreWrite.close()
分数文件的格式是什么并不重要,只要我可以在游戏开始时输入现有分数的名称时编辑它们。如果新用户不存在,请添加新用户。然后在每场比赛结束时打印分数
我完全不知所措
你在最后一个街区有多处失误。您可以打开
scoreList.txt
,但在with .. as
块之外执行写操作。在此块之外,文件将关闭。另外,由于您使用的是with .. as
,因此最终不必手动关闭文件然后,您迭代所有行,并为不包含它的每一行编写名称,可能会重复很多次。然后用
'w'
打开文件,告诉它覆盖。如果要追加,请使用'a'
试着这样做:
另外请注意,您当前正在将每个名字写入得分列表,而不仅仅是那些赢得比赛的名字
我相信您可以使用json模块实现这一点,因为它将允许使用json文件格式的字典中的数据
字典将是存储用户和相关分数的最佳方法,因为如果使用相关文本文件,在python中更容易访问这些值
我已使用有效的解决方案更新了您的代码:
这将检查JSON文件中是否存在当前玩家,然后将他们的分数添加到当前玩家字典中
在游戏结束时,它将检查是否:
然后将相应地打印分数列表。 不过要小心,如果用户名有任何错误,就会创建一个新用户
如果需要,还可以手动更新.json文件中的分数
相关问题 更多 >
编程相关推荐