多次点击在pygame中注册

时间:2013-06-29 01:08:09

标签: python pygame

我正试图制作一个在鼠标左键点击时改变颜色的电路板。但是当我点击它时,循环通过is_square_clicked()3次。这是一个问题,我只希望它做一次。你可能猜到这会导致我的程序出现问题。那么如何将每次点击限制为1次?谢谢!

def is_square_clicked(mousepos):
    x, y = mousepos
    for i in xrange(ROWS):
        for j in xrange(COLS):
            for k in xrange(3):
                if x >= grid[i][j][1] and x <= grid[i][j][1] + BLOCK:
                    if y >= grid[i][j][2] and y <= grid[i][j][2] + BLOCK: 
                        if grid[i][j][0] == 0:
                            grid[i][j][0] = 1
                        elif grid[i][j][0] == 1:
                            grid[i][j][0] = 0

while __name__ == '__main__':
    tickFPS = Clock.tick(fps)
    pygame.display.set_caption("Press Esc to quit. FPS: %.2f" % (Clock.get_fps()))
    draw_grid()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()
        elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
            mousepos = pygame.mouse.get_pos()
            is_square_clicked(mousepos)
    pygame.display.update()

2 个答案:

答案 0 :(得分:1)

它循环的原因是因为你按住鼠标足够长的时间来检查三次。我想如果你在点击之间等待,或者你不是每次都检查一个周期,那就应该修复。

答案 1 :(得分:0)

即时猜测,因为游戏每次点击多次循环,所以更改一次

即使点击非常快,循环也会更快地循环(取决于FPS)

这是一个将在每次点击时更改屏幕颜色的示例:

"""Very basic.  Change the screen color with a mouse click."""
import os,sys  #used for sys.exit and os.environ
import pygame  #import the pygame module
from random import randint

class Control:
    def __init__(self):
        self.color = 0
    def update(self,Surf):
        self.event_loop()  #Run the event loop every frame
        Surf.fill(self.color) #Make updates to screen every frame
    def event_loop(self):
        for event in pygame.event.get(): #Check the events on the event queue
            if event.type == pygame.MOUSEBUTTONDOWN:
                #If the user clicks the screen, change the color.
                self.color = [randint(0,255) for i in range(3)]
            elif event.type == pygame.QUIT:
                pygame.quit();sys.exit()

if __name__ == "__main__":
    os.environ['SDL_VIDEO_CENTERED'] = '1'  #Center the screen.
    pygame.init() #Initialize Pygame
    Screen = pygame.display.set_mode((500,500)) #Set the mode of the screen
    MyClock = pygame.time.Clock() #Create a clock to restrict framerate
    RunIt = Control()
    while 1:
        RunIt.update(Screen)
        pygame.display.update() #Update the screen
        MyClock.tick(60) #Restrict framerate

每次单击时,此代码都会显示随机颜色背景,因此您可以从上面的代码中找出正确的方法

祝你好运!

相关问题