How can I prevent console from printing in JavaScript game? - javascript

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 = prompt("Do you choose rock, paper or scissors?");
var computer = Math.random();
if (computer < 0.34) {
computer = "rock";
}
else if (computer <= 0.67) {
computer = "paper";
}
else {
computer = "scissors";
}
console.log("Computer Chooses: " + computer);
console.log("User Chooses: " + user);
var compare = function (computer, user) {
if (computer === "rock") {
if (user === "scissors") {
return "Computer wins by choosing rock!";
}
}
else if (computer === "scissors") {
if (user === "paper") {
return "Computer wins by choosing scissors!";
}
}
else if (computer === "paper") {
if (user === "rock") {
return "Computer wins by choosing paper!"
}
}
if (computer === user) {
return ("It is a tie!")
}
else if (user === "paper") {
if (computer === "rock") {
return ("You win by choosing paper!")
}
}
else if (user === "rock") {
if (computer === "scissors") {
return ("You win by choosing scissors!")
}
}
else if (user === "scissors") {
if (computer === "paper") {
return ("You win by choosing scissors!")
}
}
***if (user !== "rock" && user !== "paper" && user !== "scissors") {
confirm(user + " is an invalid entry.");
}***
};
compare(computer, user);
At the end I snipped the bit of code that gives the user an indication that he has put in the wrong characters. What I am wondering is:
How do I keep anything from displaying to the console once someone has put in the wrong input?

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/

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
}

You can add this code on top of your js code
var console = {};
console.log = function(){};

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 2
return (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 move
while (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!");
}
}

Related

Javascript output in alert is different in console, and counter is not working properly even when condition is met

I'm making a rock paper scissors games where the counter should add 1 if user wins, add 0.5 if it's a tie, and remains the same if user lost. But in the alert and what's shown in the console doesn't match. Sometimes its shown in the alert that I win and in the console its shown I lose or its a tie. And the counter doesn't add up correctly.
In the image above it's shown 3 wins, 1 tie, and 1 lose. It should show I've won 3.5 games but it shows 5.5. And there is only 5 games played so it should be impossible to win 5.5.
Here is the code:
let winCounter = 0;
// playRound function will play a game of rock, paper, scissors and returns the result
function playRound(playerSelection, computerSelection) {
let getPlayerInsensitive = playerSelection.toLowerCase();
if (getPlayerInsensitive === "rock" && computerSelection === "Rock") {
winCounter+=0.5;
return "It's a tie, both are Rock";
} else if (getPlayerInsensitive === "rock" && computerSelection === "Paper") {
winCounter = winCounter;
return "You Lose! Paper beats Rock";
} else if (getPlayerInsensitive === "rock" && computerSelection === "Scissors") {
winCounter+=1;
return "You win! Rock beats Scissors";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Rock") {
winCounter+=1;
return "You win! Paper beats Rock";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Paper") {
winCounter+=0.5;
return "It's a tie! Both are Paper";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Scissors") {
winCounter = winCounter;
return "You lose! Scissors beats Paper";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Rock") {
winCounter = winCounter;
return "You lose! Rock beats Scissors";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Scissors") {
winCounter=0.5;
return "It's a tie! Both are Scissors";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Paper") {
winCounter+=1;
return "You win! Scissors beat Paper";
} else {
return "Check your spelling!";
}
}
// game function returns the winner after five rounds
function game() {
for (let i = 0; i < 5; i++) {
let getSelect = prompt("Choose Rock, Paper, or Scissors", "");
if (getSelect === null || getSelect === "") {
alert("You clicked Cancel!");
}
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
//outputs the winner of 5 games
if (i === 4) {
alert("You've played 5 games");
if (winCounter >= 3) {
alert(`You've won ${winCounter} out of 5 games. You win!`);
return `You've won ${winCounter} out of 5 games. You win!`;
} else if (winCounter === 2.5) {
alert(`You've won 2.5 out of 5 games. It's a tie!`);
return `You've won 2.5 out of 5 games. It's a tie!`;
} else if (winCounter < 2.5) {
alert(`You've won ${winCounter} out of 5 games. You lost!`);
return `You've won ${winCounter} out of 5 games. You lost!`;
}
}
}
}
console.log(game());
And here is the fiddle: https://jsfiddle.net/JaredDev/o62hr7as/125/
Why does it show different results in alert and console.log
It's because you called the computerPlay function twice, thus could returns different selection each time it is called,
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
you could change it to this, so it is called only once
const result = playRound(getSelect, computerPlay())
alert(result);
if (i < 5) {
console.log(result)
}
also why the score could be more than it should have, its because playRound function also called twice each turn
Caling code with random behaviour and side-effects twice
This piece of code produces an unintended result because the function computerPlay has random behaviour and the function playRound has has side-effects (modifies the winCounter).
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
You could correct this part of the problem by calling the function only once and assigning its result to a variable:
const result = playRound(getSelect, computerPlay());
alert(result);
if (i < 5) {
console.log(result);
}
Typo
You also have a typo:
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Scissors") {
winCounter=0.5;
return "It's a tie! Both are Scissors";
This should say += not just =:
winCounter+=0.5;

Javascipt Rock Paper Scissors game, single mode or best out of three

I'm new to coding and javascript. I'm working on an assignment where I have to create a Rock Paper Scissors game that has 2 modes, single player and best out of three. In the best out of three mode, you need to create a system to remember the score of the user and the bot. And it needs a loop to run as many rounds as possible until there is a player that wins at least two rounds. Once the game ends, you can ask the human player if he/she wants to play again using a confirm() function. I have the base game but I cant figure out how to have the game loop until one player wins 2 rounds. I also cant figure out how to add a play again option. If someone can please help I would greatly appreciate it.
const play = () => {
// set Computer Choice
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log("Player Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
if (computerChoice === userChoice) {
return "The result is tie!";
}
if (computerChoice === "rock") {
if (userChoice === "scissors") {
return "Computer wins";
} else {
if (userChoice === "paper")
return "Player wins";
}
}
if (computerChoice === "paper") {
if (userChoice === "scissors") {
return "Computer wins";
} else {
if (userChoice === "rock")
return "Player wins";
}
}
if (computerChoice === "scissors") {
if (userChoice === "rock") {
return "Computer wins";
} else {
if (userChoice === "scissors")
return "Player wins";
}
}
};
const round = () => {
const res = play();
let playerScore = 0;
let computerScore = 0;
console.log(res)
cnt--
wins[cnt] = res.startsWith("Player") ? 1 : 0;
if (cnt === 0) {
const total = wins.reduce((a, b) => a + b)
console.log(`You beat the computer ${total} time${total===1?"":"s"}`)
return
}
setTimeout(round, 10) // else go again
}
let cnt = 1,
wins = [];
const mode = prompt("Please press 1 for single game mode or 2 for best out of 3 mode");
if (mode === '2') {
cnt = 3;
round()
}
You can pass a parameter to the round() function to tell it how many wins are needed. Then, put the main code in a loop:
const round = (winsNeeded) => {
let playerScore = 0;
let computerScore = 0;
while (playerScore < winsNeeded && computerScore < winsNeeded) {
const res = play();
console.log(res)
if (res[0] == 'P') playerScore++;
else if (res[0] == 'C') computerScore++;
console.log(`Score: you ${playerScore}, computer ${computerScore}`);
}
if (playerScore == winsNeeded) {
console.log("Player won that round.");
}
else {
console.log("Computer won that round.");
}
}
while (true) {
let cnt = 1;
const mode = prompt("Please press 1 for single game mode or 2 for best out of 3 mode");
if (mode === '2') cnt = 2;
round(cnt);
const choice = prompt("Play again?");
if (choice[0].toLowerCase() != 'y') break;
}
For every 2 round you can check for the current status of the game. Also made some changes on the play logic
const play = () => {
// set Computer Choice
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log("Player Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
if (computerChoice === userChoice) {
return "The result is tie!";
}
//little change in logic here----
if (computerChoice === "rock") {
if (userChoice === "scissors") {
return "Computer wins";
} else {
if (userChoice === "paper")
return "Player wins";
}
}
if (computerChoice === "paper") {
if (userChoice === "rock") {
return "Computer wins";
} else {
if (userChoice === "scissors")
return "Player wins";
}
}
if (computerChoice === "scissors") {
if (userChoice === "paper") {
return "Computer wins";
} else {
if (userChoice === "rock")
return "Player wins";
}
}
};
const round = () => {
const res = play();
let playerScore = 0;
let computerScore = 0;
console.log(res)
cnt--
wins[cnt] = res.startsWith("Player") ? 1 :res.includes("tie") ?-1:0;
console.log(wins)
if (cnt === 0) {
const total = wins.filter((a) => a==1)
console.log(`You beat the computer ${total.length} time${total.length===1?"":"s"}`)
playAgain()
}else if(cnt == 1){ // Check for every round
var el2 = wins[2];
var el1 = wins[1];
if(el2 == el1 && el1!=-1){
const total = wins.filter((a) => a==1)
console.log(`You beat the computer ${total.length} time${total.length===1?"":"s"}`)
playAgain()
}
}
if(pa){
setTimeout(round, 10) // else go again
}else{
prompt("Thank you for playing")
}
}
let pa = true;
let cnt = 1,
wins = [];
const mode = prompt("Please press 1 for single game mode or 2 for best out of 3 mode");
if (mode === '2')
cnt = 3;
round()
function playAgain(){
if(confirm('Do you want to play again ?')){
pa = true
cnt = 1
wins = [];
const mode = prompt("Please press 1 for single game mode or 2 for best out of 3 mode");
if (mode === '2')
cnt = 3;
round()
}else{
pa=false
}
}

rock, paper, scissor app using javascript, can't display correctly

i'm learning javascript and currently making a rock, paper, scissor game using only javascript. the game will have 1 round mode and 3 rounds mode but as i finished to code the 1 round mode i found out having problem display result, whoever win the game it display "the game is tie" and can't find where s the mistake, can anybody help me?
// Player choice
var getPlayerChoice = function() {
var playerChoice = prompt("Choose rock, paper, or scissors");
while (playerChoice !== 'rock' && playerChoice !== 'paper' && playerChoice !== 'scissors') {
if (playerChoice === null) {
break;
}
playerChoice = prompt("Invalid ! you have to choose rock, paper, or scissors");
}
return playerChoice;
}
// Computer Choice
var getComputerChoice = function () {
var randomNum = Math.random();
if ( randomNum < 0.3333 ) {
return "rock";
} else if ( randomNum > 0.3333 && randomNum < 0.6666 ) {
return "scissors";
} else {
return "paper";
}
}
// Winner Function
var getWinner = function (playerChoice, computerChoice) {
if (computerChoice === playerChoice) {
return "The Game is Tie";
} else if (computerChoice === "paper") {
if (playerChoice === "scissors") {
return "player win";
} else if (playerChoice === "rock") {
return "computer win";
}
} else if (computerChoice === "rock") {
if (playerChoice === "scissors") {
return "computer win";
} else if (playerChoice === "paper") {
return "player win";
}
} else if (computerChoice === "scissors") {
if (playerChoice === "rock") {
return "player win";
} else if (playerChoice === "paper") {
return "computer win";
}
}
}
// Single game mode
var singleRound = function() {
var playerChoice = getPlayerChoice();
if (playerChoice === null) {
return;
}
var computerChoice = getComputerChoice();
var winner = getWinner(playerChoice, computerChoice);
var message = " You chose: " + playerChoice + "\n Computer chose: " + computerChoice;
if (winner === "player") {
alert(message + "\nYou won!");
} else if (winner === "computer") {
alert(message + "\nYou lost!");
} else {
alert(message + "\nThe Game is Tie");
}
return winner;
}
var mode = prompt("Welcome!\n \nplease insert 1 for single round mode\n2 for 3 rounds mode");
if (mode === '1') {
singleRound();
} else if (mode === '2') {
threeRoundsMode();
}
Your getWinner() function returns player win or computer win, but your code that calls it is looking for return values of player or computer.
Because the code never gets what it's looking for it defaults to `'The Game is Tie'
This is happening because of a mistake in the singleRound() function. if (winner === "player") { should be if (winner === "player win") { and similarly the if (winner === "computer") { should say if (winner === "computer win") { so that the text being compared matches. Right now, it is comparing "player" and "player win", then "computer" and "computer win" so then the else clause is reached regardless of actual game outcome.

prompt keep popping up even though I write the write answer

I have a question why this is happening, I want when the user doesn't type one of the values
the prompt keeps popping up until the user type one, what is happening here is that it keep popping up even tho I'm typing one of the possibilities.
const player = document.querySelector(".player");
const computer = document.querySelector(".computer");
const button = document.querySelector("button");
let choose;
button.addEventListener("click", (e) => {
e.preventDefault();
choose = prompt(`Please choose between Rock, paper, scissors`).toUpperCase();
if (choose === "ROCK") {
console.log("ROCK");
} else if (choose === "PAPER") {
console.log("PAPER");
} else if (choose === "SCISSORS") {
console.log("SCISSORS");
} else {
while (choose !== "ROCK" || choose !== "PAPER" || choose !== "SCISSORS") {
choose = prompt(
`Please choose between Rock, paper, scissors`
).toUpperCase();
}
}
});
Thanks in advance guys!
I think you mean to say:
while (choose !== "ROCK" && choose !== "PAPER" && choose !== "SCISSORS") {
...
}
As choose will always not equal at least 2 of them.
EDIT: You could simplify your code to:
const player = document.querySelector(".player");
const computer = document.querySelector(".computer");
const button = document.querySelector("button");
button.addEventListener("click", (e) => {
e.preventDefault();
let choose;
while (choose !== "ROCK" && choose !== "PAPER" && choose !== "SCISSORS") {
choose = prompt(`Please choose between Rock, paper, scissors`).toUpperCase();
}
if (choose === "ROCK") {
console.log("ROCK");
} else if (choose === "PAPER") {
console.log("PAPER");
} else if (choose === "SCISSORS") {
console.log("SCISSORS");
}
});
It would be better if you can contain the prompt within one while loop
button.addEventListener("click", (e) => {
e.preventDefault();
let choose;
do {
choose = prompt(`Please choose between Rock, paper, scissors`).toUpperCase();
} while (!["ROCK","PAPER","SCISSORS"].includes(choose));
console.log(choose); // one of ROCK, PAPER, SCISSORS
});

My Rock Paper Scissors program in jQuery is only returning the result when it is a tie [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Here is the link to the pen on CodePen where I made this: http://codepen.io/PartTimeCoder/pen/KzQQvM?editors=0010
My Javascript, the problem must be in the if commands at the bottom of the $("img").click() function:
$("img").click(function() {
var user;
user = this.id;
var computer = Math.random();
if (computer <= 0.33) {
computer = "Rock"
} else if (computer <= 0.67) {
computer = "Scissors"
} else {
computer = "Paper"
}
$(".cpu").html("The computer chose - " + computer);
$(".you").html("You chose - " + user);
$(".result").html("");
if (computer == user) {
$(".result").html("It's a tie!");
}
if (user == "paper") {
if (computer == "rock") {
$(".result").html("You win!");
} else {
$(".result").html("You lose!");
}
}
if (user == "rock") {
if (computer == "scissors") {
$(".result").html("You win!");
} else {
$(".result").html("You lose!");
}
}
if (user == "scissors") {
if (computer == "paper") {
$(".result").html("You win!");
} else {
$(".result").html("You lose!");
}
}
});
Your id's are in caps case, but you are trying to match lower case. Change either the code or the markup.
For example, the id for rock is Rock, but your logic tries to match user == 'rock'. If you changed the id to rock, your code should work. You'll need to repeat this for each id ie rock, paper and scissors.
The strings are case-sensitive. "Scissors" != "scissors".
Here it is again with correction and also a simpler IF()
$("img").click(function() {
var user;
user = this.id;
var computer = Math.random();
if (computer <= 1/3) {
computer = "Rock"
} else if (computer <= 2/3) {
computer = "Scissors"
} else {
computer = "Paper"
}
$(".cpu").html("The computer chose - " + computer);
$(".you").html("You chose - " + user);
var result = '';
if (computer == user) {
result = "It's a tie!";
} else if (user == "Paper" && computer == "Rock") {
result = "You win!";
} else if (user == "Rock" && computer == "Scissors") {
result = "You win!";
} else if (user == "Scissors" && computer == "Paper") {
result = "You win!";
} else {
result = "You lose!";
}
$(".result").html(result);
});

Categories