簡體   English   中英

多次在pygame中注冊

[英]multiple clicks registering in pygame

我正在嘗試制作一個在鼠標左鍵單擊時會改變顏色的板。 但是,當我單擊它時,它會循環is_square_clicked()3次。 這是一個問題,我只希望它執行一次。 您可能會猜到,這會導致我的程序出現問題。 那么如何將其限制為每次點擊一次通過? 謝謝!

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()

之所以會循環,是因為您按住鼠標足夠長的時間,使其可以檢查3次。 我認為,如果您在兩次單擊之間等待它,或者不每次檢查一次它就應該對其進行修復。

我會猜測,由於游戲在每次點擊時循環播放不止一次,因此更改的次數超過一次

即使點擊非常快,循環也會循環得更快(取決於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

每次單擊時,此代碼都會隨機顯示一個隨機的顏色背景,因此您可以從上述代碼中找出執行此操作的正確方法

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM