如何在盒子周围建立互动区域?

时间:2015-04-25 16:32:57

标签: python python-3.x pygame

想象一下4个不同颜色的盒子的照片。以下是我试过的代码。我想知道当我点击其中一个框时会弹出其他图片(如何标记该区域并阅读点击以供以后使用)。有没有比这更简单的方法?

a, b = 685, 227
c, d = 310, 203
w, z = 684, 518
k, l = 311, 518
x, y = 310, 200
ekraan.blit(background,(x,y))

while True:
    for i in pygame.event.get():
        pygame.display.flip()
        if i.type == pygame.QUIT:
            sys.exit()
        elif i.type == pygame.MOUSEBUTTONDOWN:
            ma,mb = i.pos
            mc,md = i.pos
            mw,mz = i.pos
            mk,ml = i.pos
            if abs(ma-a)<379 and abs(mb-b)<319:
                ekraan.blit(green,(685,227))
                klickedButton = green
            elif abs(mc-c)<379 and abs(md-d)<319:
                ekraan.blit(red,(310,203))
                klickedButton = red
            elif abs(mw-w)<379 and abs(mz-z)<319:
                ekraan.blit(yellow,(684,518))
                klickedButton = yellow
            elif abs(mk-k)<379 and abs(mk-k)<319:
                ekraan.blit(blue,(311,518))
                klickedButton = blue

1 个答案:

答案 0 :(得分:0)

您的代码的一个改进是,您可以将点和它们各自的颜色一起放在元组列表中,并在检查事件时摆脱elif的墙:

quadrants = [(685, 227, green),
             (310, 203, red),
             (684, 518, yellow),
             (311, 518, blue)]
x, y = 310, 200
ekraan.blit(background, (x, y))

while True:
    for i in pygame.event.get():
        pygame.display.flip()
        if i.type == pygame.QUIT:
            sys.exit()
        elif i.type == pygame.MOUSEBUTTONDOWN:
            mx, my = i.pos
            for x, y, color in quadrants:
                if abs(mx-x) < 379 and abs(my-y) < 319:
                    ekraan.blit(color, (x, y))
                    klickedButton = color
                    break