当我按下一个按钮时,会同时按下两个按钮,pygame。

3
当我按下一个按钮时,两个按钮都被按下了。 我创建了像按钮一样的图像,但当我按下第一个按钮时,第二个按钮也被按下了。 我是pygame新手,正在尝试让每个按钮在单击时执行不同的操作。
import pygame
import time

pygame.init();
screen = pygame.display.set_mode((340,340));
img = pygame.image.load('3.gif')
iimg = pygame.image.load('2.gif')
mg = pygame.image.load('4.gif').convert()
g = pygame.image.load('5.gif')
waitingForInput = False
pygame.display.set_caption("SIMON");
BEEP1 = pygame.mixer.Sound('beep1.wav')
BEEP2 = pygame.mixer.Sound('beep2.wav')
BEEP3 = pygame.mixer.Sound('beep3.wav')
BEEP4 = pygame.mixer.Sound('beep4.wav')
screen.blit(img,(0,0))
screen.blit(mg,(150,0))
pygame.display.flip()

def main():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False

            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = event.pos

                if img.get_rect().collidepoint(mouse_pos):
                    print ('button was pressed at {0}'.format(mouse_pos))
                    BEEP1.play()
                    screen.blit(iimg,(0,0))
                    pygame.display.flip()
                    time.sleep(.30)
                    screen.blit(img,(0,0))
                    pygame.display.flip()


                if mg.get_rect().collidepoint(mouse_pos):
                    print ('button was pressed at {0}'.format(mouse_pos))
                    BEEP2.play()
                    screen.blit(g,(150,0))
                    pygame.display.flip()
                    time.sleep(.30)
                    screen.blit(mg,(150,0))
                    pygame.display.flip()

main()

另外一件事:您可能需要在个人资料中将 software prgrammer at apple 更改为 software programmer at apple ;) - iLuvLogix
1个回答

1
如果在Surface上调用get_rect,则返回的Rect始终具有xy值为0
因此,在事件循环中运行 if img.get_rect().collidepoint(mouse_pos)时,您不是检查Surface是否被点击。您只是检查鼠标位置是否在屏幕左上角。
您可以使用一些print语句进行检查。
您可以为每个按钮创建一个Rect,并在主循环之外使用这些矩形进行blitting:
...
img = pygame.image.load('3.gif')
img_rect = img.get_rect()
...
mg = pygame.image.load('4.gif').convert()
mg_rect = img.get_rect(topleft=(150,0))
...
while True:
   ...
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = event.pos

            if img_rect().collidepoint(mouse_pos):
                BEEP1.play()

            if mg_rect ().collidepoint(mouse_pos):
                BEEP2.play()

    screen.blit(img, img_rect)
    screen.blit(mg, mg_rect)

注意,在主循环中还应避免使用time.sleep或多次调用pygame.display.flip()
另一个解决方案是使用pygame的Sprite类,它允许您将SurfaceRect组合在一起。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接