2014-06-21 54 views
-1

如何檢測哪個圖像被點擊,或者如何添加它們,有沒有我可以看的例子,我沒有搜索過。如何在pygame中創建具有相同屬性的多個實例

import pygame , random 
from pygame.locals import * 

pygame.init() 

screen = pygame.display.set_mode((800,600),16) 
screen.fill((60,120,160)) 

instances = 10 

while instances > 0: 
    image = pygame.image.load("image.png").convert() 
    image_rect = image.get_rect() 
    image_rect[0] = random.randint(10,700) 
    image_rect[1] = random.randint(10,500) 
    screen.blit(image,image_rect) 
    instances -= 1 

pygame.display.update() 

while True: 
    for event in pygame.event.get(): 
     if event.type == QUIT: 
      exit() 
     elif event.type == pygame.MOUSEBUTTONDOWN: 
      if event.button == 1: 
       if image_rect.collidepoint(event.pos): 
        print "image 1 clicked" 
+1

使用列表。如果你這樣循環,它會被覆蓋。 – aIKid

回答

1
instances = [] 

for _ in range(10): 
    image = pygame.image.load("image.png").convert() 
    image_rect = image.get_rect() 
    image_rect.x = random.randint(10,700) 
    image_rect.y = random.randint(10,500) 
    screen.blit(image, image_rect) 
    instances.append((image, image_rect)) 

現在你有名單instances
所有圖像,你可以通過instances[number]

if event.button == 1: 
     for index, (image, image_rect) in enumerate(instances): 
      if image_rect.collidepoint(event.pos): 
       print "image", index, "clicked" 

獲取圖像 -

BTW:你的下一步就是要學習和使用classSprite

相關問題