用鼠标在一组中只拖动一个精灵

Drag only one sprite in a group with the mouse

我不知道如何排序的问题是,当我将一块拖到另一块上时,第二块也会与第一块一起拖动。我尝试了几种方法来将鼠标选择一次限制为一件,但都失败了。任何人都可以帮忙 - 毫无疑问,有一个简单的方法!我所有失败尝试的代码如下:

   # In main loop:
   # Watch for keyboard and mouse events
       for event in pygame.event.get():
           if event.type == pygame.MOUSEBUTTONDOWN:
               mouse_held = True
           if event.type == pygame.MOUSEBUTTONUP:
               mouse_held = False

       # Update pieces that are in a sprite.Group()
       pieces.update(mouse_held)

    # In sprite class:
    def update(self, mouse_held):
        if mouse_held == True:
            self.mouse_coordinates = pygame.mouse.get_pos()
            if self.rect.collidepoint(self.mouse_coordinates) == True:
                self.rect.centerx = self.mouse_coordinates[0]
                self.rect.centery = self.mouse_coordinates[1]

你的问题相当难,但通过所有这些你应该无法实现你想要的。

您应该将 sprite class 更改为具有名为 depth 的新类型 int 变量('deeper' 的值越高)。

考虑到您有一个列表,其中包含要检查名为 spriteList 的点击的所有精灵对象,您应该添加以下内容:

from operator import attrgetter

然后更改这些行:

   if event.type == pygame.MOUSEBUTTONDOWN:
           mouse_held = True

至:

if event.type == pygame.MOUSEBUTTONDOWN:
    sprites = []
    for sprite in spriteList:
        if sprite.rect.collidepoint(event.pos)  ==  True:
            sprites.append(sprite)
    active = min(lists, key=attrgetter('depth'))
    mouse_held = True

您应该将 spriteupdate 函数替换为:

def update(self):
    self.mouse_coordinates = pygame.mouse.get_pos()
    if self.rect.collidepoint(self.mouse_coordinates) == True:
         self.rect.centerx = self.mouse_coordinates[0]
         self.rect.centery = self.mouse_coordinates[1]

最后,当您想更新精灵的位置时,只需输入:

if mouse_held:
    active.update()