You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame井字棋:显示结束画面后自动重启游戏的时间处理问题

解决井字棋结束画面显示后再重置的问题

你当前代码的问题在于:time.sleep(2) 会直接阻塞程序,且绘制结束画面后没有更新显示,导致画面根本没机会展示就被重置了。Pygame 的渲染需要调用 pygame.display.update() 或 pygame.display.flip() 才能将绘制内容显示到屏幕上,而 time.sleep 会卡住整个程序,无法完成渲染刷新。

修改后的 reset_game() 函数

import pygame

def reset_game():
    global winner, draw, main_board, XO, screen, game_font, width, height

    # 1. 先绘制结束画面
    screen.fill((255, 255, 255))
    if winner:
        end_message = game_font.render(f"{winner} is the winner!", False, (0, 0, 0))
        end_message_rect = end_message.get_rect(center=(width/2, (height/2)+50))
        screen.blit(end_message, end_message_rect)
    elif draw:
        end_message = game_font.render("Draw", False, (0, 0, 0))
        end_message_rect = end_message.get_rect(center=(width/2, (height/2)+50))
        screen.blit(end_message, end_message_rect)
    
    # 2. 强制更新显示,让结束画面显示出来
    pygame.display.update()

    # 3. 等待2秒,用pygame的delay避免阻塞事件循环(比time.sleep更适配Pygame)
    pygame.time.delay(2000)  # 参数为毫秒,2000=2秒

    # 4. 重置游戏状态
    winner = None
    draw = None
    XO = "X"
    main_board = [[None] * 3, [None] * 3, [None] * 3]
    game_initiating_window()

关键说明

  • 先绘制再更新显示:必须在等待前调用 pygame.display.update(),否则绘制的内容不会被渲染到屏幕上。
  • 用 pygame.time.delay() 替代 time.sleep:delay 会让程序暂停指定毫秒数,且不会完全阻塞Pygame的内部事件处理,更适配游戏场景。
  • 顺序不能乱:绘制→更新显示→等待→重置状态,这个顺序是实现需求的核心。

内容的提问来源于stack exchange,提问作者Kamil Gryboś

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:40:50