Saturday, October 6, 2018

4.8 Winning and Losing

As you know, the game ends when the last gem has been taken. Also obvious is the fact that there are two possible outcomes for this game. The player can win the game, or the computer can win the game. Knowing this, our movie is going to have to be able to handle either situation. This will require a bit of JavaScript. Here is the final version of the gemRemoved function with the new lines bolded.

function gemRemoved(gemCount) {
   if (gemCount <= gemsRemaining) {
          if (gemCount == 0) {
                 if (gamestate == GAMESTATE_PLAYER_ANIMATING)
          if (gamestate == GAMESTATE_PLAYER_ANIMATING)
          else {
                 gamestate = GAMESTATE_PLAYER_PLAYING;
Both sequences start out with the final gem growing larger while moving to the left side of the screen. This is a simple scaling operation combined with a movement operation. The end result is shown in the image below.

To keep the code simple, the end sequence will simply display the results for a few seconds before returning to the title screen. An alternative approach would be to have a button that the user clicks to return to the title screen. To return to the title screen we simply call a returnToTitle function at the end of the winning screen and at the end of the losing screen.
The line of code that needs to be added to both:


Finally, we need a function in the global script called returnToTitle that actually does the work:

function returnToTitle() {

And now we have a our completed NIM game!

No comments: