我不知道如何排序的问题是,当我将一块拖到另一块上时,第二块也会与第一块一起拖动。 我已经尝试了几种方法将鼠标选择限制为一次一块,但都失败了。 任何人都可以帮忙 - 毫无疑问,有一个简单的方法! 我所有失败尝试的代码如下:
# 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
类更改为具有一个名为depth
的 int 类型的新变量(值越高,它越"深")。
考虑到您有一个要检查点击的所有精灵对象的列表,称为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
您应该将sprite
的update
函数替换为:
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()