I need a bit of help with a basic JavaScript version of Rock-Paper-Scissors I'm working on. I just started learning today and would like to keep the code as intact as possible, if possible.
The main problem I'm having is with the loop. It continues despite me setting 'again' to 'no' (through the prompt). Also, the computer always seems to choose Rock... I have a feeling that I'm just missing something simple:
<html>
<script type="text/javascript">
var myChoice = "";
var compChoice = "";
var again;
while (again = "yes")
{
myChoice = prompt("Do you choose rock, paper or scissors?");
compChoice = Math.random();
if (compChoice < 0.33)
{
compChoice = "rock";
}
else if(compChoice < 0.67)
{
compChoice = "paper";
}
else
{
compChoice = "scissors";
}
if (compChoice = myChoice)
{
alert("It's a tie!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (compChoice = "rock")
{
if(myChoice = "scissors")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "paper")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
}
else if (compChoice = "paper")
{
if (myChoice = "rock")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "scissors")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
}
else if (compChoice = "scissors")
{
if (myChoice = "rock")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "paper")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
}
};
</script>
</html>
You are using = instead of == in the while statement and same in all the if statements also
= is the assignment operator, while == is the comparison operator
var myChoice = "";
var compChoice = "";
var again;
do
{
myChoice = prompt("Do you choose rock, paper or scissors?");
compChoice = Math.random();
if (compChoice < 0.33)
{
compChoice == "rock";
}
else if(compChoice < 0.67)
{
compChoice = "paper";
}
else
{
compChoice == "scissors";
}
if (compChoice == myChoice)
{
alert("It's a tie!");
}
else if (compChoice == "rock")
{
if(myChoice == "scissors")
{
alert("You lose!");
}
else if (myChoice == "paper")
{
alert("You win!");
}
}
else if (compChoice == "paper")
{
if (myChoice == "rock")
{
alert("You lose!");
}
else if (myChoice == "scissors")
{
alert("You win!");
}
}
else if (compChoice == "scissors")
{
if (myChoice == "rock")
{
alert("You win!");
}
else if (myChoice == "paper")
{
alert("You lose!");
}
}
again = prompt("Would you like to play again?(yes/no)");
}while (again == "yes");
Demo: Fiddle
One major issue is that you are assigning values instead of comparing values in multiple places.
a = 2 // assigns a to value 2, and evaluates to true
a == 2 // compares a to 2, only evaluates to true if a has value 2
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 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.
Everything works fine but when i try to re run the function it is stuck on the alert box what did i do wrong and can anyone explain why its happening.You can look at the comment in the code to see the area im getting this probem
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("Computer: " + computerChoice);
var compare = function(choice1,choice2){
if (choice1 === choice2){
return "The result is a tie!";
}else if (choice1 === "rock"){
if(choice2 === "scissors"){
return("rock wins");
}else{
return("paper wins");
}
}else if (choice1 === "paper"){
if(choice2 === "rock"){
return("paper wins");
}else{
return("scissors wins");
}
}else if(choice1 === "scissors"){
if(choice2 === "rock"){
return("rock wins");
}else{
return("scissors wins");
}
}else if (choice1 != "rock"&&"paper"&&"scissors"){
alert("not a viable input,please try again");
compare(userChoice,computerChoice);
//calling the function here makes the alert box repeatedly pop up
}
};
compare(userChoice,computerChoice);
You can set a flag and put everything in a while loop.
var finished = false;
var compare = function (choice1, choice2) {
if (choice1 === choice2) {
finished = true;
return "The result is a tie!";
} else if (choice1 === "rock") {
if (choice2 === "scissors") {
finished = true;
return ("rock wins");
} else {
finished = true;
return ("paper wins");
}
} else if (choice1 === "paper") {
if (choice2 === "rock") {
finished = true;
return ("paper wins");
} else {
finished = true;
return ("scissors wins");
}
} else if (choice1 === "scissors") {
if (choice2 === "rock") {
finished = true;
return ("rock wins");
} else {
finished = true;
return ("scissors wins");
}
} else if (choice1 != "rock" && "paper" && "scissors") {
alert("not a viable input,please try again");
finished = false;
//compare(userChoice, computerChoice); This causes recursion. Not necessary.
}
};
while (!finished) {
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("Computer: " + computerChoice);
alert(compare(userChoice, computerChoice));
}
Take a look at this fiddle http://jsfiddle.net/7p94axhp/
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;
}