How can I fix this rock, paper, scissor game in JavaScript? - javascript

The first function getComputerChoice() returns a random - rock, paper, or scissor. However, in the playRound function when the computer' choice and user's choice are compared, it shows incorrect answers for a few of them. For example, when I choose rock and computer chooses paper, I win, which is wrong.
I tried using if else and switch statements but faced the same problem. It would be great if someone could help me out.
let computerSelection = getComputerChoice();
let playerSelection = prompt("rock, paper, or scissor?").toLowerCase();
function getComputerChoice(){
const randomNumber = Math.floor(Math.random()*3);
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissor";
} return choice;
}
function playRound(playerSelection, computerSelection){
let result = '';
if(computerSelection === playerSelection){
result = "It's a tie";
} else if(computerSelection === 'paper' && playerSelection === 'rock'){
result = "you lose";
} else if(computerSelection === 'scissor' && playerSelection === 'rock'){
result = "you win";
} else if ((computerSelection === 'rock') && (playerSelection === 'paper')){
result = "You win";
} else if((computerSelection === 'scissor') && (playerSelection === 'paper')){
result = "you lose";
} else if ((computerSelection === 'paper') && (playerSelection === 'scissor') ){
result = "You win";
} else if((computerSelection === 'rock') && (playerSelection === 'scissor')){
result = "You lose";
}
return result;
};
alert("The computer chose: " + getComputerChoice());
alert("That means " + playRound(playerSelection, computerSelection));

In your first statement, you choose the computer selection. But in your second to last statement, you call getComputerChoice() which makes a DIFFERENT selection. Change the next to the last line to
alert("The computer chose: " + computerSelection);

Try adding this debug line that I have put in, and then look at the console in the browser. You will see what the computer really chose
function getComputerChoice(){
const randomNumber = Math.floor(Math.random()*3);
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissor";
}
// debug line
console.log('randomly chose', choice);
return choice;
}

ChatGPT?
This code will run but it has a couple of problems:
In the getComputerChoice function, the variable choice is declared without const, let, or var. This means that it's a global variable and could cause issues in the future.
The line alert("The computer chose: " + getComputerChoice()); is calling the getComputerChoice function twice, but it should only be called once and stored in the computerSelection variable.
The result of the playRound function is not being logged to the console or displayed in any other way, it's only being returned.
To resolve these problems, you could modify the code as follows:
let computerSelection = getComputerChoice();
let playerSelection = prompt("rock, paper, or scissor?").toLowerCase();
function getComputerChoice(){
let choice = '';
const randomNumber = Math.floor(Math.random() * 3);
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissor";
}
return choice;
}
function playRound(playerSelection, computerSelection){
let result = '';
if(computerSelection === playerSelection){
result = "It's a tie";
} else if(computerSelection === 'paper' && playerSelection === 'rock'){
result = "you lose";
} else if(computerSelection === 'scissor' && playerSelection === 'rock'){
result = "you win";
} else if ((computerSelection === 'rock') && (playerSelection === 'paper')){
result = "You win";
} else if((computerSelection === 'scissor') && (playerSelection === 'paper')){
result = "you lose";
} else if ((computerSelection === 'paper') && (playerSelection === 'scissor') ){
result = "You win";
} else if((computerSelection === 'rock') && (playerSelection === 'scissor')){
result = "You lose";
}
return result;
};
console.log("The computer chose: " + computerSelection);
console.log("That means " + playRound(playerSelection, computerSelection));

Your Code is not consistent : here is the answer:
let computerSelection = getComputerChoice();
let playerSelection = prompt("rock, paper, or scissor?").toLowerCase();
function getComputerChoice(){
const randomNumber = Math.floor(Math.random() * 3);
let choice;
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissors";
}
return choice;
}
function playRound(playerSelection, computerSelection){
let result = '';
if(computerSelection === playerSelection){
result = "It's a tie";
} else if(computerSelection === 'paper' && playerSelection === 'rock'){
result = "You lose";
} else if(computerSelection === 'scissors' && playerSelection === 'rock'){
result = "You win";
} else if ((computerSelection === 'rock') && (playerSelection === 'paper')){
result = "You win";
} else if((computerSelection === 'scissors') && (playerSelection === 'paper')){
result = "You lose";
} else if ((computerSelection === 'paper') && (playerSelection === 'scissors') ){
result = "You lose";
} else if((computerSelection === 'rock') && (playerSelection === 'scissors')){
result = "You win";
}
return result;
};
let result = playRound(playerSelection, computerSelection);
alert("The computer chose: " + computerSelection);
alert("That means " + result);
Note:
scissor has been corrected to scissors.
Consistent use of capitalization for "You win" and "You lose".
The result ofplayRound() function has been stored in a variable
result before using it in the alert
.

Related

stuck on the if on Rock, paper, scissors

I am new to coding I have to do this rock paper scissors but can't find my error it still show me the else result each time.
Any help are welcome
// Get the computer choice
function getComputerChoice() {
"use strict";
const computerPlay = Math.floor(Math.random()*3);
if (computerPlay === 1){
return("rock")
}
else if(computerPlay === 2){
return ("paper")
}
else {
return ("scissors")
}
}
// Get the user choice
function getUserChoice(){
prompt("Please enter 'rock', 'paper', 'scissors': ").toLowerCase();
}
// Play a round
function playRound(){
let computerSelection = getComputerChoice();
let playerSelection = getUserChoice();
if (computerSelection === playerSelection){
console.log("Game is a Tie")
}
else if (computerSelection == 'paper' && playerSelection == 'rock'){
console.log("Computer Win")
}
else if (computerSelection == 'rock' && playerSelection == 'scissors'){
console.log("Computer Win")
}
else if (computerSelection == 'scissors' && playerSelection == 'paper'){
console.log("Computer Win")
}
else {
console.log("User Win")
}
}
// Play Game function
function playGame(){
for (let i = 0; i < 5; i++){
playRound()
}
}
playGame()
I try the if seems it miss something to run correctly.
Solution
You've missed the return keyword from the getUserChoice method.
function getUserChoice(){
return prompt("Please enter 'rock', 'paper', 'scissors': ").toLowerCase();
}

Last "if" in "If else" function not working // Error "unreachable code detected ts(7027)"

const playerText = document.querySelector("#playerText");
const computerText = document.querySelector("#computerText");
const resultText = document.querySelector("#resultText");
const choiceBtns = document.querySelectorAll(".choiceBtn");
let player;
let computer;
let playerScore = 0;
let computerScore = 0;
let ifresult = "";
choiceBtns.forEach(button => button.addEventListener("click", () => {
player = button.textContent;
computerSelection();
playerText.textContent = "Player: " + player;
computerText.textContent = "Computer: " + computer;
resultText.textContent = "Result: " + result();
}));
function computerSelection(){
const randNum = Math.floor(Math.random() * 3) + 1;
switch(randNum){
case 1:
computer = "rock";
break;
case 2:
computer = "paper";
break;
case 3:
computer = "scissors";
break;
}
}
function result() {
if ((player === "paper" && computer === "rock") ||
(player === "scissors" && computer === "paper") ||
(player === "rock" && computer === "scissors")) {
playerScore += 1;
return ("You win! ");
}
if (playerScore == 2) {
return ("Winner winner chicken dinner! You won the game!");
}
else if (player == computer) {
return ("Draw!");
}
else {
computerScore += 1;
display ("you lose");
if (computerScore == 5) {
return ("You lost the game. ");
}
}
}
Everything in this function works except this final if statement in the else bracket.
if (computerScore == 5) {
return ("You lost the game. ");
I am getting the error,
"unreachable code detected ts(7027)".
If I delete the "return ("You lose!");" how would i display i lost the game? The second return "return ("You lost the game.");" returns that statement if i lose 5 times. Thanks for the help
In your final else statement, you're returning a value before the if condition is run.
return ("You lose!");
if (computerScore == 5) { // this code is unreachable
You need to remove this return.
} else {
computerScore += 1;
if (computerScore == 5) {
return ("You lost the game.");
}
}
Avoid such mistakes by adding a good extension into your VS Code. Image below demonstrates how my plugin detected the mistake. I am using Tabnine.
2. Be careful when returning values to close the if statement and then start new one.
3. There are some logic issues that makes this function a bit hard to read and unscalable.
4. Using your params I have cleaned and fixed it. I think your level of programming will fit into this solution. Since you are learning then it's OK to write longer code and with time your skill will come.
5. You can test this game, change the function values under the script.
// DEFINE VARIABLES
let player = undefined
let computer = undefined
let playerScore = 0
let computerScore = 0
let returnText = undefined
const theGame = (player, computer) => {
// PLAYER HAS PAPER
if (player === 'paper' && computer === 'rock') {
playerScore++
returnText = 'You win!'
checkScore(playerScore, computerScore)
return returnText
} else if (player === 'paper' && computer === 'paper') {
returnText = 'Draw!'
return returnText
} else if (player === 'paper' && computer === 'scissors') {
computerScore++
returnText = 'You lose!'
checkScore(playerScore, computerScore)
return returnText
}
// PLAYER HAS ROCK
if (player === 'rock' && computer === 'rock') {
returnText = 'Draw!'
return returnText
} else if (player === 'rock' && computer === 'paper') {
computerScore++
returnText = 'You lose!'
checkScore(playerScore, computerScore)
return returnText
} else if (player === 'rock' && computer === 'scissors') {
playerScore++
returnText = 'You win!'
checkScore(playerScore, computerScore)
return returnText
}
// PLAYER HAS SCISSORS
if (player === 'scissors' && computer === 'rock') {
computerScore++
returnText = 'You lose!'
checkScore(playerScore, computerScore)
return returnText
} else if (player === 'scissors' && computer === 'paper') {
playerScore++
returnText = 'You win!'
checkScore(playerScore, computerScore)
return returnText
} else if (player === 'scissors' && computer === 'scissors') {
returnText = 'Draw!'
return returnText
}
}
// CHECK SCRORE FUNCTION
const checkScore = (playerScore, computerScore) => {
let winningScore = 3
let result = undefined
if (playerScore === winningScore) {
result = 'Winner winner chicken dinner! You won the game!'
} else if (computerScore === winningScore) {
result = 'Winner winner chicken dinner! You won the game!'
} else {
// For testing
console.log('Player score: ', playerScore, 'Computer score: ', computerScore)
return playerScore, computerScore
}
// For testing
console.log(result)
return result
}
// TESTING
theGame('paper', 'rock')
Everything you put after a return statement will not be executed.
If the last else statement is reached, the function will return “You lose!” and its execution will stop.

return value of a function is not shown in console (javascript)

I read all the previous and similar topics and I didnt get my answer
The problem is that the function "rockPaperScissors" doesn't return anything in the close despite the fact that I have put return messages inside for different conditions,
Thanks in advance ,
what is the problem and solution and what have I done wrong?
let playerScore = 0;
let computerScore = 0;
let pcChoice = Math.floor(Math.random() * 3) + 1;
if (pcChoice === 1) {
pcChoice = "rock";
} else if (pcChoice === 2) {
pcChoice = "paper";
} else {
pcChoice = "scissors";
}
let userInput = prompt("Rock ?\nPaper?\nScissors?")
userInput = userInput.toLowerCase();
let errorMessage = "You have put a wrong input"
if (! ((userInput === "rock") || (userInput === "paper") || (userInput === "scissors"))) {
alert(errorMessage);
} else {
rockPaperScissors(userInput, pcChoice);
console.log("Userscore is " + playerScore + "and Computerscore is " + computerScore);
};
if (playerScore > computerScore) {
console.log("You are the winner");
} else if (computerScore > playerScore) {
console.log("Computer is the winner");
} else {
console.log("It's a draw");
}
function rockPaperScissors(user, pc) {
let winningMessage = "You Won!";
let drawMessage = "it's a draw!";
let losingMessage = " You lost!";
if (user === "rock" & pc === "scissors") {
playerScore++;
return `You won! ${user} beats ${pc}`;
} else if (user === "paper" & pc === "rock") {
playerScore++;
return `You won! ${user} beats ${pc}`;
} else if (user === "scissors" & pc === "paper") {
playerScore++;
return `You won! ${user} beats ${pc}`;
} else if (user === pc) {
return drawMessage;
} else {
computerScore++;
return `You won! ${pc} beats ${user}`;
}
}

What is wrong with my if/else statements?

My first time and first project: Rock, Paper, Scissors. I have spent hours trying to figure out what could be wrong with my if/else statements. Regardless of conditions evaluated, it returns the first statement(It's a tie"). My code is as below;
const computerSelection = computerPlay();
const playerSelection = humanPlay();
function computerPlay() {
let gameItems = ["rock", "paper", "scissors"];
let randItem = gameItems[Math.floor(Math.random() * gameItems.length)];
return randItem.toLowerCase();
}
function humanPlay() {
let selectItem = prompt(
"Please pick one battle item: rock, paper, or scissors"
);
return selectItem.toLowerCase();
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "It's a tie!";
} else if (computerSelection === "rock" && playerSelection === "scissors") {
return "You lose!";
} else if (computerSelection === "scissors" && playerSelection === "rock") {
return "You win";
} else if (computerSelection === "scissors" && playerSelection === "paper") {
return "You lose";
} else if (computerSelection === "paper" && playerSelection === "scissors") {
return "You win";
} else if (computerSelection === "paper" && playerSelection === "rock") {
return "You lose";
} else if (computerSelection === "rock" && playerSelection === "paper") {
return "You win";
} else {
return "Please play again";
}
}
console.log(computerSelection);
console.log(playerSelection);
console.log(playRound());
Add console.log(playerSelection, computerSelection) to the first line of the playRound() function. You'll see that both values are undefined, because you aren't passing those values into the function when you call it.
To fix, change the very last line to: console.log(playRound(computerSelection, playerSelection));

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.

Categories