在函数中使用附加到 pygame.sprite class 的属性时遇到问题

I'm having trouble with attributes attached to a pygame.sprite class when using them in functions

所以我修改了一些代码,使用 'pygame.sprite' 并制作了一个函数来处理所有绘图。如果你看到下面的代码,我正在尝试制作一个目标射击游戏,玩家向光标发射子弹并尝试击中目标。 'movement()' 函数旨在执行它在罐子上所说的,通过将 'self.rect.x' 值增加 0.5,使目标在每次屏幕刷新时移动。我在另一个函数 (refresh_window()' 中调用了该函数。'refresh_window()' 函数只处理所有绘图。但是当我 运行 游戏时,目标不会移动。我得到没有错误或任何错误,我猜这是因为 'movement()' 中的 self.rect.x 不是全局的,但是当我试图将其设为全局时,我收到一条错误消息:

File "main.py", line 60
    global item.rect.x
               ^
SyntaxError: invalid syntax

无论如何,我很难看到代码的问题,所以如果您能看到问题,请指出,我们将不胜感激。干杯。

class Target(pygame.sprite.Sprite):
    def __init__(self, width, height, offset, threshold):
        pygame.sprite.Sprite.__init__(self, target_sprites)
        self.image = pygame.Surface([width, height])
        self.image = target_img
        self.rect = self.image.get_rect()
        self.rect.center = (self.rect.x + 50, self.rect.y + offset)


target_sprites = pygame.sprite.Group()

target_1 = Target(100, 100, 100, 0)
target_2 = Target(100, 100, 300, 1000)
target_3 = Target(100, 100, 200, 2000)

#Function to make targets move each time screen refreshes.
def movement():
  global item.rect.x
  for item in target_sprites:
    item.rect.x += 0.5
    return


#Creating a function which will deal with redrawing all sprites and updating the screen.
def refresh_window():
  window.blit(bgr, (0,0))

  player_sprites.draw(window)
  target_sprites.draw(window)
  movement()
  pygame.display.update()

global item.rect.x 根本没有任何意义。删除此行并阅读有关 global statement 的内容。


Target 个对象不会移动,因为您没有将它们添加到 target_sprites。您错过了将 pygame.sprite.Sprite 对象添加到 pygame.sprite.Group():

target_sprites = pygame.sprite.Group()

target_1 = Target(100, 100, 100, 0)
target_2 = Target(100, 100, 300, 1000)
target_3 = Target(100, 100, 200, 2000)

target_sprites.add([target_1 , target_2, target_3])

或者将精灵传递给 grpup 的构造函数

target_1 = Target(100, 100, 100, 0)
target_2 = Target(100, 100, 300, 1000)
target_3 = Target(100, 100, 200, 2000)
target_sprites = pygame.sprite.Group([target_1 , target_2, target_3])