国际象棋程序调用pyttsx3.speak后自动终止问题求助
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

