测试用户输入值是否在给定数组中(JavaScript)

时间:2018-04-22 22:40:00

标签: javascript while-loop

我刚刚使用vanilla JavaScript创建了一个五轮摇滚剪刀游戏。该程序到目前为止运行得很好,除了每次我第一次开始游戏时它会将任何用户输入视为无效而无论什么并且不会计算该轮次。

这是我的代码:



// Global variables
let playerWins = 0;
let computerWins = 0;
let array = [];
let validInput = 0;
let newRound = "";

// This function generates a computer selection
const computerPlay = () => {
    array = ["rock", "paper", "scissors"]
    return array[Math.floor(Math.random() * array.length)];
}

// This function stores player selection
const playerSelection = (selection) => {
    selection = prompt("Enter: 'Rock', 'Paper' or 'Scissors'").toLowerCase();
    validInput = array.indexOf(selection);
    console.log(validInput);
    
    // This loop will validate user input is correct
    while (validInput === -1) {
        alert("Invalid input, try again");
        selection = prompt("Enter 'Rock', 'Paper' or 'Scissors'").toLowerCase();
        validInput = array.includes(selection);
    }
    return selection;
}

// This function plays a single round of Rock-Paper-Scissors
const playRound = (playerSelection, computerPlay) => {

    // If both players select the same item
    if (playerSelection === computerPlay) {
        return alert("It's a tie!");
    }

    // If player selects "Rock"
    if (playerSelection === "rock") {
        if (computerPlay === "scissors") {
            playerWins += 1;
            return alert("Rock crushes scissors: YOU WIN!!!");
        } else {
            computerWins += 1;
            return alert("Paper covers rock: YOU LOOSE!!!");
        }
    }

    // If player selects "Paper"
    if (playerSelection === "paper") {
        if (computerPlay === "rock") {
            playerWins += 1;
            return alert("Paper covers rock: YOU WIN!!!");
        } else {
            computerWins += 1;
            return alert("Scissors cuts paper: YOU LOOSE!!!");
        }
    }

    // If player selects "Scissors"
    if (playerSelection === "scissors") {
        if (computerPlay === "rock") {
            computerWins += 1;
            return alert("Rock crushes scissors: YOU LOOSE!!!");
        } else {
            playerWins += 1;
            return alert("Scissors cuts paper: YOU WIN!!!");
        }
    }
}

// This function keeps score and reports a winner or loser at the end
const trackWins = (pw, cw) => {
    alert("COMPUTER WINS: " + cw + "\nPLAYER WINS: " + pw)
    if (pw > cw) {
        alert("YOU WIN THIS ROUND, CONGRAX!!!")
    } else if (cw > pw) {
        alert("YOU LOOSE THIS ROUND, SO BEST LUCK FOR THE NEXT TIME :_(")
    } else {
        alert("IT'S A TIE")
    }
}

// This function creates a 5 round game
const game = () => {   
    for (let i = 0; i < 5; i++) {
        playRound(playerSelection(), computerPlay());
    }
    trackWins(playerWins, computerWins);
}

do {
    game();
    newRound = prompt("Do yo want to play another round? Type 'y' to continue or any other key to exit").toLowerCase();
    
} while (newRound === "y");
alert("It was a good game, bye for now!")
&#13;
&#13;
&#13;

我将非常感谢您解决此问题或改进我的脚本的任何想法,请提前感谢您!

1 个答案:

答案 0 :(得分:0)

您发布的代码可以简化以更好地反映问题 - 例如,您有一个数组,以及一个存储用户输入的变量。如何测试输入值是否在数组中?

var arr=['Rock','Paper','Scissors'];
var inp='Rock'; //user input

你可以使用while循环,但有更快的方法:

var options={'rock':0,'paper':1,'scissors':2}
var inp='Rock'; //user input
var ninp=inp.toLowerCase().trim(); //normalize input

var pick=(options[ninp]);

if (pick==null) // invalid selection
if (pick==0) //rock
if (pick==1) //paper
if (pick==2) //scissors

可以使用开关进一步清理代码:

switch (pick){
  case 0: ... break; //rock
  case 1: ... break; //paper
  case 2: ... break; //scissors
  default: //invalid
}