mercredi 27 octobre 2021

I have trouble managing my for loop inside while loo[ and vice versa

I have been recently working on a project to make a rock paper scissor game in JS console. Right now as you can see in the code below I am only testing the waters with rock and scissor and will soon be adding paper as soon as I resolve this bug. I want to play this game for six rounds between a randomly generated pick (variable b) and user's choice (variable a).

I want the for loop to run 6 times to play six rounds. There is no score counter whatsoever for now. As I run the for loop I want the randomly generated pick to be logged in console and then the user will be asked for the selection and his/her choice will be logged after that. I then want my if statements inside the do-while loops to evaluated the current two values of a and b and give me the result I am trying to log (eg. Rock crushes scissor! You loose!) immediately after the two responses are logged. Then another random choice will be generated and logged and so on....

What is happening right now is that I am getting the if statements evaluated only after the sixth iteration of for loop whereas it should give me the logged statement from if conditional after every iteration.

Here is the code:

var arr = ['rock', 'scissor']
let win = false

function play(arr){

  
    
    do{

      for(let i=0; i<=5;i++){
        var a = prompt('Enter choice:')
        console.log(a)
        var b = arr[(Math.floor(Math.random()*2))]
        console.log(b)

        if(a==="rock" && b==="scissor"){
          console.log("Rock crushes Scissor! You win!") 
          win=true
        }
        
        else if(b==="rock" && a==="scissor"){
          console.log("Rock crushes Scissor! You lose!") 
          win=true
        }
    
      }

    }
    while(!win);
  
    check_winner(win)
  }

 
function check_winner(win){
  if(win===true){
    console.log("gamne over")
  }
  else{
    prompt("Enter again")
  }
}

play(arr)

I am new to JS and having a tough time dealing with this bug. Maybe you sincere people could get me out of this predicament. Any help will be extremely appreciated. Thank you!

Aucun commentaire:

Enregistrer un commentaire