将最高分写入数据文件 [英] Writing a Top Score to a data file
本文介绍了将最高分写入数据文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个仅包含一个数字的文件;我正在写的游戏的最高分.
I am trying to create a file that will hold just one number; the highscore to a game I am writing.
我有
f = open('hisc.txt', 'r+')
和
f.write(str(topScore))
我想知道怎么做:
- 删除整个文件
- 获取文件中的数字并将其设置为游戏中的变量
- 检查topScore是否高于文件中的数字,如果是,则替换它
推荐答案
删除整个文件
with open('hisc.txt', 'w'):
pass
获取文件中的数字并将其设置为游戏中的变量
with open('hisc.txt', 'r') as f:
highScore = int(f.readline())
检查topScore是否高于文件中的数字
if myScore > highScore:
,如果是,则将其替换
if myScore > highScore:
with open('hisc.txt', 'w') as f:
f.write(str(myScore))
将它们放在一起:
# 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))
这篇关于将最高分写入数据文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文