如何使pygame按钮仅注册一键? [英] how to get pygame button to register only one click?

查看:93
本文介绍了如何使pygame按钮仅注册一键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个可按下的按钮在pygame中制作游戏,但我希望它在单击时只能做一件事.只要按住不放,下面的代码就会打印按下按钮".更改此代码以使其每次单击仅打印一次的一种优雅方法是什么?

I'm making a game in pygame with a pressable button, but I want it to do only one thing when clicked. The code below prints "button pressed" for as long as you hold it down. What's an elegant way to change this code to make it only print that once per click?

import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((640, 480),0,32)
clock = pygame.time.Clock()

def makeButton(x,y,width,height):
    if x + width > cur[0] > x and y + height > cur[1] > y:
        if click == (1,0,0):
            print "button pressed"


square = pygame.Rect((0,0), (32,32))

while True:
    cur = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    makeButton(square.left,square.top,square.width,square.height)

    screen.fill((255,255,255))
    screen.fill((55,155,0), square)
    pygame.display.update()
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()

推荐答案

一种简单有效的方法来执行所需操作,即显式检查pygame.MOUSEBUTTONDOWN事件,仅在必要时进行鼠标事件处理.您还可以使用pygame的Rect类简化makeButton()中的逻辑,该类知道如何进行冲突检测.

A simple and more efficient way to do what you want would be to explicitly check for pygame.MOUSEBUTTONDOWN events and only do the mouse event processing when necessary. You can also streamline the logic in makeButton() by using pygame's Rect class which knows how to do collision detection.

这是我的意思:

import pygame
import sys

pygame.init()
screen = pygame.display.set_mode((640, 480),0,32)
clock = pygame.time.Clock()

def makeButton(cur, rect):
    if rect.collidepoint(cur):
        print "button pressed"

square = pygame.Rect((0,0), (32,32))

while True:
    screen.fill((255,255,255))
    screen.fill((55,155,0), square)
    pygame.display.update()
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:  # left mouse button?
                makeButton(event.pos, square)

这篇关于如何使pygame按钮仅注册一键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆