Skip to content Skip to sidebar Skip to footer

How Can I Prevent Console From Printing In Javascript Game?

I've been practicing a game with JavaScript, and was wondering how to prevent the console from printing when a user makes an ill defined choice? Here is the code: var user = prom

Solution 1:

One option would be to keep asking the user for a valid input until a valid input is given:

while (user != "rock" && user != "paper" && user != "scissors") {
    user = prompt("Do you choose rock, paper or scissors?")
    if (user == null) {
        break;
    }
};

if (user != null) {
...
}

http://jsfiddle.net/2w3pt5yy/3/

Solution 2:

make the validation of user input at the beginning . if user passes only show the code else show error.

var user = prompt("Do you choose rock, paper or scissors?");
if(user !== "rock" && user !== "paper" && user!== "scissors") { 
    confirm(user + " is an invalid entry."); 
} else {
    // code for process
}

Solution 3:

Solution 4:

You have more if statements than is necessary; you can simplify the logic.

var getComputerMove = function () {
    // equivalent of Math.floor// aka it grabs the integer component of `Math.random() * 3`// either 0, 1, or 2return (Math.random() * 3) | 0;
}

var playRockPaperScissors = function () {
    var moves = [ "rock", "paper", "scissors" ]
      , user = ""
      , computer = getComputerMove();

    // while `user` is not in the `moves` array// `Array.indexOf` returns -1 if an element is not in the array// prompt the user for his movewhile (moves.indexOf(user.toLowerCase()) == -1) {
        user = prompt("Rock, paper, or scissors?");
    }

    // this is where you can save yourself all that typing and think out// the possible movesets:// item:    rock < paper < scissors < rock// index:   0    < 1     < 2        < 0// so, the computer wins if its choice is greater than the user's,// or if the computer chose "rock" and the user chose scissors// we can translate this to// user < computer || (computer == 0 && user == 2)var userIndex = moves.indexOf(user.toLowerCase());

    // uncomment, if you want to see the moves// console.log("user:", user, "computer:", moves[computer]);if (userIndex < computer || (userIndex == 2 && computer == 0) {
        alert("Computer wins!");
    } else {
        alert("User wins!");
    }
}

Post a Comment for "How Can I Prevent Console From Printing In Javascript Game?"