猿问

Pygame - 未检测到鼠标点击

我正在学习 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")

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


为了学习 Pygame,我使用开发人员的官方文档。https://www.pygame.org/docs/这是一种过时的学习方式吗?这就是我的代码继续运行错误的原因吗?


翻过高山走不出你
浏览 139回答 2
2回答

一只萌萌小番薯

pygame.mouse.get_pressed()当处理事件时,将评估返回的坐标。pygame.event.pump()您需要通过或 来处理事件pygame.event.get()。参见pygame.event.get():对于游戏的每一帧,您都需要对事件队列进行某种调用。这确保您的程序可以在内部与操作系统的其余部分进行交互。pygame.mouse.get_pressed()返回代表所有鼠标按钮状态的布尔值序列。因此,您必须评估any按钮是否被按下(any(buttons))或者是否通过订阅按下了特殊按钮(例如buttons[0])。例如:import pygamepygame.init()screen = pygame.display.set_mode((800, 800))run = Truewhile 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()如果您只想检测鼠标按钮何时按下或释放,那么您必须实现MOUSEBUTTONDOWNand MOUSEBUTTONUP(参见pygame.event模块):import pygamepygame.init()screen = pygame.display.set_mode((800, 800))run = Truewhile 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()Whilepygame.mouse.get_pressed()返回按钮的当前状态,而 MOUSEBUTTONDOWN和MOUSEBUTTONUP仅在按下按钮后发生。

慕桂英546537

函数 pygame.mouse.get_pressed 返回一个包含 true 或 false 的列表,因此对于单击,您应该使用-import pygamepygame.init()screen = pygame.display.set_mode((800, 800))run = Truewhile 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")
随时随地看视频慕课网APP

相关分类

Python
我要回答