Game: Forty Thieves
In my
previous article I told about my problems with z coordinate in
Phaser. I got a suggestion which I have to investigate and probably I
will write about it in my future texts:
Thanks lumoludo.
Today I
would like to present my second game. Again, it is a solitaire card
game interpretation. And again, there are more websites which explains
Forty Thieves game rules in detail than you need.
So, lets dive into the code.
This
game is really fun from the code perspective:
first:
instead of click, this time I used drag;
second:
if user lets card go, it has to go back to its previous location;
third:
I also used double click;
four: I
have to add and remove click ability dynamically all the time;
fifth:
cards can be placed only on correct cards.
So
where would you like to start?
If you
read my first game article you do not need more explanation. I enable
ability to click and drag; change the cursor, that user would know,
he can click; add events for click, start drag and stop drag.
Now you can drag a card. What if you release the card in the middle of nowhere? Card has to go to its original location.
First
you have to save original card coordinates somewhere. You can not
save card coordinates on startDrag, because somebody can let
go the card and catch it (you would be in trouble). If you know where
you want to go it is easy: you can use tween movement like in
my previous article.
You drag the card to correct place. How do you know it’s correct place? You have to check if both cards fit each other according to the rules. How do you know which cards to check? You don’t.
As far
as I know card games do not use physics, so there is no such thing as
collision detection. Good news: Phaser allows to do the simpler
version of detection. So you take a cycle and check all cards for
collision.
Trust me this works. You get the bounds of each sprite and check if they intersect. But there is another trick. If you place the card on another two cards, collision will come back true for both. How do you know which one user wanted to choose? As I said, this game is fun from the coding perspective.
Phaser does not have double click event only click. What do we do? We fake it:
The
idea is: if you click fast enough we count it as double click. To do
that we need to know time-stamp of your current and previous click. I
didn’t think about it myself, I should give a mention where I found
it, but I can remember.