2016-07-22 36 views
2

在pygame我有一個背景遊戲(在代碼圖像命名:'bg)和一個圖像(命名:'骰子') 我是試圖注意玩家何時點擊圖像,但是它向我寫道,骰子的矩形是0,0(x = 0和y = 0),而圖像顯示在740,40。pygame不認識我的形象

我該怎麼辦?

bg = pygame.image.load("temptry.gif") 
dice=pygame.image.load("dicee.gif") 
screen.blit(bg, (0, 0)) 
bg.blit(dice,(740,40)) 
pygame.display.update() 

while True: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      sys.exit() 
     if event.type == pygame.MOUSEBUTTONDOWN: 
      # Set the x, y postions of the mouse click 
      x, y = event.pos 
      print dice.get_rect() 
      if dice.get_rect().collidepoint(x, y): 
       print "omg" 
    screen.blit(bg, (0, 0)) 
    bg.blit(dice,(740,40)) 
    pygame.display.update() 
+0

'dice.get_rect()'默認會在(0,0)處產生一個pygame.Rect。嘗試使用'dice.get_rect(left = 740,top = 40).collidepoint(x,y)'代替。 –

+1

omg yess非常感謝你!!!!!而已! – roni280

回答

1

您的代碼有多個問題。在主循環之前,您不需要pygame.display.update()。接下來你應該.convert()你的圖片。例如dice = pygame.image.load(「dicee.gif」)。convert()。加載GIFS也可能存在問題。

看來你正在使用非常複雜的方式來做事情。 我會建議的是,你有所有的圖像加載在你的主循環後面,轉換。主循環結束後,圖像。而不是做bg.blit(dice,(740,40))你剛剛怎麼做screen.blit(bg,(740,40))

接下來你應該在主循環之後做一個鼠標位置變量。

它應該是這樣的

mouse_pos = pygame.mouse.get_pos() 

接下來,你應該爲你的骰子圖像rects。設置一個變量爲它

dice_rect = dice.get_rect()

然後再做一個if語句測試,如果有人點擊骰子圖像

if pygame.mouse.get_pressed()[0] and dice_rect.collidepoint(mouse_pos): 
     print "omg" 

然後做pygame.display.update()

希望這有助於,如果您對下面的評論有任何進一步的問題。

+0

我不能把兩張照片放在屏幕下(screen.blit),它不是這樣工作,我從這個問題的建議:http://stackoverflow.com/questions/19336585/how-to-blit -a-image-in-python-inside-the-area-of-specific-image?rq = 1 – roni280

+0

另外,我沒有加載照片的問題,它們顯示在我的正確位置上屏幕,但pygame只是不認識到他們是正確的地方 – roni280

+0

我猜你可以blit圖像罰款然後。只需使用碰撞點參數來測試一個人是否點擊圖像。 – abc1234