python - 当我按下一个按钮时,两个按钮被按下,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()
解决方案
如果您调用get_rect
a Surface
,Rect
则返回的结果将始终具有x
和的y
值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
或多次调用 of pygame.display.flip()
。
另一种解决方案是使用 pygame 的Sprite
类,它允许您组合 aSurface
和 a Rect
。
推荐阅读
- linux - 无法在 Linux 中打开目录,但我绝对可以“ls”显示它
- python - 我可以在 Django 中使多个子模型“可爱”吗?
- bash - 使用 AWK 计算文件中特定字母的比例
- php - Microsoft Graph API(日历)间歇性 503 错误
- asp.net-core - 有什么方法可以离线使用 NToasNotify 吗?
- flutter - 无效的 radix-10 数字(在字符 1 处)//flutter-update-4bb0a-default-rtdb.firebaseio.com/ ^
- python-3.x - 如何使用 numpy 和 python 计算小批量 SGD?
- javascript - OpenLayers 中的卫星视图 - 如何设置?
- angular - 如何将数据从数据库传递到 ng multiselect-dropdown
- python - 带有 Plotly Express 的宽格式 CSV