Next page | Contents page |

A specific game example: Spider

The aim is to make the JavaScript useable for various solitaire-type games but we need a specific example in order to have a complete runnable game. I have chosen Spider as the example.

In the usual fashion we will have a new file called spiderA.js in which we will have a function for constructing a single object, the behaviour (methods) of which will encapsulate the rules of this particular game.

The script elements in the HTML so far look like this:


    <script src="js/cardA.js"></script>
    <script src="js/deckA.js"></script>
    <script src="js/gameA.js"></script>
    <script src="js/spiderA.js"></script>

The ordering of those is not important because of the way our script is written inside functions, apart from the 2 global constants (GAME and SUITS). Nevertheless I like to list the scripts logically so that later ones are generally dependent on earlier ones.

To get the game started we need to add some statements to the run() function in gameA.js:


function run()
{ GAME.cnv = document.getElementById ("canvas");
  GAME.cnv.width = screen.availWidth;
  GAME.cnv.height = screen.availHeight;
  GAME.g2 = GAME.cnv.getContext ("2d");
  GAME.N_COLUMNS = 0; // To be set by particular game
  GAME.COLUMNS = [];
  
  // A specific game to use this framework:
  GAME.game = new Spider ();

  GAME.game.deal ();
  GAME.game.draw ();
}

Why call it GAME.game rather than GAME.spider?

So that if we want to use as much as possible of the same code for other games there is only one line to change. We might have:


  GAME.game = new Freecell ();

With the new code in run() we are also saying that any game-specific object must have methods deal() and draw(). In some programming languages we would write a file called an interface to specify what every specific game must implement but in JS it is not necessary.

Spider lays cards out in 10 columns, so initially spiderA.js will contain the following.


function Spider ()
{ GAME.deck = new Deck (2, 0);// 2 packs, no jokers
  GAME.deck.shuffle ();
  GAME.N_COLUMNS = 10;
  const COL_WIDTH = (GAME.cnv.width - 40) / (GAME.N_COLUMNS + 1);
  // - 40 allows some margin, + 1 allows space for the remainder pile
  // TO DO: create columns - in a later page
}

Spider.prototype.deal = function ()
{ // TO DO
}

Spider.prototype.draw = function ()
{ // TO DO
}

Notice the 11th column, left empty for now but the remainder pile will go there and so will complete suits when they can be removed from the game.

Next page | Contents page |