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

Error: WebView element type is not valid. A valid string was expected

Here is my basic React code : import React from "react"; import { Text, StyleSheet,View } from "react-native"; import { WebView } from 'react-native'; const App = () => { return( <WebView source={{ ...

A guide on incorporating Vue.js into a Hexo static site generator

Exploring the use of vue.js within my hexo theme has sparked my interest. Can anyone guide me on how to compile my .vue files for both development and production environments? It's worth mentioning that I intend for vue.js to operate on the client sid ...

Is a component updating an unregulated text input to be controlled?

Whenever I attempt to input information into the form and save it in the state, I encounter the following issue: Warning: A component is converting an uncontrolled text input to a controlled one. Input elements should not transition between being contro ...

Determine if a specific checkbox with a particular id has been selected using JQuery

Looking for assistance on how to determine if a checkbox with a specific ID is checked or unchecked. <input name="A" id="test" type="checkbox" value="A" /> <input name="B" id="test" type="checkbox" value="B" /> <input name="C" id="test1" t ...

When utilizing AJAX within a for loop, the array position may not return the correct values, even though the closure effectively binds the scope of the current value position

Is this question a duplicate of [AJAX call in for loop won't return values to correct array positions? I am following the solution by Plynx. The issue I'm facing is that the closure fails to iterate through all elements in the loop, although the ...

Elevate your Material UI Avatar with an added level of

Attempting to give a MUI Avatar component some elevation or shadow according to the documentation provided here. <Avatar alt="Cindy Baker" src="/static/images/avatar/3.jpg" /> Enclosing the Avatar within a paper or Card element increases the size o ...

Stopping the animation of scrollLeft upon user interaction can be achieved by utilizing JavaScript

Here is my current code snippet: <script> $(document).ready(function() { $('.scrolls').stop().animate({ scrollLeft : 4000 },100000, 'linear') }) </script> I am looking for a way to halt the animation once ...

Flow bar for micro-tasks

In my current project, I am faced with the task of organizing a series of 4 mini tasks and displaying to the end user which specific mini task they are currently on. To accomplish this, I have been utilizing image tags for each task. <img>1</img ...

Is there a way to retrieve the properties of another function within the same component?

I am trying to place NumberFormat inside OutlinedInput and I also need different properties for the format of NumberFormat. (There will be a select window that defines which format property to use). This is what I have: import OutlinedInput from "@ma ...

JavaScript problem with setting values in 2D array

I am attempting to assign values to a 2d array at particular indices. During each iteration, all sub-arrays at the j index are being assigned the same variable (number). inputTensor dimensions: 140x7 - 140 arrays of size 7 inputMinArray dimensions: 1x7 - ...

"Empty array conundrum in Node.js: A query on asynchronous data

I need assistance with making multiple API calls and adding the results to an array before returning it. The issue I am facing is that the result array is empty, likely due to the async nature of the function. Any help or suggestions would be greatly appre ...

utilize javascript variables within an HTML document

I keep encountering a strange error (Express 400 Error: Bad Request) Some lines are translated to the variable value, while others just output an error. This is an example of my code: exports.add_comment = function(req, res){ var id = req.params.id; ...

A Node.js feature that enables atomic file replacement, triggering watchers only once

I have a unique scenario where I need to handle two types of processes. One process is responsible for writing a file, while the other processes are required to read it whenever there is a change. In my research, I came across fs.watch as a solution to ke ...

The Vuetify accordion template is not appearing due to a v-for loop issue in Nuxt.js

My goal is to set up an FAQ page using Nuxt.js. The template I obtained from Vuetify doesn't display correctly on my localhost. Instead, I'm encountering errors. If I replace 'v-for "(item,i) in 5" : key="i"' as per the template source ...

Is it possible to add to the existing class based on a certain condition?

I have a coding challenge that I need help with. I have a set of code where I want to replace the old value in a class named "content" based on certain conditions. If the value within the class matches one of the values in an Array, then I need to append s ...

Express application receiving repetitive post requests

Recently, I have been working on developing a YouTube video conversion app that utilizes youtube-dl for streaming videos from YouTube and saving them. Everything was going smoothly until I encountered an issue when trying to stream a video that exceeded on ...

After zooming in on the canvas and panning, I encountered a problem where I was unable to drag objects within the canvas. Instead, the canvas continued to pan as I tried to move the objects

1) I have the ability to pan the canvas and drag images without scaling or zooming. 2) When scaling or zooming, I can still drag images within the canvas. 3) However, if I try to pan the canvas after zooming and then attempt to drag images, only the canv ...

Can you eliminate the commas and turn it into a string?

function EncryptMessage(message) { var encryptedArr = []; for(i=0;i<message.length+1;i++){ var unicode = message.charCodeAt(i); var encryptedUnicode; var newCharacter = String.fromCharCode(encryptedUnicode); if( ...

Errors in Chartist.js Data Types

I am currently using the Chartist library to monitor various metrics for a website, but I have encountered some challenges with the plotting process. The main errors that are appearing include: TypeError: a.series.map is not a function TypeError: d.normal ...