首页 > 解决方案 > Win check 的 Java 脚本刽子手问题

问题描述

我一直在尝试使用 javascript 制作一个刽子手游戏,但我正在努力获得两人和一人模式的胜利检查

alert('welcome to hang man here you will have ten guesses you may type one letter at '+
  'a time or try to guess the whole word but be careful each letter in the word '+
   'will count as a guess ');
game_mode_choice = prompt('what game mode would you like to play, A 1 player mode or B '+
   '2 player mode');
dictinary_array = ["dog", 'cat', 'elephant', 'fox', 'horse'];
character_limit = [];
guess = "";

if (game_mode_choice == "B") {
    usersGuesses = [];
    solved = false;

    alert('The first player will input a word for the other player to then guess got it okay');
    word_choice = prompt('Which word would u like to chose');

    for (spaces = 0; spaces < word_choice.length; spaces++) {
        // check if the charAt word_choice index of spaces is in a 
        //  list of the users guesses, if it is than you need to 
        //  push the letter instead of a blank space;
        character_limit.push(' _ ');
    }
    alert(character_limit);

    while (!solved) {
        guess = prompt("Please choose a letter");
        if (word_choice.includes(guess)) {
            for (i = 0; i < word_choice.length; i++) {
                if (word_choice[i] == guess) {
                    character_limit[i] = guess;
                    solved = true;
                }
            }
        }
        usersGuesses.push(guess);
        alert(character_limit + "\n\nLetters used so far: " + usersGuesses);
    }
}

标签: javascriptarrays

解决方案


尝试像这样创建函数:

function isWin(riddle, guess) {
  for (let i = 0; i < riddle.length; i += 1) {
    if (riddle[i] !== guess[i]) {
      return false;
    }
  }
  return true;
}

用法:

const win = isWin(word_choice, character_limit)

推荐阅读