2017-02-25 87 views
2

我無法弄清楚如何排序的問題是,當我將一塊碎片拖到另一塊碎片上時,第二塊碎片也會隨着第一塊一起拖動。我嘗試了幾種方法來限制鼠標的選擇,但都失敗了。任何人都可以幫助 - 毫無疑問,有一個簡單的方法!剪我所有的失敗嘗試的代碼如下:用鼠標拖動組中的一個精靈

# 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] 

回答

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 

您應該更換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() 
+0

謝謝,我也不會很快發現解決方案。爲了完整性起見,我不得不適應/修改代碼: 嘗試: 活性=分鐘(子畫面,鍵= attrgetter(「RECT」)) 除了ValueError異常: 打印(「空的地方選擇,所以子畫面列表爲空」) 和: 如果mouse_held: 嘗試: active.update() 除了UnboundLocalError: 打印( '積極不設置,以因前一個異常') – rms9