所以我通过使用'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的信息。
global
对象不会移动,因为您没有将它们添加到Target
。您未将target_sprites
对象添加到pygame.sprite.Sprite
:
pygame.sprite.Group()
或将精灵传递给grpup的构造函数
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])