0
私はパイゲームでゲームを作っており、ハイスコアを保存します。コードを終了して再実行するたびに、スコアは決してファイルに保存されません。私は考えられる問題に目を向け、手作業で閉じようと試みていませんでした。誰もが、私はそれをはるかに高く評価されるだろう下のコードから行っているかもしれないものを知っている場合。.txtファイルを書き込むことはありません。
#This opens the file and sets the score as self.highscore
HS_FILE = "highscore.txt"
self.dir = path.dirname(__file__)
with open(path.join(self.dir, HS_FILE), 'w') as f:
try:
self.highscore = int(f.read())
except:
self.highscore = 0
#This is elsewhere in the code but the code around it runs fine
#self.score is created elsewhere
if self.score > self.highscore:
self.highscore = self.score
with open(path.join(self.dir, HS_FILE), 'w') as f:
f.write(str(self.score))
#for the purpose of confusion I will just print out the score to the command line
print(str(self.highscore))
'' r "'( "read"のように)使う必要がありますが、ファイルを消去する '" w "'を使うべきです。 – furas
BTW: 'print(str(self.highscore))'と 'f.write(str(self.score))'で 'str()'を使う必要はありません。自動的に文字列に変換されます。 – furas