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

打字游戏功能优化:实现错误输入拦截,强制正确输入后才可继续

打字游戏功能优化实现

我开发了一款可生成指定数量单词的打字游戏,游戏会询问用户需要的单词数量(比如输入1则生成1个单词)。希望实现以下核心功能:用户必须正确输入每个字母,若输入错误,程序将拦截后续操作,直到用户输入正确字母为止。

以下是我当前的代码:

import random
import time
import keyboard  # using module keyboard
import string # use this to get the alphabet
from random_word import RandomWords
r = RandomWords()
start_time=time.time()
def time_convert(sec):
  mins = sec // 60
  sec = sec % 60
  hours = mins // 60
  mins = mins % 60
x=0
print("How many words do you want to do?")
while True:

    sNumOfTimes=input()
    iNumOfTimes=int(sNumOfTimes)
    w = ""
    #message = w
    #message.replace(" ", "")
    for z in range(iNumOfTimes):
        w = r.get_random_word() + " "+ w
        w= w.strip()

    print(w[-100:100])

    while True:
            w = keyboard.read_key()
            al = chr(w)

修改后的完整代码

import random
import time
import keyboard
from random_word import RandomWords

r = RandomWords()

def time_convert(sec):
    mins = sec // 60
    sec = sec % 60
    hours = mins // 60
    mins = mins % 60
    return f"{int(hours)}h {int(mins)}m {round(sec,2)}s"

print("How many words do you want to do?")
while True:
    # 校验单词数量输入的有效性
    try:
        iNumOfTimes = int(input())
        if iNumOfTimes <=0:
            print("请输入大于0的整数")
            continue
        break
    except ValueError:
        print("请输入有效的整数")

# 生成指定数量的有效随机单词
target_words = []
for _ in range(iNumOfTimes):
    word = r.get_random_word()
    # 避免API返回空值,循环获取直到拿到有效单词
    while not word:
        word = r.get_random_word()
    target_words.append(word)
target_text = ' '.join(target_words)
print("\n开始输入:")
print(target_text)

start_time = time.time()
current_index = 0
total_chars = len(target_text)

# 逐字符校验输入逻辑
while current_index < total_chars:
    expected_char = target_text[current_index]
    input_char = keyboard.read_key()
    
    # 处理特殊按键:将keyboard模块返回的'space'转为实际空格字符
    if input_char == 'space':
        input_char = ' '
    # 忽略回车、方向键等无关按键
    elif len(input_char) > 1 and input_char != 'space':
        continue
    
    # 校验输入是否匹配当前预期字符
    if input_char == expected_char:
        current_index += 1
        print(input_char, end='', flush=True)
    else:
        # 输入错误时提示并等待正确输入
        print(f"\n错误!请输入正确字符:'{expected_char}'")

# 完成输入后展示用时
end_time = time.time()
elapsed_time = end_time - start_time
print(f"\n\n完成!用时:{time_convert(elapsed_time)}")

关键功能说明

  • 输入有效性校验:添加对单词数量输入的校验,确保用户输入合法的正整数。
  • 逐字符锁定逻辑:仅当输入字符与当前预期字符完全一致时,才推进到下一个字符;输入错误时会给出明确提示,强制用户修正后才能继续。
  • 特殊按键适配:处理空格按键的格式转换,同时过滤回车、方向键等无关操作。
  • 稳定性保障:添加循环获取随机单词的逻辑,避免API返回空值导致程序异常。
  • 结果反馈:完善时间转换函数,输入完成后展示总用时。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 23:45:03