如何在一键Pygame中不注册多次点击

2024-04-27 04:03:05 发布

您现在位置:Python中文网/ 问答频道 /正文

所以基本上,我在写一个游戏,你必须点击一个按钮;当你点击它时,你的钱会增加1。我要添加更多,但现在,我的点击有问题

我的意思是,每次我点击一次,多次点击都会失败 注册的。当我按住我的点击按钮时,它会一直点击。我想让它,当我点击它一次,只有一次点击得到注册

这是我的密码:

import pygame
from pygame.locals import *
pygame.init()
x = 0
black = (0,0,0)
myfont2 = pygame.font.SysFont("monospace",30)
myfont = pygame.font.SysFont("monospace",25)
green = (0,255,0)
blue = (255,0,0)
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("Hackathon Theamatic Project!")
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
    pygame.draw.circle(screen,green,(250,250),75,0)
    text1 = myfont.render("Click Me",1,blue)
    screen.blit(text1,(190,230))
    text2 = myfont2.render("Money:"+str(x),1,blue)
    screen.blit(text2,(350,50))
    if event.type == pygame.MOUSEBUTTONDOWN:
        if event.button == 1:
            screen.fill(black)
            x = x+1
            print(x)
            if x == 5:
                x = 0
    pygame.display.update()

所以,是的,如果你们中有人能解释一下如何只注册一次点击,并向我展示代码,我将不胜感激。谢谢大家!


1条回答
网友
1楼 · 发布于 2024-04-27 04:03:05

您必须在事件循环而不是应用程序循环中处理事件(注意Indentation):

# application loop
while True:

    # event loop
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()

    # INDENTATION
    # >|    
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                x = x+1
                print(x)
                if x == 5:
                    x = 0

    screen.fill(black)
    pygame.draw.circle(screen,green,(250,250),75,0)
    text1 = myfont.render("Click Me",1,blue)
    screen.blit(text1,(190,230))
    text2 = myfont2.render("Money:"+str(x),1,blue)
    screen.blit(text2,(350,50))
    pygame.display.update()

相关问题 更多 >