The JavaScript rock, paper, scissors application is experiencing issues with displaying correctly

Currently, I am in the process of learning JavaScript and working on developing a rock, paper, scissors game using only JavaScript. The game will have two modes- a single round mode and a three-round mode. However, after completing the code for the single round mode, I encountered an issue in displaying the result. Regardless of who wins the game, it always displays "the game is tie" and I am unable to locate the mistake. Can anyone provide assistance?

    // 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();
}

Answer №1

The function getWinner() that you have implemented returns either player win or computer win, however, the code calling this function is expecting values of player or computer.

Due to this mismatch in return values, the code defaults to saying 'The Game is Tie' as it doesn't receive the expected results.

Answer №2

The issue lies within the singleRound() function due to a small error. In the code snippet,

if (winner === "player") {
should actually be
if (winner === "player win") {
. Similarly,
if (winner === "computer") {
should be corrected to
if (winner === "computer win") {
. This adjustment ensures that the text being compared aligns correctly. Currently, the comparison is between "player" and "player win", as well as "computer" and "computer win", leading to reaching the else clause regardless of the actual game outcome.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps do I need to take in order to integrate an mpg video onto my

I am in need of embedding mpg (dvd compliant mpeg2) movie files onto my webpage. Unfortunately, I do not have the ability to convert these videos into any other format. This webpage is solely for personal use, so any solution would be greatly appreciated. ...

Utilizing $templateCache with ui-router and minifying in AngularJS 1.x

Posting this as a question-answer post. How can one effectively utilize the $templateCache in the templateProvider of a route within ui-router when attempting to refactor the code? Injection is ineffective, and Angular cannot inject by reference. For ins ...

Disable the Tooltip Bootstrap feature

Based on the documentation, it seems possible to disable the functionality by using $('body').off('.alert.data-api'). I attempted to do the same for tooltips by running $('body').off('.tooltip.data-api') in the Jav ...

Tips on effectively utilizing a function within middleware in Node.js

I've successfully used the checkAuth function with this format: router.get('/login', checkAuth, function(){ }) Now I'm wondering how to utilize the checkAuth function with this format: routes file router.get('/login', con ...

Is it possible to incorporate an external javascript file in my CSS file?

Currently, I am attempting to create a setup where my background adjusts based on the width of the user's browser. However, I am constrained by a background specified in the external stylesheet under a specific element. While I have the ability to alt ...

Managing HTTP requests across different HTML pages in a Cordova mobile application

I have developed a Multiple Page Application (MPA) for Android and iOS which navigates to different pages when users want to view them. Everything is running smoothly so far, but I now want to add some backend sync features. The issue I am facing is that I ...

Having trouble with data retrieval from MySQL using PHP and Angular on certain mobile devices, although it functions properly on desktops and laptops

The data retrieved from the mysql database is functioning properly on desktop and laptop, but not on mobile devices. The following HTML code is present in the html file: <table class="table table-default"> <thead> <tr> & ...

Could JOI be used to validate unidentified keys within nested data structures?

I've developed a middleware that uses Joi to validate incoming requests. export default (schema: any) => async (req: Request, res: Response, next: NextFunction) => { try { const validation = schema.validate(req, { abortEarly: false }) ...

The MIME type 'text/html' is incompatible with stylesheet MIME type and is not supported

I have exhausted all possible solutions for the issue, from specifying the type for <link rel="stylesheet" href="./style.css" /> to using app.use(express.static('public')), but unfortunately, none of them seem to resolve the problem. index ...

HTML comments generated from Freemarker's list notation

Currently, I have integrated Apache Freemarker into an HTML editor where users can create templates using code. For example, a user may write the following code for a list: <#list items as item>...</#list> While this is the correct way to gen ...

Adding input values to a jQuery Ajax POST request

I am currently attempting to send form values to a remote API using AJAX. The necessary information I require from the HTML form element includes the author, string, false, and true. At the moment, I have hard-coded some values but... function sendData ...

What sets Protractor apart from Grunt?

According to the Protractor website (http://www.protractortest.org/#/infrastructure), Protractor utilizes Selenium for browser automation. However, when browsing through the Grunt website (http://gruntjs.com/), it's mentioned that Grunt is also used f ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Key factors to keep in mind when comparing JavaScript dates: months

Check the dates and determine if the enddate refers to the following month by returning a boolean value. Example startdate = January 15, 2020 enddate = February 02, 2020 Output : enddate is a future month startdate = January 15, 2020 enddate = January 2 ...

What is the best way to trigger a JavaScript function using an HTML button?

I am trying to trigger a JavaScript file from an HTML component by clicking on a button, but nothing happens when I click the button: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> < ...

What steps can I take to avoid keypress events causing issues with the browser's input functionality?

Utilizing Bootstrap's modal component, I have implemented an "Add User" dialog within my web application. In order to streamline the user experience and enable quick data entry, I am aiming for the escape and enter keys to close and submit the form re ...

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

Maintain MUI Autocomplete in the open state even after making a selection from the

Whenever I select certain options on my Autocomplete component, I want to keep the component open. However, each time I click on onChange, the Autocomplete closes automatically and I can't seem to find a way to prevent this. Is there a workaround? In ...

Ways to determine the count of selected checkboxes in React.js?

Recently, I delved into learning React. For one of my beginner projects, I decided to create a "life checklist" using Functional Components as the foundation. Just a heads up: I've structured data.js as an array of objects containing "action", "emoj ...

The PHP script encountered an issue with the HTTP response code while processing the AJAX contact form, specifically

Struggling to make this contact form function properly, I've tried to follow the example provided at . Unfortunately, all my efforts lead to a fatal error: "Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom ...