Saturday, February 16, 2013

Game Reset

‹prev | My Chain | next›

With a reasonable Scoreboard implementation in place for 3D Game Programming for Kids, tonight I hope to put it through its paces. It should be able to display "Game Over" messages when the game is lost. It should display "Win!" when the game is won. It should support resetting the game at any point.

I already have "Game Over" working:

The Scoreboard work from last night makes this straight-forward:
  scoreboard.onTimeExpired(function() {
    scoreboard.setMessage("Game Over!");
Actually, winning the game is similarly easy to code up with last night's scoreboard work. A completed level with no more levels remaining results in a call to gameOver():
  function levelUp() {
    if (current_level >= levels.length) return gameOver();
If there is still time remaining on the scoreboard, then the scoreboard will display "Win!":
  function gameOver() {
    if (scoreboard.getTimeRemaining() > 0) scoreboard.setMessage('Win!');
    // ...
Even if the game is over for less desirable reasons, both the countdown and elapsed time timers are halted as well.

It takes some effort, but it is possible to win the game:

That leaves reset. The scoreboard does not support reset yet, nor does the elapsed timer that is used in the scoreboard. The countdown timer does already support reset so that it could be reset between levels. Adding the same ability to the elapsed timer is a matter of changing the start time and starting the clock anew:
__Timer.prototype.reset = function() {
  this._start = (new Date).getTime();
I also add a convenience method directly to the Scoreboard class to save on dots:
Scoreboard.prototype.resetTimer = function() {
With that, I can add a key handler so that "R" resets the game and the clocks on the scoreboard:
  document.addEventListener("keydown", function(event) {
    var code = event.keyCode;
    // ...
    if (code == 82) gameReset(); // R
  // ...

  function gameReset() {
    pause = false;
    current_level = -1;
There is no need to reset the countdown—the levelUp() function already does that.

I think that may do it for the Scoreboard class. I even have nice help, accessible with a press of the question mark:

Which is thanks to a simple call to the Scoreboard's help() method:
  var scoreboard = new Scoreboard();
    "Get the green ring. " +
    "Click and drag blue ramps. " +
    "Click and S to spin. " +
    "Regular R to restart. " +
    "Left and right arrows to move player. " +
    "Be quick!"
I will poke around a bit more tomorrow, but assuming all is good, it could be time to move on to other outstanding issues in the book, of which there are many.

(live code of the game)

Day #664

No comments:

Post a Comment