Home > Software engineering >  Game where two players have to try to guess a random number
Game where two players have to try to guess a random number

Time:10-04

I wanted to create a game where two players have to try to guess a random number. Here's the code i tried to use:

const player1 = '87'
const player2 = '55'

const randomNumber = '55' //Math.floor(Math.random() * 100   1)

console.log('Player 1:', player1)
console.log('Player 2:', player2)

if(randomNumber != player1 || randomNumber != player2){ //if no one guessed the number
  console.log('No one guessed the random number which is', randomNumber)
} else { //if someone guessed the number
  console.log('The random number is', randomNumber)
}

Normally the const randomNumber should be the comment but to try if it works i put '55' which is the same number as the const player2, which is the Player 2 attempt to guess the number, so it should console.log the part where i commented //if someone guessed the number but somehow this code always console.log the part where i commented //if no one guessed the number

CodePudding user response:

    const player1 = '87'
    const player2 = '55'
    
    const randomNumber = '87' //Math.floor(Math.random() * 100   1)
    
    console.log('Player 1:', player1)
    console.log('Player 2:', player2)
    
    if(randomNumber !== player1 && randomNumber !== player2){ //if no one guessed the number
      console.log('No one guessed the random number which is', randomNumber)
    } else { //if someone guessed the number
      console.log('The random number is', randomNumber ,"Guessed by player : ",randomNumber === player1?"Player 1":"Player 2")
    }

  • Related