我正在使用可按下的按钮在pygame中制作游戏,但我希望它在点击时只做一件事。只要按住它,下面的代码就会打印“按下按钮”。更改此代码以使其每次点击仅打印一次的优雅方法是什么?
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()
答案 0 :(得分:4)
执行所需操作的一种简单而有效的方法是显式检查pygame.MOUSEBUTTONDOWN
事件,并在必要时仅执行鼠标事件处理。您还可以使用知道如何进行冲突检测的pygame' makeButton()
类来简化Rect
中的逻辑。
这就是我的意思:
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)
答案 1 :(得分:0)
我不是只有一个方法,而是制作一个按钮类,并为你需要的每个按钮实例化它。您还尝试创建自己的鼠标事件处理,每次游戏循环都会运行,但最好在pygame中将鼠标信息传递给鼠标事件上的此类按钮对象。只要有一个点击,MOUSEBUTTONDOWN和MOUSEBUTTONUP事件类型就会传递给事件队列。要创建您描述的行为,只有当鼠标位于MOUSEBUTTONUP事件的按钮范围内时,才能执行按钮操作。 This页面为pygame输入处理提供了一个很好的介绍,this页面提供了在pygame中创建常规按钮类的详细(虽然有点高级)讨论。
答案 2 :(得分:0)
我不知道这是否有帮助,但这对我有用。 我来自这样的代码:
..........ygame.mouse.get_pressed()
if x+ button_width > mouse[0] > x and y + button_height > mouse[1] > y:
pygame.draw.rect(screen, ac, ([x, y],[button_width, button_height])
if click[0] == 1:
if bn == 0:
button_0()
if bn == 1:
button_1()
if bn == 2:
button_2()
if bn == 3:
button_3()
if bn == 4:
button_4()
if bn == 5:
button_5()
与另一个添加全局变量is_clicked = False 程序开头的变量,全局语句 在函数中,以及2个if语句(6行代码)。 更改为此:
# (msg, (x, y coordinates),width,height,inactive color, active color,
# button number) all the info to place and label the buttons.
def按钮(msg,x,y,w,h,ic,ac,bn): 全局is_clicked 鼠标= pygame.mouse.get_pos() 点击= pygame.mouse.get_pressed() 如果x + button_width> mouse [0]> x和y + button_height> mouse [1]> y: pygame.draw.rect(screen,ac,([[x,y],[button_width,button_height]))
if click[0] == 1 and is_clicked == False:
is_clicked = True
if bn == 0:
button_0()
if bn == 1:
button_1()
if bn == 2:
button_2()
if bn == 3:
button_3()
if bn == 4:
button_4()
if bn == 5:
button_5()
if click[0] == 0 and is_clicked == True:
is_clicked = False # set is_clicked back to False after mouse
# button up.