O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required