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

Python实现刽子手游戏每10秒扣分数计时器的方法及问题解决

Hangman Timer Implementation: Fixing Your Issue & Better Approaches

Hey there! Let's break down what's going wrong with your current code and build a cleaner, more reliable timer for your Hangman game that deducts 1 point every 10 seconds.

What's Wrong With Your Current Code?

First, let's spot the key issues in your existing implementation:

  • Blocks the main game: Your countdown() function runs a continuous loop that sleeps and prints messages, but if you run this directly, it'll freeze your game—users won't be able to input guesses while the timer is running. That's almost certainly why you're hitting errors at the 30-second mark; the main thread is stuck in the timer loop instead of handling core game logic.
  • Confusing timing logic: You're incrementing count every 0.5 seconds, then deducting a point on every iteration plus an extra when count == 20 (10 seconds). This doesn't align with your goal of 1 point every 10 seconds—right now you're deducting points way too frequently, leading to inconsistent scoring.
  • Uncontrollable stop condition: The stop_thread variable is local to your function, so there's no way to halt the timer when the user makes a correct guess or the game ends. This will keep running even after the game finishes, causing unexpected behavior.

A Better Implementation Using Threading

Since we need the timer to run in the background while the user plays, we'll use Python's threading module. This lets the timer operate independently without blocking the main game input. Here's a robust version:

import threading
import time

def hangman_timer(stop_event, score, score_lock):
    """Runs in a background thread, deducts 1 point every 10 seconds until stopped."""
    while not stop_event.is_set():
        time.sleep(10)
        # Only deduct if the timer wasn't stopped during the sleep
        if not stop_event.is_set():
            with score_lock:
                score[0] -= 1
            print(f"You took too long! Score deducted by 1. Current score: {score[0]}")

def main_game():
    # Use a list for score so it's mutable across threads (or use a class)
    score = [10]  # Starting score
    # Event to signal the timer to stop immediately
    stop_timer = threading.Event()
    # Lock to safely modify the score across threads (prevents race conditions)
    score_lock = threading.Lock()

    # Start the timer as a daemon thread so it exits when the main program does
    timer_thread = threading.Thread(target=hangman_timer, args=(stop_timer, score, score_lock), daemon=True)
    timer_thread.start()

    # Simulate your actual Hangman game logic here
    print("Welcome to Hangman! Start guessing letters, or type 'exit' to quit.")
    while True:
        guess = input("Your guess: ").strip().lower()
        if guess == "exit":
            print("Game over!")
            stop_timer.set()
            break
        # Example correct guess condition (replace with your word-check logic)
        if guess in "hangman":
            print(f"Correct! '{guess}' is in the word.")
            stop_timer.set()
            break

    # Wait for the timer thread to finish cleanup (optional for daemon threads)
    timer_thread.join()
    print(f"Final score: {score[0]}")

if __name__ == "__main__":
    main_game()

Key Improvements:

  • Non-blocking background thread: The timer runs independently, so users can input guesses without the game freezing.
  • Controllable stop: The threading.Event lets you instantly halt the timer when the user guesses correctly or quits—no more runaway timers.
  • Safe score updates: The threading.Lock ensures the score isn't modified by both the main thread and timer thread at the same time, preventing bugs from race conditions.
  • Clear timing: The timer sleeps for exactly 10 seconds between deductions, perfectly matching your requirement of 1 point per 10 seconds.

Alternative: Class-Based Cleanup (For Larger Games)

If you want more organized code (great for extending your Hangman game later), wrap the timer and game state in a class:

import threading
import time

class HangmanGame:
    def __init__(self, starting_score=10):
        self.score = starting_score
        self.stop_timer = threading.Event()
        self.score_lock = threading.Lock()
        self.timer_thread = None

    def start_timer(self):
        """Launch the background timer thread."""
        self.timer_thread = threading.Thread(target=self._timer_loop, daemon=True)
        self.timer_thread.start()

    def _timer_loop(self):
        """Internal loop that handles 10-second score deductions."""
        while not self.stop_timer.is_set():
            time.sleep(10)
            if not self.stop_timer.is_set():
                with self.score_lock:
                    self.score -= 1
                print(f"Too slow! Current score: {self.score}")

    def play(self):
        """Main game loop for user interaction."""
        self.start_timer()
        print("Hangman Game Start! Guess letters or type 'exit' to quit.")
        while True:
            guess = input("Your guess: ").strip().lower()
            if guess == "exit":
                self.stop_timer.set()
                break
            # Replace with your actual word validation logic
            if guess in "hangman":
                print(f"Nice! '{guess}' is part of the word.")
                self.stop_timer.set()
                break
        self.timer_thread.join()
        print(f"Game Over. Final Score: {self.score}")

if __name__ == "__main__":
    game = HangmanGame()
    game.play()

This class encapsulates all game state and timer logic, making your code easier to maintain and expand with new features later.

内容的提问来源于stack exchange,提问作者cena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:32:53