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但我不知道如何解決這個問題。謝謝
uj5u.com熱心網友回復:
看起來問題出在這里:
while True:
Game().mainloop()
這會Game在回圈的每次迭代中創建一個新物件,這意味著所有值都是第一次初始化,因為它是一個新物件。
替代方法是將while True回圈移動到內mainloop(),或嘗試類似的操作:
game = Game()
while True:
game.mainloop()
這將創建一個Game物件 as game,其mainloop()方法被重復呼叫。因為物件只被創建一次,作為玩家動作的結果修改的物件的屬性(例如money,訪問為self.money)將在回圈的迭代之間保持它們的值。
在原來的回圈結構中,Game每次都會創建一個新物件,這意味著在物件被放棄并被一個新的、具有新初始化屬性的新物件替換之前,玩家的動作只執行了一次。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/334169.html
