首页 > 解决方案 > 当我按下一个按钮时,两个按钮被按下,pygame

问题描述

当我按下一个按钮时,有两个按钮被按下。我制作的图像就像一个按钮,但是当我按下第一个按钮时,第二个按钮也被按下了。我是 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()

标签: pythonpygame

解决方案


如果您调用get_recta SurfaceRect则返回的结果将始终具有x和的y0

因此,当您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或多次调用 of pygame.display.flip()

另一种解决方案是使用 pygame 的Sprite类,它允许您组合 aSurface和 a Rect


推荐阅读