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

国际象棋程序调用pyttsx3.speak后自动终止问题求助

Fixing the Chess Program Crash After "Check" Voice Announcement

Hey, I see exactly what's going on here—your program is freezing up after the "check" voice because of how you're using pyttsx3.speak(). That function is synchronous and blocking, plus it creates a temporary voice engine under the hood. When it finishes speaking, it can disrupt Pygame's main event loop, making the program look like it's terminated.

Let's fix this with two key changes:

1. Use a Persistent pyttsx3 Engine

Instead of calling pyttsx3.speak() directly (which makes a new engine every time), initialize a single engine instance once at the start of your program. This avoids unnecessary resource cleanup that can break your game loop.

2. Run Voice Announcements in a Background Thread

Since engine.runAndWait() (which handles the speech) blocks execution, we'll run the speech code in a separate thread. This way, Pygame can keep processing user input and rendering the board while the voice plays.

Step-by-Step Code Changes

First, add the threading import at the top of your file:

import pygame as p
import ChessEngine
import pyttsx3
import threading  # Add this line

Then, initialize the voice engine once in your main() function:

def main():
    p.init()
    # Initialize the voice engine once (reuse this for all announcements)
    engine = pyttsx3.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    # ... rest of your existing main() setup code ...

Now, replace your old CheckV logic with this async speech code:

if moveMade:
    if animate:
        animateMove(gs.moveLog[-1], screen, gs.board, clock)
    validMoves = gs.getValidMoves()
    
    # Check if we need to announce "check"
    if gs.inCheck():
        # Define a helper function for the speech task
        def announce_check():
            engine.say('check')
            engine.runAndWait()
        # Run the speech in a daemon thread (dies when main program exits)
        threading.Thread(target=announce_check, daemon=True).start()
    
    moveMade = False
    animate = False

You can also remove the CheckV global variable entirely—it's no longer needed with this simplified logic.

Why This Works

  • Persistent Engine: Reusing one engine instance prevents the odd state changes that come with creating/destroying engines every time you speak.
  • Background Thread: The speech runs in the background, so Pygame's main loop never gets blocked. Your game keeps responding to mouse clicks, rendering the board, and running like normal while the "check" voice plays.

内容的提问来源于stack exchange,提问作者AG-88301

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:40:38