Python 为什么我的类方法不更新属性?
我正在尝试使用pygame和random制作一个以恒定速度向下移动的精灵。但不幸的是,精灵只停留在一个地方。 问题在于itemMover()方法。它不会更新实例的属性值(debris1,在底部),因此每次y值增加速度值后,它都会重置为原始值。。。这会导致精灵静止不动。 我不知道为什么它不更新属性Python 为什么我的类方法不更新属性?,python,class,pygame,attributes,Python,Class,Pygame,Attributes,我正在尝试使用pygame和random制作一个以恒定速度向下移动的精灵。但不幸的是,精灵只停留在一个地方。 问题在于itemMover()方法。它不会更新实例的属性值(debris1,在底部),因此每次y值增加速度值后,它都会重置为原始值。。。这会导致精灵静止不动。 我不知道为什么它不更新属性 import pygame import random # variables mainWindow = pygame.display.set_mode((800, 600)) posX = rand
import pygame
import random
# variables
mainWindow = pygame.display.set_mode((800, 600))
posX = random.randint(0,800)
posY = 0
#speedXRight = 0.5
#speedXLeft = -0.5
# images
sprite = pygame.image.load("rockred.png")
xval = random.randint(50, 750)
ypos = 0
yspeed = 0.5
class item:
def __init__(self, xpos, ypos, yspeed):
self.xpos = xpos
self.ypos = ypos
self.yspeed = yspeed
# below method not working as intended
def itemMover(self, win, val):
############HELP HERE
print(self.ypos)
self.ypos += self.yspeed
############HELP HERE
print(self.xpos, self.ypos)
win.blit(val, (self.xpos, self.ypos))
mainLoop = True
while mainLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainLoop = False
#keycode.Main = False
debris1 = item(xval, 0, 0.5)
debris1.itemMover(mainWindow, sprite)
pygame.display.update()
输出:
0
167 0.5
0
167 0.5
0
167 0.5
0
167 0.5
0
167 0.5
0
167 0.5
0
167 0.5
0
167 0.5
还有一个带有静止精灵的窗口。方法
itemMover
可以工作,但是您可以在循环中连续地重新创建对象debris1
。因此,对象从每个帧的开始处开始。
在应用程序循环之前创建对象,并在循环中移动对象。此外,在绘制对象之前,必须通过以下方式清除显示:
debris1=项目(xval,0,0.5)
mainLoop=True
而主循环:
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
mainLoop=False
主窗口。填充(0)
debris1.itemMover(主窗口,精灵)
pygame.display.update()
原因是每次在循环中,您都会用ypos=0和yspeed=0.5重新创建对象debrise1,因此当您执行方法itemMover()时,它将始终显示相同的更改,您需要做的是在循环外创建对象,而循环中应该只包含methode itemMover(),如下所示:
mainLoop = True
debris1 = item(xval, 0, 0.5)
while mainLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainLoop = False
#keycode.Main = False
debris1.itemMover(mainWindow, sprite)
pygame.display.update()
看起来代码的行为符合预期。您正在每个循环上重新定义
debris1=item(xval,0,0.5)
,重置ypos
每个循环。尝试在循环外部定义debris1
,然后在循环内部调用debris1.itemMover(主窗口,sprite)
。这个问题已经得到了回答,但我将对其他问题发表评论。您说过您正在创建一个精灵,但您没有利用pygame.sprite.sprite
类。你应该这样做,因为这很有帮助。如果您确实开始使用sprite类,那么您还应该将itemMover()方法重命名为update(),这样您也可以使用pygame.sprite.Group()
s(尽管您必须更改该方法以除去update()之后的参数)
不带任何参数。pygame中内置的精灵功能相当不错。@Rabbid76这是因为我从未使用过pygame,所以我不知道这一点,反正我所理解的是你问题的根源