我正在设计pygame中的增量/点击游戏,我希望每次点击都会将$ counter更改为1。但是,我可以按下按钮,我找不到限制它的方法。
我的按钮类如下:
class Button(object):
def __init__(self,x,y,width,height,color):
self.rect=(x,y,width,height)
self.image=pygame.draw.rect(screen, color,(self.rect),)
self.x=x
self.y=y
self.width=width
self.height=height
def check(self):
mouse=pygame.mouse.get_pos()
if self.x+self.width >mouse[0] > self.x and self.y+self.height >mouse[1] > self.y:
if pygame.mouse.get_pressed()[0]==True:
return True
有没有办法阻止按钮被按住?
感谢所有帮助!
完整代码:
import pygame, sys
from pygame.locals import *
pygame.init()
light_gray=(211,211,211)
black=(0,0,0)
white=(255,255,255)
def terminate():
pygame.quit()
sys.exit()
def drawText(text, font, screen, x, y,color):
textobj = font.render(text,True, color)
textrect = textobj.get_rect(center=(x,y))
screen.blit(textobj, textrect)
class Button(object):
def __init__(self,x,y,width,height,color):
self.rect=(x,y,width,height)
self.image=pygame.draw.rect(screen, color,(self.rect),)
self.x=x
self.y=y
self.width=width
self.height=height
def check(self):
mouse=pygame.mouse.get_pos()
if self.x+self.width >mouse[0] > self.x and self.y+self.height >mouse[1] > self.y:
if pygame.mouse.get_pressed()[0]==True:
return True
clock=pygame.time.Clock()
font=pygame.font.SysFont(None,50)
screen_width=1300
screen_height=700
screen=pygame.display.set_mode([screen_width,screen_height])
pygame.display.set_caption('Clicker')
done=False
money=0
sprites=pygame.sprite.Group()
button=Button(25,screen_height-125,500,100,light_gray)
while not done:
for event in pygame.event.get():
if event.type==QUIT:
terminate()
if button.check()==True:
money+=1
screen.fill(light_gray)
sprites.draw(screen)
pygame.draw.rect(screen,black,button.rect, 3)
text_width, text_height=font.size('Click!')
drawText('Click!', font,screen,button.x+button.width/2,button.y+button.height/2,black)
drawText('$'+str(money),font,screen,screen_width/2,25,black)
pygame.display.flip()
clock.tick(15)
pygame.quit()
答案 0 :(得分:2)
如果将button.check()
调用移动到事件循环,则每次鼠标点击而不是每一帧都会调用一次。
while not done:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
elif event.type == pygame.MOUSEBUTTONDOWN:
if button.check():
money += 1
我还建议在pygame.Rect
课程中使用Button
,然后您只需调用pygame.Rect.collidepoint
方法查看鼠标是否与按钮发生碰撞。
class Button(object):
def __init__(self,x,y,width,height,color):
self.rect = pygame.Rect(x,y,width,height)
self.image=pygame.draw.rect(screen, color,(self.rect),)
self.x=x
self.y=y
self.width=width
self.height=height
def check(self):
return self.rect.collidepoint(pygame.mouse.get_pos())
如果你想将它与按钮一起使用, pygame.mouse.get_pressed()
可能会有问题,因为它只会检查是否按下了鼠标按钮,而不是只按了一次鼠标按钮。
答案 1 :(得分:-2)
在button.check()
if语句中,它应该添加一个钱,然后等到鼠标未被点击:
if button.check()==True:
money+=1
while pygame.mouse.get_pressed()[0]==True:
clock.tick(10)
是吗?