Writing a Top Score to a data file

2019-09-20 20:26发布

I am trying to create a file that will hold just one number; the highscore to a game I am writing.

I have

f = open('hisc.txt', 'r+')

and

f.write(str(topScore))

What I want to know how to do is to:

  • Erase the entire file
  • Get the number in the file and make it a variable in the game
  • Check if the topScore is higher than the number in the file, and if so, replace it

3条回答
我想做一个坏孩纸
2楼-- · 2019-09-20 20:50
f = open('hisc.txt', 'w')
f.write('10') # first score
f.close()


highscore = 25 #new highscore

# Open to read and try to parse
f = open('hisc.txt', 'r+')
try:
    high = int(f.read())
except:
    high = 0

# do the check
if highscore > high:
    high = highscore

f.close()

# open to erase and write again
f = open('hisc.txt', 'w')
f.write(str(high))
f.close()

# test
print open('hisc.txt').read()
# prints '25'
查看更多
别忘想泡老子
3楼-- · 2019-09-20 21:10

Erase the entire file

with open('hisc.txt', 'w'):
    pass

Get the number in the file and make it a variable in the game

with open('hisc.txt', 'r') as f:
    highScore = int(f.readline())

Check if the topScore is higher than the number in the file

if myScore > highScore:

and if so, replace it

if myScore > highScore:
    with open('hisc.txt', 'w') as f:
        f.write(str(myScore))

Putting it all together:

# UNTESTED
def UpdateScoreFile(myScore):
    '''Write myScore in the record books, but only if I've earned it'''
    with open('hisc.txt', 'r') as f:
        highScore = int(f.readline())
    # RACE CONDITION! What if somebody else, with a higher score than ours
    # runs UpdateScoreFile() right now?
    if myScore > highScore:
        with open('hisc.txt', 'w') as f:
            f.write(str(myScore)) 
查看更多
我命由我不由天
4楼-- · 2019-09-20 21:12

Maybe it's my preference, but I am much more used to the idiom in which on initialization, you do

f = open('hisc.txt','r')
# do some exception handling so if the file is empty, hiScore is 0 unless you wanted to start with a default higher than 0
hiScore = int(f.read())
f.close()

And then at the end of the game:

if myScore > hiScore:
   f = open('hisc.txt', 'w')
   f.write(str(myScore))
   f.close()
查看更多
登录 后发表回答