dave thawley
dave thawley

Reputation: 13

Saving a highscore - Python 3

I'm trying to save a score for my game. I've got a piece of example code, why isn't it saving, if so, how would I go about fixing it?

hisc = open("highscore.txt","w+")
hi = hisc.read()
if hi == '':
    hisc.write('0')
    hi = '0'
if score > int(hi):
    hisc.write(str(score))
    print("NEW HIGHSCORE!")
else:
    print("HIGHSCORE =",hi)

Upvotes: 1

Views: 2483

Answers (4)

Ethan Lipson
Ethan Lipson

Reputation: 488

In this case, you should use with and as to open your text file.

with open("foo.txt", "w") as bar:
    # code that references bar goes here

The great thing about this method is that it automatically closes the file for you, and handles some other things for you as well.

In your case, it would look like this:

with open("highscore.txt", "w+") as hisc:
    hi = hisc.read()
    if hi == '':
        hisc.write('0')
        hi = '0'
    if score > int(hi):
        hisc.write(str(score))
        print("NEW HIGHSCORE!")
    else:
        print("HIGHSCORE =",hi)

Upvotes: 1

TemporalWolf
TemporalWolf

Reputation: 7952

There are a few issues: First and foremost, you cannot use w+ as the file mode for a scorelist, as it opens for reading & writing, truncating the file first. So every time you open a file with w+, it first erases it, so you'll have an empty file every time. You want r+.

Second, I've removed hisc.write('0'). Since we treat an empty file as a zero anyway, and are going to immediately overwrite it with their high score if empty, it's not helpful.

Third, manually opening/closing files is discouraged. Instead, use a context manager

Finally, we need to seek(0) to get back to the start of the file, or else we are appending the score to the end. If we want to be able to reset the highscore list (which may make it smaller, we need to truncate() after we are finished writing to remove any extra that is left over.

with open("highscore.txt", "r+") as hisc:
    hi = hisc.read()
    if not hi:  # not hi will only be true for strings on an empty string
        hi = '0'
    if score > int(hi):
        print("NEW HIGHSCORE!")
        hisc.seek(0)  # We already read to the end. We need to go back to the start
        hisc.write(str(score))
        hisc.truncate()  # Delete anything left over... not strictly necessary
    else:
        print("HIGHSCORE =%s" % hi)

Upvotes: 2

epinal
epinal

Reputation: 1465

Use context managers in python every time you can. This will help you avoiding bugs related to closing resources and will save you a lot of debugging time.

If you don't know what a context manager is take a look at this: http://book.pythontips.com/en/latest/context_managers.html

new_score = 100

with open("highscore.txt", "r") as high_file:
    stored_val = high_file.read()
    high_score = int(stored_val) if stored_val else 0

with open("highscore.txt", "w") as high_file:
    if new_score > int(high_score):
        high_file.write(str(new_score))
        print("NEW HIGHSCORE!")
    else:
        print("HIGHSCORE =", high_score)

EDIT: I had to edit the example code and make it a fully functional based on comments. This code runs perfectly on python3.

Upvotes: 1

The Sleepy Penguin
The Sleepy Penguin

Reputation: 100

As @swimmingduck said, so need to add hisc.close() to the end of your code, as without it, Python wouldn't realise that you have finished writing to the file.

Upvotes: 0

Related Questions