Skip to content

Instantly share code, notes, and snippets.

@acr13
Created January 30, 2017 21:19
Show Gist options
  • Save acr13/431f62d67f086d73c69df05dfff1a1de to your computer and use it in GitHub Desktop.
Save acr13/431f62d67f086d73c69df05dfff1a1de to your computer and use it in GitHub Desktop.
const R = require('ramda');
const NUM_CARDS_IN_DECK = 52;
const NUM_CARDS_PER_PLAYER = 2;
const NUM_PLAYERS = 2;
const possibleValues = [
'2', '3', '4', '5', '6', '7', '8', '9',
'10', 'J', 'Q', 'K', 'A'
];
const possibleSuits = ['♣', '♠', '♥', '♦'];
const cards = R.xprod(possibleValues, possibleSuits);
const getRandomIndex = max => Math.floor(Math.random() * max);
const shuffle = deck => {
let deckToTakeFrom = R.clone(deck);
let shuffled = [];
while (shuffled.length < NUM_CARDS_IN_DECK) {
let cardIdx = getRandomIndex(deckToTakeFrom.length);
let card = R.nth(cardIdx, deckToTakeFrom);
deckToTakeFrom = R.remove(cardIdx, 1, deckToTakeFrom);
shuffled.push(card);
}
return shuffled;
};
// setup
let shuffledCards = shuffle(cards);
let currentHands = [...new Array(NUM_PLAYERS)].map(hand => []);
// deal
while (shuffledCards.length > (NUM_CARDS_IN_DECK - (NUM_CARDS_PER_PLAYER * NUM_PLAYERS))) {
currentHands = currentHands.map(hand => {
let cardIdx = getRandomIndex(shuffle.length);
let card = R.nth(cardIdx, shuffledCards);
shuffledCards = R.remove(cardIdx, 1, shuffledCards);
return R.append(card, hand);
});
}
let state = {
hands: currentHands,
deck: shuffledCards,
round: 1,
table: [],
discard: []
};
// play
const discardOneCard = state => {
const cardIdx = getRandomIndex(state.deck.length);
const discard = R.nth(cardIdx, state.deck);
// remove the discard from the deck
// add it to the discard pile
state = R.assoc('deck', R.remove(cardIdx, 1, state.deck), state);
return R.assoc('discard', R.append(discard, state.discard), state);
};
const dealTable = state => {
let numCardsToDeal = 1;
if (state.round === 1) { // flop
numCardsToDeal = 3;
}
while (numCardsToDeal > 0) {
const cardIdx = getRandomIndex(state.deck.length);
const card = R.nth(cardIdx, state.deck);
state = R.assoc('deck', R.remove(cardIdx, 1, state.deck), state);
state = R.assoc('table', R.append(card, state.table), state);
numCardsToDeal--;
}
return state;
};
const showBoard = state => {
console.log('Player 1:\t', state.hands[0][0][0] + state.hands[0][0][1], state.hands[0][1][0] + state.hands[0][1][1]);
console.log('Player 2:\t', state.hands[1][0][0] + state.hands[1][0][1], state.hands[1][1][0] + state.hands[1][1][1]);
console.log();
console.log('Table:\t', state.table.reduce((prev, curr) => prev += curr[0] + curr[1] + ' ', ''));
return state;
};
const finishRound = state => R.assoc('round', state.round + 1, state);
while (state.round <= 3) {
state = R.pipe(
discardOneCard,
dealTable,
showBoard,
finishRound
)(state);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment