1

我正在尝试制作一个通过鼠标左键单击改变颜色的板。但是当我单击它时,它会循环 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()
4

2 回答 2

1

它循环通过的原因是因为您按住鼠标的时间足够长,可以检查三遍。我认为如果你让它在点击之间等待,或者你不是每次循环都检查它,它应该被修复。

于 2013-06-29T20:07:25.933 回答
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

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

祝你好运!

于 2013-07-01T03:27:42.190 回答