我想将int变量“totalbal”保存到一个文本文件中,这样它就不会在每次退出时重置变量
import pygame, sys, time
from pygame.locals import *
cpsecond = open("clickpersecond.txt", "r+")
cps = int(cpsecond.read())
baltotal = open("totalbal.txt", "r+")
totalbal = int(baltotal.read())
pygame.init()
while True: # main game loop
...
if event.type == MOUSEBUTTONDOWN:
totalbal += cps
savebal = str(totalbal)
str(baltotal.write(savebal))
print("Your current money is", savebal, end="\r")
pygame.display.flip()
clock.tick(30)
单击时,它会将变量“totalbal”增加+1,单击8次时,它会保存在文本文件中,如012345678,我尝试用以下方法修复它:
int(baltotal.write(savebal))
但是没有成功
<<< Your current money is 1
<<< Your current money is 2
<<< Your current money is 3
<<< Your current money is 4
<<< Your current money is 5
<<< Your current money is 6
<<< Your current money is 7
<<< Your current money is 8
#The text file output: 012345678
如果要重写文件,只需在读写后关闭即可
为了使主进程更清晰,最好将文件写入委托给函数。你也应该考虑你到底想写多少次这个信息;大多数情况下,游戏状态不需要经常记录
相关问题 更多 >
编程相关推荐