问题描述
所以基本上,我正在编写一个你必须点击按钮的游戏;当你点击它时,你的钱会增加 1。我会添加更多,但现在,我的点击有问题。
我的意思是每次我点击一次多次点击 挂号的。当我按住我的点击时,它会一直点击。我想让它当我点击一次时,只有一次点击被注册。
这是我的代码:
import pygame
from pygame.locals import *
pygame.init()
x = 0
black = (0,0)
myfont2 = pygame.font.SysFont("monospace",30)
myfont = pygame.font.SysFont("monospace",25)
green = (0,255,0)
blue = (255,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),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()
所以,是的,如果你们中的任何人都可以解释如何只注册一次点击并向我展示代码,我们将不胜感激。谢谢!
解决方法
您必须在事件循环而不是应用程序循环中处理事件(注意 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),blue)
screen.blit(text2,(350,50))
pygame.display.update()