簡體   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