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 theMath.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; } // ThesetHand( )
method sets the cards in a player's hand. CardPlayer.prototype.setHand = function (hand) { this.hand = hand; }; // ThegetHand( )
method returns the cards in a player's hand. CardPlayer.prototype.getHand = function ( ) { return this.hand; }; // Thedraw( )
method deals the specified number of cards to the player. CardPlayer.prototype.draw = function (num) { this.deck.draw(this.id, num); }; // Thediscard( )
method discards the cards specified // by their indexes in the ...
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.