Проблема в коде pygame

Вот у меня проблема с кодом, я хочу сделать так, чтобы в файл записывалась информация об переменной в текстовой файл и при следующем запуске она записалась в переменную. Вот мой код:

import pygame


pygame.init()
bg = pygame.image.load("images/kira.png")
window = pygame.display.set_mode((1300, 500)) 
screen = pygame.Surface((1300, 600))
start_game = True
print("Log")
score = 0
coins = 0
f = open('whu.txt','r')

coins = f.read()
f.close()


while start_game == True:
    for i in  pygame.event.get():
        if i.type == pygame.QUIT:
            start_game = False
        if i.type == pygame.KEYDOWN and i.key == pygame.K_w:
            coins += 1
            print(coins)
        if i.type == pygame.KEYDOWN and i.key == pygame.K_d and coins == 1000:
            coins -= 1000
            score += 1
            print("Молодец! Ты заработал 1 робукс! Теперь у тебя: " + str(score) + " робуксов! Кидай скрин Владу и пиши сколько хочешь вывести!")
            








    window.blit(screen, (1,1))
    screen.blit(bg, (1,0))


    pygame.display.update()

    while True:
        with open ('whu.txt', 'r') as f:
            old_data = f.read()

        new_data = old_data.replace('0', str(coins))

        with open ('whu.txt', 'w') as f:
            f.write(new_data)
        break






pygame.quit()

Ответы (1 шт):

Автор решения: Prog

Из текста задачи не понятно, какую именно переменную сохранять, поэтому я решил записывать обе - пришлось создать новый текстовый файл. Ну и плюсом чуток код почистил

Вот код:

import pygame


pygame.init()
bg = pygame.image.load("images/kira.png")
window = pygame.display.set_mode((1300, 500)) 
screen = pygame.Surface((1300, 600))
print("Log")
score = 0
coins = 0

f = open('whu.txt','r')
coins = int(f.read())
f.close()
print(f'coins = {coins}')

f = open('score.txt','r')
score = int(f.read())
f.close()
print(f'score = {score}')


while True:
    for i in  pygame.event.get():
        if i.type == pygame.QUIT:
            f = open('whu.txt','w')
            f.write(f'{coins}')
            f.close
            f = open('score.txt', 'w')
            f.write(f'{score}')
            f.close
            exit()
        if i.type == pygame.KEYDOWN and i.key == pygame.K_w:
            coins += 1
            print(f'coins = {coins}')
        if i.type == pygame.KEYDOWN and i.key == pygame.K_d and coins == 1000:
            coins -= 1000
            score += 1
            print("Молодец! Ты заработал 1 робукс! Теперь у тебя: " + str(score) + " робуксов! Кидай скрин Владу и пиши сколько хочешь вывести!")
→ Ссылка