Next Cycle
Previous Cycle
Back to Exercise Overview

Cycle 2: Register a CardListener to transfer cards, find and transfer pairs

The player that has the next move (the "current player") clicks on a particular partner's card to request it. The card is then moving visually from the partner's hand to the current player's hand. To perform this action, a CardListener is registered for each partner's hand. If you use the current player's hand location as target area, the card is moved to this location. Insert the following code in the for-loop of initHands() and see how it works:

if (i != 0)
{
  // Register CardListener
  hands[i].addCardListener(new CardAdapter()
  {
    public void leftDoubleClicked(Card card)
    {
      // Transfer double-clicked card to own hand
      card.getHand().setTargetArea(new TargetArea(handLocations[0]));
      card.transfer(hands[0], true);
      card.setVerso(false);

    }
  });
}

After the card is transferred to the current player's hand, the player checks, if he/she can discard any card pairs. If a pair is found, it is transferred to the player's stock. If we assume to have a method searchPairs(Hand hand) that returns an ArrayList with all card pairs found in the given hand, the code to transfer the cards in this array list is simple: add the following code in the leftDoubleClicked() callback:

// Search and transfer pairs to stock
for (Card c : searchPairs(hands[0]))
{
  hands[0].setTargetArea(new TargetArea(stockLocations[0]));
  c.transfer(stocks[0], false);
}
hands[0].draw();

Put an almost empty method

private ArrayList<Card> searchPairs(Hand hand)
{
  ArrayList<Card> list = new ArrayList<Card>();
  // TODO: Insert algorithm for finding pairs
  return list;
}

in your CardGame class and the application will compile and can be executed. You may include a System.out.println(hand) into your empty method to reassure you that all is well. It is now your task, to code the searchPairs() method. You may do it from scratch or use the getPairs() method from the class Hand.

Execute the solution you should obtain.

Next Cycle
Previous Cycle
Back to Exercise Overview