我在pygame中的游戏无法正常运行

时间:2020-09-14 11:31:56

标签: python pygame

我正在尝试用pygame做井字游戏。如果单击任何一个正方形,将显示一个x。问题在于,要显示x,需要点击很多。这是代码:

while True:
    for event in pygame.event.get():
        if event == pygame.QUIT:
            pygame.quit()
            sys.exit()
        mouse_pos = pygame.mouse.get_pos()
        event = pygame.event.wait()
        screen.fill(bg_color)
        if event.type == pygame.MOUSEBUTTONDOWN and 250 < mouse_pos[0] < 300 and 250 > mouse_pos[1] > 199:
            mouse_clicked1 = True
        if event.type == pygame.MOUSEBUTTONDOWN and 301 < mouse_pos[0] < 351 and 249 > mouse_pos[1] > 201:
            mouse_clicked2 = True
    if mouse_clicked1:
        screen.blit(x, object_top_left)
    if mouse_clicked2:
        screen.blit(x, object_top)

1 个答案:

答案 0 :(得分:0)

pygame.event.wait()等待队列中的单个事件。使用从pygame.event.get()获得的事件来删除该函数。
如果事件类型为MOUSEBUTTONDOWN(或MOUSEBUTTONUP),则鼠标位置存储在pygame.event.Event()对象的pos属性中:

while True:
    for event in pygame.event.get():
        if event == pygame.QUIT:
            pygame.quit()
            sys.exit()
        
        if event.type == pygame.MOUSEBUTTONDOWN and 250 < event.pos[0] < 300 and 250 > event.pos[1] > 199:
            mouse_clicked1 = True
        if event.type == pygame.MOUSEBUTTONDOWN and 301 < event.pos[0] < 351 and 249 > event.pos[1] > 201:
            mouse_clicked2 = True
    
    screen.fill(bg_color)
    if mouse_clicked1:
        screen.blit(x, object_top_left)
    if mouse_clicked2:
        screen.blit(x, object_top)

请注意,pygame.event.get()获取并从队列中删除所有事件。因此,在循环中对pygame.event.wait()的调用很少返回任何事件。


此外,我建议使用pygame.Rect对象和collidepoint()

while True:
    for event in pygame.event.get():
        if event == pygame.QUIT:
            pygame.quit()
            sys.exit()
        
        if event.type == pygame.MOUSEBUTTONDOWN:
            rect1 = pygameRect(250, 200, 50, 50)
            if rect1.collidepoint(event.pos):
                mouse_clicked1 = True
            rect2 = pygameRect(300, 200, 50, 50)
            if rect2.collidepoint(event.pos):
                mouse_clicked2 = True
    
    screen.fill(bg_color)
    if mouse_clicked1:
        screen.blit(x, object_top_left)
    if mouse_clicked2:
        screen.blit(x, object_top)