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

React实现Wordle克隆:猜中正确单词时gameOver状态无法触发

React Wordle克隆猜中单词不触发gameOver状态的问题修复

问题根源分析

从你的代码和描述来看,主要有两个核心问题导致猜中单词时无法触发gameOver状态:

1. 隐藏字符导致字符串匹配失败

你在判断单词有效性时,需要给currentWord拼接\r才能匹配词库的wordSet,说明词库中的单词(包括correctWord)大概率带有\r换行符,但你拼接的currentWord是纯5个小写字母,没有这个隐藏字符。表面上打印的字符串看起来一致,但实际比较时因为\r的存在导致currentWord === correctWord返回false。

2. 逻辑执行顺序不合理

当前代码先更新currentGuess状态,再判断是否猜中正确单词,不仅会产生不必要的状态更新,还可能在异步状态更新的特性下干扰后续判断逻辑。


修复方案

第一步:处理隐藏字符

先确认correctWord是否带有\r:

useEffect(() => {
  genWordSet().then((words) => {
    setWordSet(words.wordSet);
    setCorrectWord(words.todaysWord);
    // 打印字符细节,查看是否有隐藏的\r
    console.log('correctWord原始内容:', JSON.stringify(words.todaysWord));
    console.log('correctWord字符拆分:', [...words.todaysWord]);
  });
}, []);

根据结果选择其中一种处理方式:

方式A:给currentWord添加对应隐藏字符

let currentWord = '';
for (let i = 0; i < 5; i++) {
  currentWord += board[currentGuess.attempt][i].toLowerCase();
}
currentWord += '\r'; // 和词库单词保持一致格式

方式B:清理correctWord的隐藏字符

useEffect(() => {
  genWordSet().then((words) => {
    setWordSet(words.wordSet);
    // 去掉首尾空白字符(包括\r、\n等)
    setCorrectWord(words.todaysWord.trim());
  });
}, []);

第二步:调整逻辑执行顺序

将「猜中单词判断」放在最前面,避免无效状态更新:

const onEnter = () => {
  if (currentGuess.letterPosition !== 5) return;

  let currentWord = '';
  for (let i = 0; i < 5; i++) {
    currentWord += board[currentGuess.attempt][i].toLowerCase();
  }
  // 如果用方式A,这里加上\r:currentWord += '\r';

  // 先判断是否猜中正确单词,直接结束游戏
  if (currentWord === correctWord) {
    setGameOver({ gameOver: true, guessedWord: true });
    return;
  }

  // 再处理单词有效性和剩余尝试次数
  if (wordSet.has(currentWord + '\r')) {
    // 最后一次尝试未猜中,触发失败状态
    if (currentGuess.attempt === 5) {
      setGameOver({ gameOver: true, guessedWord: false });
    } else {
      setCurrentGuess({ attempt: currentGuess.attempt + 1, letterPosition: 0 });
    }
  } else {
    setValidWord('Not a valid word');
  }
};

额外调试技巧

可以用JSON.stringify()打印字符串,直观看到隐藏字符:

console.log('currentWord:', JSON.stringify(currentWord));
console.log('correctWord:', JSON.stringify(correctWord));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:25:48