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

查看:25
本文介绍了如何让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天全站免登陆