【问题标题】:My game in pygame is not working properly [duplicate]我在 pygame 中的游戏无法正常运行 [重复]
【发布时间】:2021-01-01 02:57:40
【问题描述】:

我正在尝试用 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)

【问题讨论】:

  • 您是否因为在一个紧密的循环中运行而使资源的事件处理程序挨饿?
  • 我没听懂你在说什么
  • 您的代码运行在一个紧密的循环中。这可能意味着负责从操作系统收集鼠标点击的 Python 运行时和/或 Pygame 代码通常没有时间运行。您可以通过在while True 循环的末尾添加延迟来确认或排除此理论。 Here's an example。如果这导致您描述的行为消失,那么事件处理程序的资源匮乏确实是罪魁祸首。
  • 我应该延迟多少
  • 这对实验来说并不重要。 10 毫秒、100 毫秒等等。

标签: python pygame


【解决方案1】:

pygame.event.wait() 等待队列中的单个事件。删除函数 a 使用从 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多