【发布时间】:2020-09-23 05:40:50
【问题描述】:
我正在为学校创建一个 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()
乐谱文件的格式并不重要,只要我可以在游戏开始时输入他们的名字时编辑现有乐谱。如果不存在,请添加新用户。然后在每场比赛结束时打印分数。
我完全不知所措。
【问题讨论】:
标签: python text-files