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

美国州名猜谜游戏计时结束后仍可输入的问题及优化需求

问题解决与功能实现方案

现存问题修复

1. 计时结束后仍允许输入一次的问题

原因:原生input()是阻塞调用,当倒计时结束触发时间到的标记时,游戏线程可能正卡在input()等待用户输入,无法立即检测到时间状态变化。

解决方案:使用带超时的输入替代原生input(),结合threading.Event实现实时中断。每次输入设置1秒超时,确保能及时检测时间是否结束,避免卡住等待输入的情况。

2. 时间提醒干扰用户输入的问题

原因:直接print()时间提醒会打断用户正在输入的内容,导致输入提示符和提醒信息混乱重叠。

解决方案:利用终端控制字符先清除当前输入行,打印提醒后重新显示输入提示符,确保用户输入流程不被打断。

待实现功能完成

1. 移除美国海外领地

原列表中的非州/海外领地包括:American Samoa、Guam、Puerto Rico、Virgin Islands、District of Columbia(原列表错误拆分了该地区,直接移除相关条目)。保留纯50个美国州的列表。

2. 高分写入/更新文本文件

实现逻辑:游戏结束后读取high_score.txt中的现有高分(文件不存在则默认0),对比当前得分,若当前得分更高则覆盖写入新高分,否则保留原记录。


完整修复后代码

import time
import threading
import sys

# 兼容Windows/Linux的带超时输入实现
try:
    import msvcrt
    def input_with_timeout(prompt, timeout):
        print(prompt, end='', flush=True)
        start_time = time.time()
        input_str = ''
        while True:
            if msvcrt.kbhit():
                char = msvcrt.getche().decode('utf-8')
                if char == '\r':  # 处理回车
                    print()
                    return input_str
                elif char == '\x08':  # 处理退格
                    if input_str:
                        input_str = input_str[:-1]
                        sys.stdout.write('\b \b')
                        sys.stdout.flush()
                else:
                    input_str += char
            if time.time() - start_time > timeout:
                print('\nTime\'s up!')
                return None
except ImportError:
    import select
    def input_with_timeout(prompt, timeout):
        print(prompt, end='', flush=True)
        ready, _, _ = select.select([sys.stdin], [], [], timeout)
        if ready:
            return sys.stdin.readline().strip()
        else:
            print('\nTime\'s up!')
            return None

# 仅保留美国50个州,移除非州/海外领地
states = [x.lower() for x in [
    "Alaska", "Alabama", "Arkansas", "Arizona", "California", "Colorado",
    "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii",
    "Iowa", "Idaho", "Illinois", "Indiana", "Kansas", "Kentucky", "Louisiana",
    "Massachusetts", "Maryland", "Maine", "Michigan", "Minnesota", "Missouri",
    "Mississippi", "Montana", "North Carolina", "North Dakota", "Nebraska",
    "New Hampshire", "New Jersey", "New Mexico", "Nevada", "New York", "Ohio",
    "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
    "South Dakota", "Tennessee", "Texas", "Utah", "Virginia", "Vermont",
    "Washington", "Wisconsin", "West Virginia", "Wyoming"
]]

print("Welcome to the US states game!\nYou will have 60 seconds to name as many states as possible\nPress enter to start!")
input()
print("starting game!")

time_up_event = threading.Event()
score = 0

def countdown():
    total_time = 60
    for remaining in range(total_time, 0, -1):
        time.sleep(1)
        # 触发指定时间点的提醒
        if remaining in (45, 30, 15, 10, 5):
            # 清除当前输入行,避免干扰用户输入
            sys.stdout.write('\r' + ' ' * 50 + '\r')
            print(f"\n{remaining} seconds left!")
            sys.stdout.write("Guess a state: ")
            sys.stdout.flush()
    time_up_event.set()

def guessing_game():
    global score
    while not time_up_event.is_set():
        guess = input_with_timeout("Guess a state: ", 1)
        if guess is None:
            continue
        guess = guess.lower()
        if guess in states:
            score += 1
            print(f"Correct! score is now {score}")
            sys.stdout.write("Guess a state: ")
            sys.stdout.flush()
        else:
            print(f"{guess} is not a state! try again")
            sys.stdout.write("Guess a state: ")
            sys.stdout.flush()
    print(f"\nTime's up, final score is {score}")

def update_high_score(current_score):
    high_score_file = "high_score.txt"
    try:
        with open(high_score_file, 'r') as f:
            high_score = int(f.read().strip())
    except (FileNotFoundError, ValueError):
        high_score = 0
    if current_score > high_score:
        with open(high_score_file, 'w') as f:
            f.write(str(current_score))
        print(f"New high score! {current_score}")
    else:
        print(f"High score remains {high_score}")

# 启动线程
countdown_thread = threading.Thread(target=countdown)
game_thread = threading.Thread(target=guessing_game)

countdown_thread.start()
game_thread.start()

countdown_thread.join()
game_thread.join()

# 更新高分记录
update_high_score(score)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:02:46