Variable undefined in Javascript, help to make it correct - javascript

I'm coding a basic rock paper scissors game.
the 2 functions are working fine. the issue is the winner variable is always undefined..
I don't know what to do to correct this. I want it to say who won, computer or the human(user).
function game(x, y) {
var inputC = computerPlay();
var inputH = humanPlay();
var winner;
if (inputH == 'paper' && inputC == 'scissors') {
console.log('Computer wins with Scissors ');
if (inputH == 'scissors' && inputC == 'rock') {
console.log('Computer wins with rock');
if (inputC == 'paper' && inputH == 'rock') {
console.log('Computer wins with paper');
}
}
winner = "computer";
} else if (inputC == 'paper' && inputH == 'scissors') {
console.log('Human wins with Scissors ');
if (inputC == 'scissors' && inputH == 'rock') {
console.log('Human wins with rock');
if (inputH == 'paper' && inputC == 'rock') {
console.log('Human wins with paper');
}
}
winner = "human";
}
document.getElementById("text1").innerHTML = winner;
console.log("result is: " + winner + " wins");
}
I'm sure its something minor but my god I'm all out of ideas.

would like this
function game() {
var inputC = computerPlay();
var inputH = humanPlay();
var winner = "human";
if (inputH === inputC) {
winner = "nobody";
} else if ((inputH === 'paper' && inputC === 'scissors') ||
(inputH === 'scissors' && inputC === 'rock') ||
(inputH === 'rock' && inputC === 'paper')
) {
console.log('Computer wins with ' + inputC);
winner = "computer";
} else {
console.log('Human wins with ' + inputH);
}
document.getElementById("text1").innerHTML = winner;
console.log("result is: " + winner + " wins");
}

it was undefined because it didn't go to either one of condition.
Another alternative answer from me
function game(x, y) {
var inputC = computerPlay();
var inputH = humanPlay();
var isComputerWin =
(inputC == 'scissors' && inputH == 'paper') ||
(inputC == 'rock' && inputH == 'scissors') ||
(inputC == 'paper' && inputH == 'rock');
var winner = isComputerWin ? 'computer' : 'human';
var winnerWith = isComputerWin ? inputC : inputH;
console.log(winner + " wins with " + winnerWith);
document.getElementById("text1").innerHTML = winner;
console.log("result is: " + winner + " wins");
}

Related

How can I fix this rock, paper, scissor game in 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
.

i need help Rock , paper and scissors exercise

i did the "mechanics" but i tried to figured out how to play more rounds, i try a do_while loop but no work so what could be a good practice for more rounds?
const arrayPlay = ["rock","paper","scissors"];
const computerPlay = () =>{
return arrayPlay[~~(Math.random()*arrayPlay.length)]
}
let playerScore = 0;
let computerScore = 0;
const playRound = (playerSelection,computerSelection) =>{
if(playerSelection == "rock" && computerSelection == "scissors"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "paper" && computerSelection == "rock"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "scissors" && computerSelection == "paper"){
console.log("player get's one point");
playerScore += 1;
}
if(computerSelection == "rock" && playerSelection == "scissors"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "paper" && playerSelection == "rock"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "scissors" && playerSelection == "paper"){
console.log("computer get's one point");
computerScore += 1;
}
}
const playerSelection = prompt("rock,paper or scissors");
const computerSelection = computerPlay();
playRound(playerSelection,computerSelection);
You could move the playerSelection and computerSelection constants inside the playRound function. Then you can use the Window.confirm() method to show the results with a prompt to play again. If they select OK, then just call the playRound function again. If they click cancel then the game stops.
See snippet below.
More on Window.confirm() here: https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
const arrayPlay = ["rock", "paper", "scissors"];
const computerPlay = () => arrayPlay[~~(Math.random() * arrayPlay.length)];
let playerScore = 0;
let computerScore = 0;
const playRound = () => {
let playerSelection = prompt(`Please enter either "rock", "paper" or "scissors"`);
playerSelection = playerSelection ? playerSelection.toLowerCase() : playerSelection;
if (arrayPlay.includes(playerSelection)) {
const computerSelection = computerPlay();
let winner;
if (playerSelection == "rock" && computerSelection == "scissors") {
playerScore += 1;
winner = `player`;
} else if (playerSelection == "paper" && computerSelection == "rock") {
playerScore += 1;
winner = `player`;
} else if (playerSelection == "scissors" && computerSelection == "paper") {
playerScore += 1;
winner = `player`;
} else if (computerSelection == "rock" && playerSelection == "scissors") {
computerScore += 1;
winner = `computer`;
} else if (computerSelection == "paper" && playerSelection == "rock") {
computerScore += 1;
winner = `computer`;
} else if (computerSelection == "scissors" && playerSelection == "paper") {
computerScore += 1;
winner = `computer`;
}
showResults(computerSelection, playerSelection, winner);
} else if (playerSelection != null){
if (confirm(`The value you entered: "${playerSelection}" is invalid.\n\nWould you like to try again?`)) {
playRound();
}
}
}
const showResults = (computer, player, winner) => {
const playAgain = confirm(`
---Selection---
Player: ${player}
Computer: ${computer}
Results: ${winner ? `${winner} WINS!!` : "Draw"}
----Score----
Player: ${playerScore}
Computer: ${computerScore}
Would you like to play again?`);
if (playAgain) {
playRound();
} else {
playerScore = 0;
computerScore = 0;
}
}
playRound();
const arrayPlay = ["rock","paper","scissors"];
const computerPlay = () =>{
return arrayPlay[~~(Math.random()*arrayPlay.length)]
}
let playerScore = 0;
let computerScore = 0;
let keepPlaying = true;
// added keep playing condition and a while loop
while(keepPlaying) {
const playRound = (playerSelection,computerSelection) =>{
// empty input or 'quit' will end the game
if (playerSelection == "" || playerSelection == "quit") {
keepPlaying = false;
}
else if(playerSelection == "rock" && computerSelection == "scissors"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "paper" && computerSelection == "rock"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "scissors" && computerSelection == "paper"){
console.log("player get's one point");
playerScore += 1;
}
if(computerSelection == "rock" && playerSelection == "scissors"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "paper" && playerSelection == "rock"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "scissors" && playerSelection == "paper"){
console.log("computer get's one point");
computerScore += 1;
}
}
const playerSelection = prompt("rock,paper or scissors");
const computerSelection = computerPlay();
playRound(playerSelection,computerSelection);
// logging the new results
console.log({playerScore, computerScore})
}
const playRound = (playerSelection,computerSelection) =>{
if(playerSelection == computerSelection) return console.log("tie!")
//rest of your code here
}
console.log("Type end or stop to finish the game.");
while(true){
const playerSelection = prompt("rock, paper or scissors");
if(playerSelection == "end" || playerSelection == "stop"){
//code to show who won
break;
}
const computerSelection = computerPlay();
playRound(playerSelection,computerSelection);
}
Next time show code on what you tried, and what part wasn't working.

getting undefined in the console after entering either rock,paper or scissors in the prompt

<script>
console.log("enter \game()\ to start the game");
function computerPlay(){
let a = ['rock','paper','scissors'];
let b = a[Math.floor(Math.random * a.length)];
return b;
}
function humanPlay(){
let c = prompt('rock,paper or scissors');
return c;
}
function playRound ( computerSelection,humanSelection){
if (computerSelection == humanSelection) {
console.log("Its a tie");
}
if (computerSelection == 'rock' && humanSelection.toLowerCase() == 'paper') {
return 'human wins';
}
else if (computerSelection == 'rock' && humanSelection.toLowerCase() == 'scissors') {
return 'computer wins';
}
else if ( computerSelection == 'paper' && humanSelection.toLowerCase() == 'rock') {
return 'computer wins';
}
else if (computerSelection == 'paper' && humanSelection.toLowerCase() == 'scissors') {
return 'human wins';
}
else if (computerSelection == 'scissors' && humanSelection.toLowerCase() == 'rock') {
return 'human wins';
}
else if (computerSelection == 'scissors' && humanSelection.toLowerCase() == 'paper') {
return 'computer wins'
}
else if (computerSelection == 'rock' && humanSelection.toLowerCase() == 'scissors') {
return 'computer wins';
}
}
function game(){
computerSelection = computerPlay();
humanSelection = humanPlay();
let results = playRound(computerSelection,humanSelection);
console.log(results);
}
</script>
I've been trying to code this simple game from the Odin project for 2 hours and i can't wrap my head around why isn't the code working. I have looked at a few student solutions and tried to write my code again and again but it just doesn't seem to work each time. what am i doing wrong in this script?
I think your problem is in this line:
let b = a[Math.floor(Math.random * a.length)];
It should be:
let b = a[Math.floor(Math.random() * a.length)];
Also, you can test your code here: https://js.do/
Hope it helps!

How do I make my function game loop so that it updates the user and computer scores?

I am looping this rock paper scissors game 5 times, if user wins they get 1 if computer wins they get 1 and so on. How do i update the user and computer score? and if it ends up being a tie how do i make it so no one gets a point?
// Computer makes a choice
function computerPlay() {
let compchoice = ['Rock', 'Paper', 'Scissors'];
return compchoice[Math.floor(Math.random() * compchoice.length)];
}
//Plays a single round Player vs Computer
function playRound(playerSelection, computerSelection) {
//Player
if (playerSelection === 'Rock' && computerSelection === 'Scissors')
{
return 'You chose ' + playerSelection + ',' + ' You win!';
} else if (playerSelection === 'Paper' && computerSelection ===
'Rock') {
return 'You chose ' + playerSelection + ',' + ' You win!';
} else if (playerSelection === 'Scissors' && computerSelection ===
'Paper') {
return 'You chose ' + playerSelection + ',' + ' You win!';
}
// Computer
else if (computerSelection === 'Rock' && playerSelection ===
'Scissors') {
return 'Computer chose ' + computerSelection + ',' + 'Computer
wins!';
} else if (computerSelection === 'Paper' && playerSelection ===
'Rock') {
return 'Computer chose ' + computerSelection + ',' + 'Computer
wins!';
} else if (computerSelection === 'Scissors' && playerSelection ===
'Paper') {
return 'Computer chose ' + computerSelection + ',' + ' Computer
wins!';
} else if (computerSelection === playerSelection) {
return 'Its a draw!';
} else {
return 'Please chose Rock, Paper, or Scissors';
}
}
//loops game 5 times to decide a winner.
function game() {
for(var i=0;i<5;i++){
let playerSelection = prompt("Rock, Paper, Scissors");
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))
console.log("your score = " + userScore);
console.log("Computer's score = " + computerScore);
}
}
let userScore =0;
let computerScore =0;
console.log(game());
I think this is what you're trying to achieve. You just need to keep track of the scores while your loop (i.e: game) iterates. I modified playRound to return an array - the first element is signifies whether the player beat the computer in the round & the second is the message that you were originally console.loging in the function:
// Computer makes a choice
function computerPlay() {
let compchoice = ['Rock', 'Paper', 'Scissors'];
return compchoice[Math.floor(Math.random() * compchoice.length)];
}
//Plays a single round Player vs Computer
function playRound(playerSelection, computerSelection) {
let playerWinsRound = false;
let text;
//Player
if (playerSelection === 'Rock' && computerSelection === 'Scissors') {
playerWinsRound = true;
text = 'You chose ' + playerSelection + ',' + ' You win!';
} else if (playerSelection === 'Paper' && computerSelection ===
'Rock') {
playerWinsRound = true;
text = 'You chose ' + playerSelection + ',' + ' You win!';
} else if (playerSelection === 'Scissors' && computerSelection ===
'Paper') {
playerWinsRound = true;
text = 'You chose ' + playerSelection + ',' + ' You win!';
}
// Computer
else if (computerSelection === 'Rock' && playerSelection ===
'Scissors') {
text = 'Computer chose ' + computerSelection + ', Computer wins!';
} else if (computerSelection === 'Paper' && playerSelection ===
'Rock') {
text = 'Computer chose ' + computerSelection + ', Computer wins!';
} else if (computerSelection === 'Scissors' && playerSelection ===
'Paper') {
text = 'Computer chose ' + computerSelection + ', Computer wins!';
} else if (computerSelection === playerSelection) {
playerWinsRound = null;
text = 'Its a draw!';
} else {
text = 'Please chose Rock, Paper, or Scissors';
}
return [playerWinsRound, text];
}
//loops game 5 times to decide a winner.
function game() {
//Score is part of the game - so move the score vars inside the game function
let userScore = 0;
let computerScore = 0;
//Update the scores on each iteration of the loop (i.e.: each round)
for (var i = 0; i < 5; i++) {
const playerSelection = prompt("Rock, Paper, Scissors");
const computerSelection = computerPlay();
const [playerWinsRound, text] = playRound(playerSelection, computerSelection)
if (playerWinsRound) {
userScore += 1;
} else {
if (playerWinsRound === false) {
computerScore += 1;
}
}
console.log(text);
console.log(`Your score = ${userScore}`);
console.log(`Computer score = ${computerScore}`);
}
}
game();

Exiting out of a function in Javascript. Simple rock, paper, scissors game

How do i stop the function from executing if the userChoice is null or a word apart from rock,paper or scissors.
I've tried to use return but i couldn't get it to work.
Any help is appreciated.
Thanks
JS Fiddle Link = http://jsfiddle.net/Renay/d9bea2ra/1/
var userChoice = prompt('Do you choose rock, paper or scissors?');
var compChoice = Math.random();
if (compChoice <= 0.34) {
compChoice = 'rock';
} else if (compChoice <= 0.67) {
compChoice = 'paper';
} else {
compChoice = 'scissors';
}
function compare() {
if (userChoice == compChoice) {
console.log( 'The result is a tie!');
} else if ((userChoice == 'rock' && compChoice == 'scissors') || (userChoice == 'paper' && compChoice == 'rock') || (userChoice == 'scissors' && compChoice == 'paper') ) {
console.log( 'You win!');
} else {
console.log('You lose!');
}
if (userChoice === null) {
console.log('Please select an option');
} else if (userChoice !== 'rock'&&'paper'&&'scissors') {
console.log('Please select rock, paper or scissors');
}
}
console.log('Your choice = ' + userChoice);
console.log('Computer Choice = ' + compChoice);
compare();
The condition in your if statement is wrong. It should be:
if (userChoice !== 'rock' && userChoice !== 'paper' && userChoice !== 'scissors')
An expression of the form e1 && e2 && e3 && ... evaluates to last eN sub-expression if all of them truthy. So your test was equivalent to:
if (userChoice !== 'scissors')
You should put that check before displaying the result of the game, and return from the function then. So it should be:
function compare() {
if (userChoice === null) {
console.log('Please select an option');
return;
} else if (userChoice !== 'rock' && userChoice !== 'paper' && userChoice !== 'scissors') {
console.log('Please select rock, paper or scissors');
return;
}
if (userChoice == compChoice) {
console.log( 'The result is a tie!');
} else if ((userChoice == 'rock' && compChoice == 'scissors') || (userChoice == 'paper' && compChoice == 'rock') || (userChoice == 'scissors' && compChoice == 'paper') ) {
console.log( 'You win!');
} else {
console.log('You lose!');
}
}
Just do return;
function compare() {
if(!userChoice)
return;
// (...) more code
}
A return call exits the function. But note that you can only use return inside a function
If i understand correctly, you want to return to the beginning of the code. You should wrap the entire thing in a function, then call that function again:
function rockPaperScissors() {
var userChoice = prompt('Do you choose rock, paper or scissors?');
var compChoice = Math.random();
if (compChoice <= 0.34) {
compChoice = 'rock';
} else if (compChoice <= 0.67) {
compChoice = 'paper';
} else {
compChoice = 'scissors';
}
function compare() {
if (userChoice == compChoice) {
console.log( 'The result is a tie!');
} else if ((userChoice == 'rock' && compChoice == 'scissors') || (userChoice == 'paper' && compChoice == 'rock') || (userChoice == 'scissors' && compChoice == 'paper') ) {
console.log( 'You win!');
} else {
console.log('You lose!');
}
if (userChoice === null) {
console.log('Please select an option');
rockPaperScissors();
} else if (userChoice !== 'rock' && userChoice !== 'paper' && userChoice !== 'scissors') { // fixed
console.log('Please select rock, paper or scissors');
rockPaperScissors();
}
}
console.log('Your choice = ' + userChoice);
console.log('Computer Choice = ' + compChoice);
compare();
}
rockPaperScissors();
You also had an error with checking if it isn't one of rock, paper, or scissors, so i fixed that. (It seems Barmar got to it before me.)
I updated each if/else part of your function to exit when it match if/else condition with return false. In addition I changed the if (userChoice === null) check to if (userChoice === "") because it looks like that prompt('Do you choose rock, paper or scissors?'); returns an empty string when the user doesn't enter any value. Fiddle Also, I just updated the beginning of the function to work accordingly to **Barmar'**s suggestion (he got it right first time around).
function compare() {
if (userChoice === "") {
console.log('Please select an option');
return false;
} else if ((userChoice !== 'rock') && (userChoice !=='paper') && (userChoice !=='scissors')) {
console.log('Please select rock, paper or scissors');
return false;
}
if (userChoice == compChoice) {
console.log('The result is a tie!');
return false;
} else if ((userChoice == 'rock' && compChoice == 'scissors') || (userChoice == 'paper' && compChoice == 'rock') || (userChoice == 'scissors' && compChoice == 'paper')) {
console.log('You win!');
return false;
} else {
console.log('You lose!');
return false;
}
}

Categories