For now we will consider moving just the exposed bottom card of a column. The first requirement is to add the event listener to the canvas as the last statement in function Spider()
:
GAME.cnv.addEventListener ("click", onClick);
That implies we need to write the handler, called onClick. It is providing behaviour specific to Spider so it goes in spiderA.js:
function onClick (e)
{ var xy = getMousePoint (e);
var target = findTarget (xy.x, xy.y, GAME.targets);
if (null === target) return;
var card = target.card;
if (!card.faceUp) return;
for (const COL of GAME.COLUMNS)
{ var last = COL.getLastCard ();
if (null !== last)
{ if (last.suit === card.suit && last.value - 1 === card.value)
{ card.column.removeCard (card);
COL.addCard (card);
GAME.game.draw ();
return;
} } } // Not exact match, so try value match only (not suit):
for (const COL of GAME.COLUMNS)
{ var last = COL.getLastCard ();
if (null !== last)
{ if (last.value - 1 === card.value)
{ card.column.removeCard (card);
COL.addCard (card);
GAME.game.draw ();
return;
} } } // Is there an empty column to move to?
for (const COL of GAME.COLUMNS)
{ if (null === COL.getLastCard ())
{ card.column.removeCard (card);
COL.addCard (card);
GAME.game.draw ();
return;
} }
}
There are 3 passes through the array of columns. First we test for a last card matching the suit of the clicked card and value one higher. If that pass fails we look for a last card just one higher in value. If that fails try looking for an empty column to move to.
All of that just needs 2 new methods for Column
: getLastCard()
, which returns null
for an empty column, and removeCard (card)
.
Column.prototype.getLastCard = function ()
{ if (this.CARDS.length > 0)
return this.CARDS [this.CARDS.length - 1];
else return null;
};
Column.prototype.removeCard = function (card)
{ this.CARDS.splice (card.columnIndex, 1);
var card = this.getLastCard ();
if (null !== card) card.reveal ();
};
Now you should be able to click or touch the last card of a column and, if there is a suitable card as the last one in another column, the clicked card will move onto it.