-2

I am currently working on a Python number guessing game. In my game, players achieve "high scores" by making the fewest guesses possible. I plan to record those high scores in a text file.

Players earn a spot on the high-score list by finishing the game in fewer guesses than some previous high score. How can I modify and then write a new high score list to my "Top 10" text file? Below is the code for the program.

#If scores ever need to be reset just run function
def overwritefile():
    f = open("Numbergame.txt", "w")
    f.close()

with open('Numbergame.txt', 'rt') as f:
    for line in f:
        highscores.append(int(line.strip()))

# Compare the values from the list and current one
for i in range(len(highscores)):
    if highscores[i] > guesses:
        print(guesses)
        print(highscores[i])
        beatenscores += 1
        i + 1
    else:
        beatenscores += 0
  • Your question ("How do I get it to replace one of the values in the text file") shouldn't require all this extra code. Please restrict the code to the actual attempt of replacing a value in the file. – 9769953 Sep 22 '21 at 20:51
  • The obvious thing to do is to read the file into some structure, change the corresponding value, then write all the data back to file. – 9769953 Sep 22 '21 at 20:52

1 Answers1

1

It is possible to read values from a text file, do something with them, and then write values back to a file. The important things to take away are:

  • Python's powerful with open(...) system is the canonical general-purpose recommendation for reading from and writing to files (aka file-IO)
  • Make use of conditional statements (boolean logic) to determine if and how to modify data

If you want to take into account the output from your game (user score in the guesses variable you named), you'll need to modify your highscores list variable before writing back to the file. The standard way to write is the same with open() that you used to read from the file, but specifying write mode "w" instead of read mode "r". As a side note, you used "rt" for "read text" mode - the default mode of "r" "read" is "read text" mode. See this post for details.

Some caveats for the end-of-code suggestions below:

  • You didn't specify if your list of high scores in the text file was an ordered list of numbers or an unordered list. The suggestion below should work regardless of whether or not it's not an ordered list of numbers, so long as you don't care about the list potentially becoming unordered as new high scores are added.
  • With your current terminology, "high scores" are achieved with fewer guesses which is a little confusing, but probably not worth refactoring your code.
with open('Numbergame.txt', 'rt') as f:
    for line in f:
        highscores.append(int(line.strip()))
print(f"Old high scores: {highscores}")

#Compare the values from the list and current one
for i in range(len(highscores)):
    if highscores[i] > guesses:
        # print(guesses)
        # print(highscores[i])
        beatenscores += 1
        i + 1
    else:
        beatenscores += 0
print("You have beaten " + str(beatenscores)+ " scores")

maxscores = 10
# If a new high score is achieved, replace one of the worst (highest-value)
# scores on the high score list
if beatenscores > 0: 
    # Make room if max number of high scores already recorded
    if len(highscores) > maxscores:
        highscores.pop(highscores.index(max(highscores)))
    # Add new high score
    highscores.append(guesses)

print(f"New high scores: {highscores}")

# Write high score list to file
with open('Numbergame.txt', 'w') as f:
    for score in highscores:
        f.write(f"{score}\n")
DoodleVib
  • 159
  • 13
  • So each time I run the program it resets the textfile due to the last line at the end there do I just need to go about disabling it for a bit to get some highscores in? Or do I need to do something else? – KGGaming Fluff Sep 23 '21 at 11:08
  • @KGGamingFluff, do you mean that you would like your script to append user scores to the high score text file if the number of recorded scores is fewer than some max number of recorded scores (you suggested 10 above), and overwrite the highest (worst) score if the number of recorded high scores is already equal or greater to the max number of recorded scores? The code I suggested assumes that there are already the max number of high scores recorded. – DoodleVib Sep 23 '21 at 17:33
  • I would like that. I'm sorry if I misworded to it as I'm still new to using stackoverflow and didn't properly explain my question. – KGGaming Fluff Sep 23 '21 at 18:53
  • @KGGamingFluff, see modified answer and modified code. – DoodleVib Sep 24 '21 at 19:12