Created
September 22, 2015 23:24
-
-
Save Nilpo/7a92c0601b5d9b079cf2 to your computer and use it in GitHub Desktop.
Playing Cards in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create a function for shuffling the elements in an array | |
Array.prototype.shuffle = function(repeat) { | |
repeat = (repeat === undefined) ? 1 : repeat; | |
for (var i = 0; i < repeat; i++) { | |
// Implement the Fisher-Yates Shuffle | |
var currentIndex = this.length, temporaryValue, randomIndex; | |
// While there remains elements to shuffle... | |
while (0 !== currentIndex) { | |
// Pick a remaining element... | |
randomIndex = Math.floor(Math.random() * currentIndex); | |
currentIndex -= 1; | |
// And swap it with the current element. | |
temporaryValue = this[currentIndex]; | |
this[currentIndex] = this[randomIndex]; | |
this[randomIndex] = temporaryValue; | |
} | |
} | |
return this; | |
}; | |
// Let's have some fun | |
// Establish the values and suits in a deck of playing cards | |
var ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']; | |
var suits = ['♠', '♡', '♢', '♣']; | |
// Adds all 52 standard cards to a deck | |
var resetDeck = function(deck) { | |
deck = []; | |
suits.forEach(function(suit) { | |
ranks.forEach(function(rank) { | |
deck.push(rank + suit); | |
}); | |
}); | |
return deck; | |
}; | |
// Deals a given number of cards from the top of the deck | |
var deal = function(limit) { | |
return deck.splice(0, limit); | |
}; | |
// Let's play a game | |
// Start with five empty hands | |
var hand1 = hand2 = hand3 = hand4 = hand5 = []; | |
var hands = { | |
0: hand1, | |
1: hand2, | |
2: hand3, | |
3: hand4, | |
4: hand5 | |
}; | |
// Reset and shuffle a deck of cards | |
var deck = resetDeck().shuffle(7); | |
// Deal five cards to each player | |
hands.forEach(function(hand) { | |
hand = deal(5); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment