首页 > 解决方案 > 变量不会在课堂上更新

问题描述

import sys
import pygame
from pygame.locals import *
pygame.init()
class Game:
    def __init__(self):
        self.width = 800
        self.height = 900
        self.win = pygame.display.set_mode([self.width, self.height])
        self.caption = pygame.display.set_caption('Clicker Game','Game')
        self.money = 0 
        self.moneyperclick = 0

    def moneytracker(self):
        self.money = self.money + self.moneyperclick
        print(self.money)

    def mousestuff(self):
        self.mousepos = pygame.mouse.get_pos()
        self.clicked = pygame.mouse.get_pressed()

    def mainloop(self):
        self.mousestuff()
        for event in pygame.event.get():
            if event.type == MOUSEBUTTONDOWN:
                self.moneytracker()
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            pygame.display.update()

while True:
    Game().mainloop()

我对编码仍然有些陌生,但我很困惑为什么self.money即使我要求它更新变量也没有更新。我已经做了一些测试,我知道它正在循环我设置的代码,self.money = 0但我不知道如何解决这个问题。谢谢

标签: pythonpygame

解决方案


看起来问题出在这里:

while True:
    Game().mainloop()

这会在循环的每次迭代中创建一个新Game对象,这意味着所有值都是第一次初始化,因为它是一个新对象。

替代方法是将while True循环移到内部mainloop(),或尝试以下操作:

game = Game()
while True:
    game.mainloop()

这将创建一个Game对象 as game,其mainloop()方法被重复调用。因为对象只被创建一次,作为玩家动作的结果而被修改的对象的属性(例如money,访问为self.money)将在循环的迭代之间保持它们的值。

在原来的循环结构中,Game每次都会创建一个新的对象,这意味着玩家的动作只执行了一次,然后该对象就被放弃并被新的对象替换,具有新的初始化属性。


推荐阅读