I'm currently writing a Rock, Paper, Scissors game in Javascript, and for some reason, no matter what the player input is, I always get a "draw" result. I've been trying to figure it out for the last hour but no dice. Any help is really appreciated. I've put my code below.
let computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
let playerPrompt = prompt("Rock, paper, or scissors?")
let playerChoice = String(playerPrompt).toLowerCase
function playRound(playerChoice, computerChoice) {
if (playerChoice === computerChoice) {
return "Draw!"
} else if (playerChoice === "rock" && computerChoice === "scissors") {
return "Player wins!"
} else if (playerChoice === "paper" && computerChoice === "rock") {
return "Player wins!"
} else if (playerChoice === "scissors" && computerChoice === "paper") {
return "Player wins!"
} else {
return "Computer wins!"
}
}
let results = playRound()
console.log(results)```
If I'm not mistaken, you're not passing any arguments to playRound(), it should probably be:
let results = playRound(playerChoice, computerChoice)
Edit: As mentionned by Quentin (and Alon Eitan) it is not the only problem:
let playerChoice = String(playerPrompt).toLowerCase
actually assigns the function String.toLowerCase to playerChoice, if you want the lower case value of playerPrompt the syntax should be
let playerChoice = playerPrompt.toLowerCase()
or directly
let playerChoice = prompt("Rock, paper, or scissors?").toLowerCase()
The error is toLowerCase instead of toLowerCase(), you missed the parenthesis. Try running this snippet, it works
let computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
let playerPrompt = prompt("Rock, paper, or scissors?")
let playerChoice = String(playerPrompt).toLowerCase()
function playRound(playerChoice, computerChoice) {
if (playerChoice === computerChoice) {
return "Draw!"
} else if (playerChoice === "rock" && computerChoice === "scissors") {
return "Player wins!"
} else if (playerChoice === "paper" && computerChoice === "rock") {
return "Player wins!"
} else if (playerChoice === "scissors" && computerChoice === "paper") {
return "Player wins!"
} else {
return "Computer wins!"
}
}
let results = playRound(playerChoice, computerChoice)
console.log(results)
Related
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
}
}
I'm building a rock paper scissors game with Javascript, i did a 1 round mode of the game and it work, now i want to add a second mode " best of three rounds" but after trying many things i got my code messy and can't figure out what to do exactly.
i try to add a count = 0; count < 3; count = count + 1but don't know exactly where to put it
can someone help me please?
var mode = prompt("Please press 1 for single game mode or 2 for best out of 3 mode");
if (mode === '1') {
oneRound;
}
if (mode === '2') {
bestOfThree;
}
// 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";
}
// Compare value for oneRound mode
var oneRound = function(computerChoice, userChoice) {
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";
}
}
};
console.log("Player Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
console.log(oneRound(computerChoice, userChoice));
Have look at this
I use setTimeout to allow the screen to show the result
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();
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()
I'm doing the JavaScript project where you make a simple rock paper scissors game and I can't seem to figure out why my code only returns "player wins" even when player is supposed to lose. Here's the code:
var userChoice = prompt("Do you choose rock, paper or scissors?");
console.log("Player: " + userChoice)
var computerChoice = Math.random();
console.log(computerChoice)
if (computerChoice < 0.34) {
computerChoice = "rock"
} else if (computerChoice > 0.67) {
computerChoice = "paper"
} else {
computerChoice = "scissors"
}
console.log("Computer: " + computerChoice);
var compare = function(userChoice, computerChoice) {
var x = userChoice
var y = computerChoice
if (x === y) {
return "The result is a tie!"
}
if (x === "rock", y === "scissors") {
return "player wins"
} else if (x === "scissors", y === "paper") {
return "player wins"
} else if (x === "paper", y === "rock") {
return "player wins"
} else {
return "You lose"
}
}
compare(userChoice, computerChoice)
Also on a side note, why does the console on stackoverflow not show the return when the console on codeacademy does.
You should use the operator && and not a ,.
var compare = function(userChoice, computerChoice) {
var x = userChoice;
var y = computerChoice;
if (x === y) {
return "The result is a tie!";
}
if (x === "rock" && y === "scissors") {
return "player wins";
} else if (x === "scissors" && y === "paper") {
return "player wins";
} else if (x === "paper" && y === "rock") {
return "player wins";
} else {
return "You lose";
}
}
I guess you lost something, maybe you should change :
if (x === "rock", y === "scissors") {
to
if (x === "rock" && y === "scissors") {
Other conditional statements should do that like above.
Ok so this should be fairly easy to answer but for some reason im having an issue.( could be because im very new to programming) I've created a rock,papers,scissors game against the CPU. Now i want to ask the user if they want to play again and if they answer Y then it should go through the loop each time. If they type "N" then the game will end. The main issue im having is that once you type in Y to play again it just gives you the result from the last game. Any pointers would help.
Here is what i have :
var userChoice = "";
var userChoice = prompt("Choose rock, paper, or scissors");
var playagain = "Y";
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
choice1 = userChoice;
choice2 = computerChoice;
while (playagain == "Y") {
function compare(choice1, choice2) {
if (choice1 == choice2) {
return ("It's a tie!");
}
if (choice1 == "rock") {
if (choice2 == "scissors") {
return ("You win!");
} else {
return ("computer wins!");
}
}
if (choice1 == "paper") {
if (choice2 == "rock") {
return ("you win!");
} else {
return ("computer wins!");
}
}
if (choice1 == "scissors") {
if (choice2 == "rock") {
return ("computer wins!");
} else {
return ("you win!");
}
}
}
document.write(compare(choice1, choice2));
document.write("<br>");
playagain = prompt("Do you want to play again, Y or N");
userChoice = prompt("Choose rock, paper, or scissors");
}
The only thing you need is to move all game logics under the while loop:
function compare(choice1, choice2) {
if (choice1 == choice2) {
return ("It's a tie!");
}
if (choice1 == "rock") {
if (choice2 == "scissors") {
return ("You win!");
} else {
return ("computer wins!");
}
}
if (choice1 == "paper") {
if (choice2 == "rock") {
return ("you win!");
} else {
return ("computer wins!");
}
}
if (choice1 == "scissors") {
if (choice2 == "rock") {
return ("computer wins!");
} else {
return ("you win!");
}
}
}
}
var playagain = "Y";
while (playagain == "Y") {
var userChoice = prompt("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";
}
document.write(compare(userChoice, computerChoice));
document.write("<br>");
playagain = prompt("Do you want to play again, Y or N");
}
I have:
moved everything except the declaration of playagain into the loop
removed choice1 and choice2 local variables, as they are redundant
removed prompt in the end of the loop, since we have one in the beginning
removed the declaration of an empty userChoice in the beginning
by the advice of #LiYinKing, moved the function out of the loop
Here is the working JSFiddle demo.
Inside of the while loop you need to include your user prompt and new computer generated random number. The problem is your loop is calculating the same random number and user input over and over.
It's hard to explain exactly what's wrong because the code is difficult to follow.
I don't know how you expect the code that sets the computer's choice to run again after the code executes to the bottom of the script.
Declaring named functions in a loop doesn't make sense. Declare them at the top. Then there's nothing left in the body of the loop. Fishy...
What you need is a function that runs the game and a while loop calling that function.
I am on a phone, this is untested
function runGame() {
var userChoice = prompt("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";
}
if(userChoice==computerChoice){
return "It's a tie!";
}
if(userChoice=="rock"){
if(computerChoice=="scissors"){
return "You win!";
} else{
return "computer wins!";
}
}
if(userChoice=="paper"){
if(computerChoice=="rock"){
return "you win!";
} else{
return "computer wins!";
}
}
if(userChoice=="scissors"){
if(computerChoice=="rock"){
return "computer wins!" ;
} else{
return "you win!" ;
}
}
}
alert(runGame());
while ( prompt("Do you want to play again, Y or N") == "Y") {
alert(runGame());
}
Later with experience and knowledge you can write the script like this :
function compare(choice1, choice2) {
if (choice1 == choice2) {
return ("It's a tie!");
}
var lose = {
"rock": "scissors",
"paper": "rock",
"scissors": "paper"
};
return (lose[choice1] == choice2) ? "You win!" : "computer wins!";
}
(function() {
var CHOICE = ["rock", "paper", "scissors"];
var userChoice = "";
var userChoice, computerChoice, playagain, i = 0;
do {
document.write("Ground " + i + " :<br>");
computerChoice = CHOICE[Math.floor(Math.random() * 3)];
do {
userChoice = (""+prompt("Choose rock, paper, or scissors")).toLowerCase();
} while (CHOICE.indexOf(userChoice) === -1);
document.write(userChoice + " vs " + computerChoice + "<br>");
document.write(compare(userChoice, computerChoice) + "<br>");
playagain = (""+prompt("Do you want to play again, Y or N")).toUpperCase();
i++;
} while (["Y", "YES"].indexOf(playagain) !== -1);
});
Explanation :
I add toLowerCase() function to replace "Rock" to "rock", and I add toUpperCase() to replace "y" to "Y".
In this circumstance do { /* script */ } while (bool) is more suitable.
With :
do {
userChoice = (""+prompt("Choose rock, paper, or scissors")).toLowerCase();
} while (CHOICE.indexOf(userChoice) === -1);
You wait a valid answer, three word only : rock or paper or scissors. When userChoice equals "rock" indexOf return 0 ; equals "paper" indexOf return 1...
This syntax :
return (lose[choice1] == choice2) ? "You win!" : "computer wins!";
Is :
if (lose[choice1] == choice2)
return "You win!";
else
return "computer wins!"
JavaScript ternary operator example with functions
I want the code to grab the value that the user has entered in the input field and pass it to a variable userChoice. I have no idea why this code isn't working and the only way to learn is to ask you guys.
HTML:
<h3> Choose your destiny !</h3>
<form>
<input type="text" id="form" />
<input type="button" id="button" value="Click Me!" onclick="clickMe();" />
</form>
JavaScript:
var computerChoice = Math.random();
var userChoice = "";
function clickMe() {
document.getElementById("form").value === userChoice;
}
if (computerChoice < 0.33) {
computerChoice = "rock";
};
if (computerChoice < 0.66) {
computerChoice = "paper";
};
if (computerChoice < 1) {
computerChoice = "scissors";
};
if (userChoice === "rock" && computerChoice === "rock") {
alert("It's a tie!");
} else if (userChoice === "rock" && computerChoice === "paper") {
alert("Computer Wins!");
} else if (userChoice === "rock" && computerChoice === "scissors") {
alert("You WIN!");
};
if (userChoice === "paper" && computerChoice === "rock") {
alert("You WIN!");
} else if (userChoice === "paper" && computerChoice === "paper") {
alert("It's a TIE!");
} else if (userChoice === "paper" && computerChoice === "scissors") {
alert("Computer Wins!");
};
if (userChoice === "scissors" && computerChoice === "rock") {
alert("Computer Wins!");
} else if (userChoice === "scissors" && computerChoice === "paper") {
alert("You WIN!");
} else if (userChoice === "scissors" && computerChoice === "scissors") {
alert("It's a TIE!");
};
Fiddle
Your function clickMe doesn't work like you'd expect I guess:
function clickMe() {
userChoice = document.getElementById("form").value;
// ... rest of your code goes inside clickMe
}
To assign a value to a variable you need a single =
Here is the simple way
<div id="Result"></div>
<div id="sellection">
Rock
Paper
Scissors
</div>
and the script is:
function result(users){
var choices = ["Rock","Paper","Scissors"];
var succesResult = "You Loose :(";
var machines = Math.floor((Math.random() * 3));
var dif = users-machines;
if(dif>0&&dif!=2||dif==-2){
succesResult = "You Win :)";
}else if(dif==0){
succesResult = "You Draw";
}
var resultText = "You Selected "+choices[users]+", Computer Selected "+choices[machines]+" and "+succesResult;
document.getElementById("Result").innerHTML = resultText;
}