为什么我的类方法没有更新属性



我正在尝试使用pygame和random制作一个以恒定速度向下移动的精灵。但不幸的是,精灵只停留在一个地方。问题是方法itemMover((。它不会更新实例的属性值(debris1,位于底部(,因此每次,在y值增加速度值后,它都会重置为原始值。。。这导致精灵刚好静止。我不知道它为什么不更新属性。

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。因此,对象从每帧的开头开始。在应用程序循环之前创建对象,并在循环中移动对象
此外,在绘制对象之前,您必须通过pygame.Surface.fill()清除显示:

debris1 = item(xval, 0, 0.5)
mainLoop = True
while mainLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainLoop = False
mainWindow.fill(0)
debris1.itemMover(mainWindow, sprite)
pygame.display.update()

原因是每次在循环中,您都会重新创建ypos=0和yspeed=0.5的对象debrise1,因此当您执行方法itemMover((时,它将始终显示相同的更改,您要做的是在循环外创建对象,而循环内应该只有方法itemMoveer((,如下所示:

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()

最新更新