Playing a game of rock, paper, scissors with two players using JavaScript

Hello! I am a beginner in JavaScript and I am trying to create a simple rock, paper, scissors game. However, when I run the code, I receive two prompt messages and an error saying 'TypeError: playerOneChoice is not a function'. What mistake did I make? Thank you very much.

function getPlayerOneChoice(){
  var playerOneInput = prompt('Hey there! What is your choice: rock, paper, or scissors?');
  playerOneInput = playerOneInput.toLowerCase();
  if(playerOneInput === 'rock' || playerOneInput === 'paper' || playerOneInput === 'scissors'){
    return playerOneInput;
  } else {
    console.log('Invalid Choice!!!');
  }
}

function getPlayerTwoChoice(){
  var playerTwoInput = prompt('And what\'s your pick? Rock, paper, or scissors?');
  playerTwoInput = playerTwoInput.toLowerCase();
  if(playerTwoInput === 'rock' || playerTwoInput === 'paper' || playerTwoInput === 'scissors'){
    return playerTwoInput;
  } else {
    console.log('Invalid selection!!');
  }
}

function determineWinner(playerOneChoice, playerTwoChoice) {
  if(playerOneChoice == playerTwoChoice) {
    console.log('It\'s a Tie!');
  }
    if(playerOneChoice === 'rock'){
    if(playerTwoChoice === 'scissors'){
      return 'You win with rock!';
    } else {
       return 'You win with paper!';
    }
  }
 if(playerOneChoice === 'scissors'){
   if(playerTwoChoice === 'paper'){
     return 'Congratulations, scissors won!';
   } else{
     return 'Scissors win this time!';
   }
 }
 if(playerOneChoice === 'paper'){
   if(playerTwoChoice === 'rock'){
     return 'Paper wins!';
   } else {
     return 'Rock beats paper!';
   }
 }  
}

function playGame() {
  var playerOneChoice = getPlayerOneChoice();
  var playerTwoChoice = getPlayerTwoChoice();
  console.log('Player One picked: ' + playerOneChoice);
  console.log('Player Two picked: ' + playerTwoChoice);
  console.log(determineWinner());
}

playGame();

Answer №1

There are 3 mistakes in the provided code

1.

console.log('Mihai\'s choice : ' + playerOneChoice());

The function playerOneChoice is being called but it should be a variable, not a function. Remove the parentheses to fix this error.

2. console.log(determineWinner());

This method requires two parameters, playerOneChoice and playerTwoChoice. Call it like

determineWinner(playerOneChoice, playerTwoChoice)

3.

if (playerOneChoice === playerTwoChoice)

In this line, you are assigning values instead of comparing them. Use === for comparison.

function getPlayerOneChoice() {
  var playerOneInput = prompt('Mihai please choose: ');
  playerOneInput = playerOneInput.toLowerCase();
  if (playerOneInput === 'rock' || playerOneInput === 'paper' || playerOneInput === 'scissors') {
    return playerOneInput;
  } else {
    console.log('Invalid Choice !!!');
  }
}

function getPlayerTwoChoice() {
  var playerTwoInput = prompt('Flavia what is your pick?');
  playerTwoInput = playerTwoInput.toLowerCase();
  if (playerTwoInput === 'rock' || playerTwoInput === 'paper' || playerTwoInput === 'scissors') {
    return playerTwoInput;
  } else {
    console.log('Invalid pick !!');
  }
}

function determineWinner(playerOneChoice, playerTwoChoice) {
  if (playerOneChoice === playerTwoChoice) {
    console.log('It\'s a Tie');
  }
  if (playerOneChoice === 'rock') {
    if (playerTwoChoice === 'scissors') {
      return 'Mihai wins!';
    } else {
      return 'Flavia wins';
    }
  }
  if (playerOneChoice === 'scissors') {
    if (playerTwoChoice === 'paper') {
      return 'Mihai wins!!!';
    } else {
      return 'Flavia wins!!!';
    }
  }
  if (playerOneChoice === 'paper') {
    if (playerTwoChoice === 'rock') {
      return 'Mihai wins';
    } else {
      return 'Flavia wins';
    }
  }
}

function playGame() {
  var playerOneChoice = getPlayerOneChoice();
  var playerTwoChoice = getPlayerTwoChoice();
  console.log('Mihai chose: ' + playerOneChoice);
  console.log('Flavia chose: ' + playerTwoChoice);
  console.log(determineWinner(playerOneChoice, playerTwoChoice));
}

playGame();

Answer №2

Take out the parentheses from playerOneChoice() and playerTwoChoice()

It should look like this:

console.log('John's selection : ' + playerOneChoice);
console.log('Sarah's selection : ' + playerTwoChoice);

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

Having trouble executing react-native project using the command "npx react-native run-android"

Hey there! I've been working on a react-native project for quite some time now and everything was going smoothly until yesterday. I encountered an error when running the command npx react-native run-android in Metro before the project had fully execut ...

Upgrading React Native hot reloading leads to a complete reload of the application

Recently, I updated my React Native app from version 0.48 to 0.55. Unfortunately, after the upgrade, hot reloading stopped functioning. Any modifications to the files now trigger a complete reload of the app. I have attempted clearing all cache related to ...

retrieve the position of a descendant element in relation to its ancestor element

I'm encountering a challenge while attempting to solve this issue. I have elements representing a child, parent, and grandparent. My goal is to determine the offset position of the child (positioned absolutely) in relation to the grandparent. However, ...

Looking to implement pyperclip functionality on Heroku platform

Is it feasible to utilize pyperclip on Heroku with a Selenium application in order to copy something to the clipboard? Since the platform utilizes a 'headless' browser and lacks a GUI, accessing the clipboard is challenging. Is there any way for ...

Creating a Vue component using v-for and a factory function allows for dynamic

I am currently developing a Table component using factory functions for all logic implementation. Within a v-for loop, I generate a cell for each item in every row. The factory Below are the actual factories that I import into the respective vue page whe ...

Tips for circumventing the ajax data size restriction in asp.net mvc3

Currently, I am implementing an auto suggest function using AJAX in the following manner: $("#empName2").autocomplete({ search: function (event, ui) { var key = CheckBrowser(event); if (key == 13) return tr ...

Unable to assign value to Ref data property in Vue3 due to undefined item

Recently, I've been utilizing Vue3 and Nuxt3 to work on a project. My main task involves extracting the :id parameter from the URL and checking if it matches an ID in a JSON file. If there is a match, I update a reference data point called 'exist ...

A for loop is executed after a console.log statement, even though it appears earlier in the code

When this specific block of code is implemented var holder = []; const compile = () =>{ let latitude = 0; let longitude = 0; for (let i = 0; i < holder.length; i++) { Geocode.fromAddress(holder[i].city).then( (response ...

Revamping status and backend systems

Seeking advice on the most effective method to execute a HTTP PUT request within my react application. A Post component is responsible for fetching data from https://jsonplaceholder.typicode.com/posts/1 and displaying it. There's another component na ...

The CanJS model is unable to retrieve data from a .json file

Implementing MVC using AMD in canjs with requirejs has been my current focus. Here's a look at my domains.json file: [ "1":{"uid": "1","urls": "domain1.abc.com"}, "2":{"uid": "2","urls": "domain2.abc.com"}, "3":{"uid": "3","urls ...

Intermittent occurrence of (404) Not Found error in the SpreadsheetsService.Query function

Using the Spreadsheet API, I frequently update various sheets. Occasionally, and without any pattern, the SpreadsheetsService.Query function returns a (404) Not Found error. This issue does not seem to be related to internet connectivity or server downti ...

The confusing case of jQuery's e.preventDefault: Unable to submit form despite preventing default behavior

Objective: Prevent the 'submit' button from functioning, validate fields, generate popover alerts for results, and submit form upon closing of popover. To achieve this, I have set up a hidden popover div. When the submit button is clicked, I uti ...

The Javascript code is failing to run following an ajax request

When I use XMLHttpRequest.send to call a php script that contains some javascript code, the javasript in the called php script does not run. The process of making the call: var formdata = new FormData(); formdata.append("uploadfilename", file); var ajax ...

Develop interactive web applications using Typescript

Having difficulty compiling and executing the project correctly in the browser. The "master" branch works fine, but I'm currently working on the "develop" branch. It's a basic web project with one HTML file loading one TS/JS file that includes i ...

What is the rationale behind not passing $scope to a service in AngularJS, and is it considered bad practice?

Is it advisable not to pass $scope to a service for certain reasons? I understand that services are intended to be reusable singletons, and passing a (potentially) large object to the service could lead to maintenance issues. However, assuming there is so ...

Issue: Inability to scroll on div overflow section

My website consists of one static page with an HTML and CSS file. Oddly enough, when testing the page and inputting content into a multiline textarea until it overflows, the browser fails to display a scrollbar. Despite inspecting the div with the id &apos ...

Minimize the gap between legend text and icon in Highchart

Is there a way to decrease the space between the number and icon? I am currently working with Angular 8 and Highchart. Below is the configuration of the chart legend. https://i.stack.imgur.com/0dL7y.jpg this.legend = { align: 'center', verti ...

How to append a JSON object to an existing .json file

UPDATE: Despite successfully executing the PHP code, my JSON file remains unchanged. I must apologize in advance for covering old ground, but I have spent countless hours exploring different solutions with no success. Perhaps sharing my challenge could as ...

npm update fails to update specific packages

After React was updated to version 0.15 to address the issue of excessive generation of tags, I made the decision to update my project.</p> <p>However, when I ran the command <code>npm update, it only updated to version 0.14.8. Running ...

What is the best way to fetch the title property from my Campaign Contract for displaying it in the render method?

I'm currently working on a unique crowdfunding DApp that requires constant access to contract variables through function calls for retrieval purposes. The getDeployedCampaigns function is responsible for returning an array of deployed campaign addres ...