javascriptobjectwindowwindow-object

Prompt Not working inside for loop in Javascript


alert("You will play 10 round and the highest scorer will win the game")
 //let player1 = prompt("choose")

let element = ['snake', 'water', 'gun']
let player1_score=0
let player2_score=0

for (let i =0; i<10;i++)
{
  
    let player1 = prompt("choose")
    let player2 = element[Math.floor(Math.random() * (element.lenght -0) + 0)]
    
    if ((player1== snake && player2 ==snake) || (player1== water && player2==water) || (player1== gun && player2 ==gun))
    {
        alert("Tie")
    }

    if ((player1== snake && player2 ==water) | (player1== gun  && player2==snake) || (player1== water && player2 == gun))
    {
        alert("player1  wins")
        player1_score++
    }

    if ((player1== snake && player2 ==gun) || (player1== gun && player2==water) || (player1== water  && player2 ==snake))
    {
        alert("player2  wins")
       player2_score++
    }
        
  }

alert("winner of Game is : ")

if (player1_score > player2_score )
  alert("user wins with score : " + player1_score)
else if (player2_score > player1_score)
  alert ("bot wins with score" +  player2_score)
else 
  alert ("tie")

console.log("final score"+ "\n" + "user : " + player1_score + "\n" + "bot : " + player2_score )

The problem is with the prompt inside the for loop for player1. When I enter snake inside the prompt box it gives a error "snake is not defined". But when I try outside the for loop it works fine. Please help me out I am still in learning phase.


Solution

  • The problem is with the prompt inside the for loop for player1.

    No it isn't. The problem is where the code is trying to use a variable that isn't defined:

    (player1 == snake && player2 == snake)
    

    There is no variable called snake. There is, however, a string value 'snake':

    let element = ['snake', 'water', 'gun']
    

    Did you mean to compare it with a string?:

    (player1 == 'snake' && player2 == 'snake')
    

    Or perhaps with the array element?:

    (player1 == element[0] && player2 == element[0])