繁体   English   中英

Pygame - 未检测到鼠标点击

[英]Pygame - Mouse clicks not getting detected

我正在学习 Pygame 来制作带有 Python 的游戏。但是,我遇到了一个问题。 我正在尝试检测玩家当前何时点击屏幕,但我的代码无法正常工作。 我的代码真的搞砸了吗,还是我正在使用的在线 Pygame 编译器?

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 800))

while True:
  pygame.display.update()
  mouse = pygame.mouse.get_pressed()
  if mouse:
    print("You are clicking")
  else:
    print("You released")

当我运行这段代码时,output 控制台每秒发送数千次文本“您正在单击”。 即使我没有点击屏幕,它仍然会这样说。 即使我的鼠标不在屏幕 只是相同的文本。 一遍又一遍。 Pygame 是否正确执行我的程序?

为了学习 Pygame,我使用的是开发者的官方文档。 https://www.pygame.org/docs/这是不是过时的学习方式,难道这就是我的代码一直运行报错的原因吗?

pygame.mouse.get_pressed()返回的坐标在处理事件时进行评估。 您需要通过pygame.event.pump()pygame.event.get()处理事件。

参见pygame.event.get()

对于游戏的每一帧,您都需要对事件队列进行某种调用。 这确保您的程序可以在内部与操作系统的 rest 进行交互。

pygame.mouse.get_pressed()返回代表所有鼠标按钮的 state 的布尔值序列。 因此,您必须评估是否按下了any按钮( any(buttons) )或者是否通过订阅按下了特殊按钮(例如buttons[0] )。

例如:

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 800))

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
  
    buttons = pygame.mouse.get_pressed()

    # if buttons[0]:  # for the left mouse button
    if any(buttons):  # for any mouse button
        print("You are clicking")
    else:
        print("You released")

    pygame.display.update()

如果您只想检测鼠标按钮何时被按下或何时被释放,那么您必须实现MOUSEBUTTONDOWNMOUSEBUTTONUP (参见pygame.event模块):

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 800))

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

        if event.type == pygame.MOUSEBUTTONDOWN:
            print("You are clicking", event.button)
        if event.type == pygame.MOUSEBUTTONUP:
            print("You released", event.button)

    pygame.display.update()

虽然pygame.mouse.get_pressed()返回按钮的当前 state,但MOUSEBUTTONDOWNMOUSEBUTTONUP仅在按下按钮时发生。

function pygame.mouse.get_pressed 返回一个包含 true 或 false 的列表,因此对于单击你应该使用 -

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 800))
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
  pygame.display.update()
  mouse = pygame.mouse.get_pressed()
  if mouse[0]:
    print("You are clicking")
  else:
    print("You released")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM