变量不会在 Class 后更新
Variable Won't Update In Class
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
的地方循环代码,但我不知道如何解决这个问题。谢谢
看来问题出在这里:
while True:
Game().mainloop()
这会在循环的每次迭代中创建一个新的 Game
对象,这意味着所有值都是第一次初始化,因为它是一个新对象。
备选方案是将 while True
循环移动到 mainloop()
内,或尝试类似的操作:
game = Game()
while True:
game.mainloop()
这将创建一个 Game
对象作为 game
,其 mainloop()
方法被重复调用。由于该对象仅创建一次,因此因玩家操作而修改的对象属性(例如 money
,访问为 self.money
)将在循环迭代之间保持其值。
在原来的循环结构中,每次都会创建一个新的Game
对象,这意味着一个玩家的动作只执行了一次,然后对象被放弃并被一个新的对象取代,具有新初始化的属性.
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
的地方循环代码,但我不知道如何解决这个问题。谢谢
看来问题出在这里:
while True:
Game().mainloop()
这会在循环的每次迭代中创建一个新的 Game
对象,这意味着所有值都是第一次初始化,因为它是一个新对象。
备选方案是将 while True
循环移动到 mainloop()
内,或尝试类似的操作:
game = Game()
while True:
game.mainloop()
这将创建一个 Game
对象作为 game
,其 mainloop()
方法被重复调用。由于该对象仅创建一次,因此因玩家操作而修改的对象属性(例如 money
,访问为 self.money
)将在循环迭代之间保持其值。
在原来的循环结构中,每次都会创建一个新的Game
对象,这意味着一个玩家的动作只执行了一次,然后对象被放弃并被一个新的对象取代,具有新初始化的属性.