简体   繁体   English

在 Hangman TypeScript 游戏结束时,一次显示一个下划线

[英]Reveal left over underscores one at a time at end of Hangman TypeScript game

When the game is over, I am trying to replace the underscores with the letters they missed one at a time using a setTimeout.游戏结束后,我尝试使用 setTimeout 将下划线替换为他们一次错过的字母。 This function swaps the underscore with the correct letter but, on the following render puts the letter back to the underscore and repeats this process until the end where it only displays the last missing letter.此函数将下划线与正确的字母交换,但是在接下来的渲染中将字母放回下划线并重复此过程,直到只显示最后一个丢失的字母为止。 I need all the letters to fully swap out the state.underscores, which is an array of strings.我需要所有字母来完全换出 state.underscores,它是一个字符串数组。

state.missingIndex is an array of numbers; state.missingIndex 是一个数字数组; missing letter indexes缺少字母索引

word is the complete word the player is guessing word 是玩家猜测的完整单词

using useReducer hook to change state使用 useReducer 钩子改变状态

React hooks and Typescript反应钩子和打字稿

  const displayMissingLetters = () => {
    let wrongWord: string[] = [];

    state.losses.missingIndex.forEach((num, index) => {
      setTimeout(() => {
        wrongWord = state.underscores
          .map((alpha: string, i: number) =>
            alpha === "_" && word[i] === word[num] ? word[num] : alpha
          );

        dispatch({ type: "SET_UNDERSCORES", underscores: wrongWord });

      }, index * 300);
    });
  }

This is what it looks like as of right now:这是它现在的样子:

显示下划线

This is what wrongWord looks like in the console:这是 wrongWord 在控制台中的样子:

控制台下划线

The problem is that when the timeout function fires, it has a stale copy of the state, set when all the timeouts are first scheduled.问题是当超时函数触发时,它有一个陈旧的状态副本,在所有超时第一次安排时设置。

It looks like you're using reducers here, so the easiest thing would be to handle this in a reducer.看起来您在这里使用了减速器,所以最简单的方法是在减速器中处理它。 Reducers get the current state as they begin to run, so they shouldn't ever have old/stale state. Reducers 在开始运行时获得当前状态,因此它们不应该有旧的/过时的状态。

setTimeout(() => {
  dispatch({ type: "REVEAL_LETTER", index: num });
}, index * 300)

Then move the logic that replaces an underscore with a letter, and saves that back in the state, to the reducer.然后将用字母替换下划线的逻辑移动到reducer,并将其保存回状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM