Example Program 5 (Part 3)

We will examine the two main program functions first.

GetStartingValue ( )

This is the first function called by the main program and it is an important function because if offers the player a choice between the computer choosing a random number between 1 and 30 or the human player entering a number. The human player can type in any number they wish.

The variable choice is used to get the option required, for example, ‘Y’ or ‘N’. The value entered is changed to uppercase if required and then a selection construct contains the code for the computer generated value if the choice is ‘Y’ or the code to allow human entry of the starting value.

// Module Reference 1
function GetStartingValue ()
{ // begin GetStartingValue
var choice = 'N' ;

choice = prompt ('Should the computer choose a random starting value between 1 and 30?')

if (choice.toUpperCase() == 'Y')
{ // begin if
Total = Math.floor((Math.random() * 30) + 1) ;
} // end if
else
{ // begin else
// Get the starting value from the player
Total = prompt ('Enter a starting value: ') ;
} // end else

alert ('The starting value = ' + Total) ;
} // End GetStartingValue

PlayGame ( )

This is the main function of the program and it calls other functions to help it. The PlayGame ( ) function contains a while loop that will only end when the boolean variable GameOver is equal to true.

function PlayGame ()
{ // beging PlayGame

// Loop until one of the players wins
while (GameOver == false)
{ // begin while
PlayerID = 'Computer' ;
ComputersTurn () ;
CheckForWin (PlayerID) ;

// Player's turn
if (GameOver == false)
{ // begin if
PlayerID = 'Human' ;
PlayersTurn () ;
CheckForWin (PlayerID) ;
} // end if

} // end while - The while will terminate when GameOver is equal to true

} // end PlayGame

Note the use of == for comparison of the boolean variable GameOver to false.

Next: Example Program 5 (Part 4)