如何在pygame中创建具有相同属性的许多实例

时间:2014-06-21 11:26:11

标签: python pygame

如何检测点击了哪个图像,或者如何添加它们ID,是否有任何我可以查看的示例,我搜索没有运气。

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 个答案:

答案 0 :(得分: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"

-

顺便说一句:您的下一步是学习并使用classSprite