2013-09-01 55 views
0

我正在開發一個簡單的遊戲,並使用小圓圈「系統」。我希望能夠點擊每個系統,以便在稍後的遊戲中我可以做更多的工作,但是我很難識別一次點擊。我將隨機生成的coords傳遞給字典,然後每個rect的碰撞都應該用鼠標位置進行檢查,但由於某種原因不再有效。任何幫助表示讚賞。Pygame .Rect不會與鼠標「碰撞」

這裏是一些更相關的代碼。

for i in range(NumSystems): 

    SysSize = random.randint(3,SystemSize) 
    SysY = random.randint(SystemSize*2,GVPHEIGHT-SystemSize*2) 
    SysX = random.randint(OverLayWidth+SystemSize*2,WINWIDTH-SystemSize*2) 



    SysList[str('SysNum')+str(i)] = ((SysSize,(SysX,SysY))) 
    SysCoords[str('SysNum')+str(i)] = pygame.draw.circle(DISPLAYSURF, WHITE, (SysX,SysY), SysSize, 0) 

    pygame.display.update() 

    #time.sleep(.25) 


#Code above is putting the random Coords into a dictionary. 
while True: 
    MousePos=mouse.get_pos() 
    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.QUIT() 
      sys.exit() 
     elif event.type == KEYDOWN: 
      # Handle key presses 

      if event.key == K_RETURN: 
       #Restarts the map 
       main() 
     elif event.type == MOUSEBUTTONDOWN: 
      if event.button == 1: 
       SysClicky(MousePos) 
       if SysClicked == True: 
        print('Clicked System') 
       elif SysClicked == False: 
        print('Something Else Clicked') 






def SysClicky(MousePos): 

for i in range(NumSystems): 
    print('Made to the SysClicky bit') 
    if SysCoords['SysNum'+str(i)].collidepoint(MousePos): 
     SysClicked = True 
     print(SysClicked) 
     return SysClicked 
    else: 

     SysClicked = False 
     return SysClicked 

回答

2

我不是什麼SysList/SysX/Y清楚,SysCoords是。它是否支持SysCoords中物品的寬度和高度?如果是,那已經在Rect()

below systems是你的dictRect s。

下面的代碼:

def check_collisions(pos): 
    # iterate dict, check for collisions in systems 
    for k,v in systems.items(): 
     if v.collidepoint(pos): 
      print("clicked system:", k) 
      return 

    print("clicked something else") 

while True: 
    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 

    elif event.type == MOUSEBUTTONDOWN: 
     if event.button == 1: 
      check_collisions(event.pos) 

    # render 
+0

關於列表的代碼只是多餘的,我忘了刪除它。 非常感謝!這正是我需要的,然後是一些 – ddaniels

0

Pygame的rect對象有這需要一個協調和返回基於碰撞的一個boolean collidepoint內置的方法。你可以像這樣輸入鼠標座標到函數中:

MousePos=mouse.get_pos() 
if mySurface.get_rect().collidepoint(MousePos): 
    doSomething()