Example 3

The code shown here is based upon the Rock, Paper and Scissors game.

Click here to play the Rock, Paper and Scissors game.

Note: Remember to press [F5] in your browser if you want to try again.

Comments have been added to the code.

<html>
<head>
<script>

// Declare and initialise variables
// Boolean variables used as a flag for the result
var CompWin = false;
var PlayerWin = false;
var Draw = false;

// Integer variables used for guesses
var CompGuess = 0 ;
var PlayerGuess = 0 ;

// Get computer guess
var CompGuess = Math.floor((Math.random() * 3) + 1);
// alert('Computer Guess = ' + CompGuess); // Retained for testing purposes

do
{ // begin do..while
// Get player guess and display 1 = Rock, 2 = Paper and 3 = Scissors
PlayerGuess = prompt('Enter your guess ' + '\n' + '1 = Rock, 2 = Paper and 3 = Scissors:');

// Data validation to make sure the player has entered a value between 1 and 3
if (PlayerGuess < 1 || PlayerGuess > 3)
{ // begin if
alert('Number not in range - Try again!');
} // end if

} // end do..while
while (PlayerGuess < 1 || PlayerGuess > 3);

// Calculate game result
// For testing use only. Possible combinations = 11, 12, 13, 21, 22, 23, 31, 32, 33
if (CompGuess == PlayerGuess)
{ // begin if
Draw = true; // Same item chosen by computer and player
alert('Draw - Both competitors selected the same item');
} // end if

// Computer chooses Rock and Player chooses Paper
if (CompGuess == 1 && PlayerGuess == 2)
{ // begin if
PlayerWin = true; // Rock is covered by Paper
alert('Player = Paper' + '\n' + 'Computer = Rock' + '\n' 
     + 'Player Wins - Rock is covered by Paper');
} // end if

// Computer chooses Rock and Player chooses Scissors
if (CompGuess == 1 && PlayerGuess == 3)
{ // begin if
CompWin = true; // Rock blunts Scissors
alert('Player = Scissors' + '\n' + 'Computer = Rock' + '\n' 
     + 'Computer Wins - Rock blunts Scissors');
} // end if

if (CompGuess == 2 && PlayerGuess == 1)
{ // begin if
CompWin = true; // Paper covers Rock
alert('Player = Rock' + '\n' + 'Computer = Paper' + '\n' 
     + 'Computer Wins - Paper covers Rock');
} // end if

if (CompGuess == 2 && PlayerGuess == 3)
{ // begin if
PlayerWin = true ; // Paper is cut by Scissors
alert('Player = Scissors' + '\n' + 'Computer = Paper' + '\n' 
     + 'Player Wins - Paper is cut by Scissors');
} // end if

if (CompGuess == 3 && PlayerGuess == 1)
{ // begin if
PlayerWin = true; // Scissors are blunted by Rock
alert('Player = Rock' + '\n' + 'Computer = Scissors' + '\n' 
     + 'Player Wins - Scissors are blunted by Rock');
alert();
} // end if

if (CompGuess == 3 && PlayerGuess == 2)
{ // begin if
CompWin = true; // Scissors cut Paper
alert('Player = Paper' + '\n' + 'Computer = Scissors' + '\n' 
     + 'Computer Wins - Scissors cut Paper');
} // end if

</script>
</head>
<body>
</body>
</html>

Next: Programming Challenge