5.10. Simulating Playing Cards

Problem

You want to use ActionScript to deal cards for a card game using a standard 52-card deck (without jokers).

Solution

Create a custom Cards class that uses the randRange( ) method to deal the cards.

Discussion

To work with playing cards within your Flash movies, you should create a custom Cards class. The Cards class should have an array property that contains all the cards in the deck and a deal( ) method that deals the cards to a specified number of players. Additionally, you should define a supporting class named CardPlayer. The CardPlayer class represents each player in a card game, including their hands of cards. Let’s take a look at the example code first:

// Include the Math.as file on whose methods this recipe relies.
#include "Math.as"

// When a new card player is created by way of its constructor, pass it a reference
// to the card deck and give it a unique player ID.
function CardPlayer (deck, id) {
  this.hand = null;
  this.deck = deck;
  this.id = id;
}

// The setHand(  ) method sets the cards in a player's hand.
CardPlayer.prototype.setHand = function (hand) {
  this.hand = hand;
};

// The getHand(  ) method returns the cards in a player's hand.
CardPlayer.prototype.getHand = function (  ) {
  return this.hand;
};

// The draw(  ) method deals the specified number of cards to the player.
CardPlayer.prototype.draw = function (num) {
  this.deck.draw(this.id, num);
};

// The discard(  ) method discards the cards specified // by their indexes in the ...

Get Actionscript Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.