python - 变量不会在课堂上更新
问题描述
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
对象 as game
,其mainloop()
方法被重复调用。因为对象只被创建一次,作为玩家动作的结果而被修改的对象的属性(例如money
,访问为self.money
)将在循环的迭代之间保持它们的值。
在原来的循环结构中,Game
每次都会创建一个新的对象,这意味着玩家的动作只执行了一次,然后该对象就被放弃并被新的对象替换,具有新的初始化属性。
推荐阅读
- java - 现有的 Ant 项目和依赖项
- html - 如何使用复选框过滤 Angular 7 中的简单表格
- python - 无法在 jupyter notebook RPi3 中导入 python 包(已安装)
- python - 如何使其将张量板日志附加到以前的运行中?
- python - 如何在 Visual Studio 代码上使用 Python 2.7 将我的 txt 文件的内容插入到小部件中?
- node.js - 在nodeJS中传递变量
- javascript - 升级到 Xcode 10.2 和 swift 5 后无法使用 react native 运行 ios 应用程序
- push-notification - 推送通知无法正常工作 (push.js) | .Net Core SignalR
- jquery - 如何在 Postman 中编写此 jQuery 代码?
- python - 如何在熊猫中按user_id从列表中逐列获取唯一值