如何让 MOUSEBUTTONDOWN 只检测左键点击?

问题描述

MOUSEBUTTONDOWN 检测 Left、Right 和 MouseWheel 事件。我想让它只检测左键点击。

代码

import pygame,sys,time
from pygame.locals import *
from millify import millify,prettify

pygame.mixer.init()
pygame.init()
pygame.mixer.music.load("soundtrack.wav")
WHITE = 255,255,255
font = pygame.font.SysFont(None,44)
cpsecond = open("clickpersecond.txt","r+")
cps = int(cpsecond.read())
baltotal = open("totalbal.txt","r+")
totalbal = int(baltotal.read())
totalbalM = prettify(totalbal,'.')
clock = pygame.time.Clock()
w = 800
h = 600
screen = pygame.display.set_mode((w,h))
pygame.display.set_caption('Tap Simulator')
Loop = True
background = pygame.image.load("Background.jpg")
egg = pygame.image.load("egg.png")
resized_egg = pygame.transform.scale(egg,(282,352))
text = font.render(f'Your total clicks are {totalbalM}',True,WHITE)
pygame.mixer.music.play(-1,0.0)
while Loop: # main game loop
    for event in pygame.event.get():
        if event.type == QUIT:
            Loop = False


        if event.type == MOUSEBUTTONDOWN: #I want it to only detect left click
            egg_rect = resized_egg.get_rect(topleft = (260,150))
            if egg_rect.collidepoint(event.pos):
                totalbal += cps
                totalbalM = prettify(totalbal,'.')
                text = font.render(f'Your total clicks are {totalbalM}',WHITE)
                print("Your total clicks are",totalbalM,end="\r")

    #print(pygame.mouse.get_pos()) #to get mouse pos
    screen.blit(background,(0,0))
    screen.blit(text,(235,557))
    screen.blit(resized_egg,(260,150))
    pygame.display.flip()
    pygame.display.update()
    clock.tick(30)

with open("totalbal.txt","w") as baltotal:
    baltotal.write(str(totalbal))
baltotal.close

pygame.quit()
sys.exit()

解决方法

MOUSEBUTTONDOWN 生成的 pygame.event.Event() 对象有两个提供鼠标事件信息的属性。 pos 是一个存储被点击位置的元组。 button 存储被点击的按钮。 button 属性的值为 1,2,3,4,5 分别代表鼠标左键、鼠标中键、鼠标右键、鼠标滚轮向上和鼠标滚轮向下。

因此,如果您想检测左键点击,您需要检查是否 event.button == 1:

while Loop: # main game loop
    for event in pygame.event.get():
        if event.type == QUIT:
            Loop = False


        if event.type == MOUSEBUTTONDOWN: #I want it to only detect left click
   
            if event.button == 1: # 1 == left 

                egg_rect = resized_egg.get_rect(topleft = (260,150))
                if egg_rect.collidepoint(event.pos):
                    totalbal += cps
                    totalbalM = prettify(totalbal,'.')
                    text = font.render(f'Your total clicks are {totalbalM}',True,WHITE)
                    print("Your total clicks are",totalbalM,end="\r")

    # [...]