Node.js examples for Object:Constructor
Card Constructor, Deck Constructor And Player
// CARD CONSTRUCTOR function Card(value, suit) { this.value = value;// w w w . jav a2s . c om this.suit = suit; } // DECK CONSTRUCTOR function Deck() { this.buildDeck(); } /************* BEGIN Deck PROTOTYPES *************/ // BUILD DECK PROTOTYPE - MAKING THIS A PROTOTYPE ALLOWS US TO EASILY RESET THE DECK Deck.prototype.buildDeck = function(n=1) { var suits = new Array("Clubs", "Diamonds", "Hearts", "Spades"), values = new Array("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"), self = this; this.cards = []; // Fill the array with 'n' packs of cards. for (i = 0; i < n; i++){ suits.forEach(function(suit){ values.forEach(function(value){ self.cards.push(new Card(value, suit)); }); }); }; } // SHUFFLE PROTOTYPE Deck.prototype.shuffleDeck = function() { var unshuffledCards = this.cards.length, cardToShuffle, shuffleIndex; // While there remain elements to shuffle? while (unshuffledCards) { // Pick a remaining element? shuffleIndex = Math.floor(Math.random() * unshuffledCards--); // And swap it with the current element. cardToShuffle = this.cards[unshuffledCards]; this.cards[unshuffledCards] = this.cards[shuffleIndex]; this.cards[shuffleIndex] = cardToShuffle; } // return this; } //RESET DECK Deck.prototype.resetDeck = function() { this.buildDeck().shuffleDeck(); } // DEAL CARDS Deck.prototype.dealCards = function(n) { if (!n){ n = 1; }; var hand = []; // deal 'n' number of cards if (this.cards.length >= n) { for (var i = 0; i < n; i++){ var randomIndex = Math.floor((Math.random() * (this.cards.length))); hand.push((this.cards.splice(randomIndex, 1))); }; return hand; } else { return console.log("NOT ENOUGH CARDS REMAINING IN DECK TO DEAL THAT MANY CARDS");; } } /************* END Deck PROTOTYPES *************/ // PLAYER CONSTRUCTOR function Player(name){ this.name = name; this.hand = []; } /************* BEGIN Player PROTOTYPES *************/ Player.prototype.takeCard = function (deck) { this.hand.push(deck.dealCards()); return this; }; Player.prototype.discard = function (cardIdx) { if (this.hand.length < cardIdx){ this.hand.splice(cardIdx, 1); } return this; }; /************* BEGIN Player PROTOTYPES *************/ /** CONSTRUCT A DECK OF CARDS **/ var myDeck = new Deck(myDeck); /** SHUFFLE THE DECK OF CARDS **/ myDeck.shuffleDeck(); console.log(myDeck.cards); console.log(myDeck.cards.length); /** DEAL CARDS FROM THE DECK **/ console.log(myDeck.dealCards(5)); console.log(myDeck.cards.length); var bob = new Player('dominic') console.log(bob); bob.takeCard(myDeck) console.log(bob.myDeck);