Playing cards with ReactJS
Clash Royale CLAN TAG#URR8PPP
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;
up vote
0
down vote
favorite
I came across problem 54 on projecteuler.net and decided to give it a go using ReactJS. I have had Angular experience prior to this. I wrote a couple of fully tested components. I think that they only have one purpose each, but they're still very big. I did my best code-wise because it's also a project where I want to show off the things I learned from a programming book about clean code. Any feedback would be greatly appreciated. I'll start with the first component I created and end it with the last.
Playing card
import React from 'react';
import propTypes from 'prop-types';
import isNumeric from '../../Helper';
import './Playing-Card.scss';
const cardSuites =
D: 'diamonds',
S: 'spades',
H: 'hearts',
C: 'clubs',
;
const cardCourts =
K: 'king',
J: 'jack',
Q: 'queen',
A: 'ace',
T: '10',
;
const cardValues =
ace: '14',
king: '13',
queen: '12',
jack: '11',
;
const PlayingCard = ( cardSymbol ) =>
const url = convertCardSymbolToUrl(cardSymbol);
return <img alt="playing-card" className="playing-card" src=url />;
;
PlayingCard.propTypes = cardSymbol: propTypes.string.isRequired ;
export const convertCardSymbolToUrl = cardSymbol => `/cards/$getCardCourt(cardSymbol)_of_$getCardSuite(cardSymbol).svg`;
export const getCardSuite = cardSymbol => cardSuites[cardSymbol[1]];
export const getCardCourt = cardSymbol =>
const courtSymbol = cardSymbol[0];
if (isNumeric(courtSymbol))
return String(courtSymbol);
return String(cardCourts[courtSymbol]);
;
export const getCardValue = cardCourt =>
if (isNumeric(cardCourt))
return Number(cardCourt);
return Number(cardValues[cardCourt]);
;
export default PlayingCard;
Hand
import React from 'react';
import propTypes from 'prop-types';
import generateUniqueKeysForItems from '../../Helper';
import PlayingCard, getCardCourt, getCardValue, getCardSuite from '../Playing-Card/Playing-Card';
const Hand = ( cards ) =>
let cardsArray = cards.split(' ');
cardsArray = generateUniqueKeysForItems(cardsArray);
return cardsArray.map(card => <PlayingCard key=card.id cardSymbol=card.value />);
;
Hand.propTypes = cards: propTypes.string.isRequired ;
export const calculateHandValue = cardsArray =>
let cardsFrequency = calculateCardsFrequency(cardsArray);
cardsFrequency = sortFrequencyDesc(cardsFrequency);
const individualCardValues = calculateIndividualCardValues(cardsFrequency);
let handValue = 9;
const cardsCombinations = [
hasRoyalFlush,
hasStraightFlush,
hasFourOfAKind,
hasFullHouse,
hasFlush,
hasStraight,
hasThreeOfAKind,
hasTwoPairs,
hasTwoOfAKind,
];
for (let i = 0; i < cardsCombinations.length; i += 1)
const isCombinationValid = cardsCombinations[i];
if (isCombinationValid(cardsArray))
break;
handValue -= 1;
return [handValue, individualCardValues];
;
export const calculateIndividualCardValues = cardsFrequency =>
Array.from(cardsFrequency.keys()).map(key => getCardValue(key));
export const hasRoyalFlush = cardsArray =>
const cardCourtsRequired = ['10', 'jack', 'queen', 'king', 'ace'];
let qualifies = true;
if (!hasSameSuits(cardsArray))
return false;
cardsArray.forEach(card =>
const court = getCardCourt(card);
if (cardCourtsRequired.indexOf(court) === -1)
qualifies = false;
);
return qualifies;
;
export const hasStraightFlush = cardsArray =>
hasSameSuits(cardsArray) && hasIncrementalCourts(cardsArray);
export const hasStraight = cardsArray => hasIncrementalCourts(cardsArray);
export const hasFlush = cardsArray => hasSameSuits(cardsArray);
export const hasFourOfAKind = cardsArray => hasXOfAKind(cardsArray, 4);
export const hasThreeOfAKind = cardsArray => hasXOfAKind(cardsArray, 3);
export const hasTwoOfAKind = cardsArray => hasXOfAKind(cardsArray, 2);
const hasXOfAKind = (cardsArray, x) =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
return frequencyArray.indexOf(x) !== -1;
;
export const hasTwoPairs = cardsArray =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
let numberOfPairs = 0;
frequencyArray.forEach(frequencyNumber =>
if (frequencyNumber === 2)
numberOfPairs += 1;
);
return numberOfPairs === 2;
;
export const hasFullHouse = cardsArray =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
return frequencyArray.indexOf(3) !== -1 && frequencyArray.indexOf(2) !== -1;
;
export const hasSameSuits = cardsArray =>
const hasEqualSuits = (card1, card2) => getCardSuite(card1) === getCardSuite(card2);
for (let i = 1; i < cardsArray.length; i += 1)
const card = cardsArray[i];
const previousCard = cardsArray[i - 1];
if (!hasEqualSuits(card, previousCard))
return false;
return true;
;
export const hasIncrementalCourts = cardsArray =>
const hasIncrementalCardValues = (card1, card2) =>
getCardValue(getCardCourt(card1)) + 1 === getCardValue(getCardCourt(card2));
const sortedCards = sortByCardValueAsc(cardsArray);
for (let i = 1; i < sortedCards.length; i += 1)
const card = sortedCards[i];
const previousCard = sortedCards[i - 1];
if (!hasIncrementalCardValues(previousCard, card))
return false;
return true;
;
export const calculateCardsFrequency = cardsArray =>
const cardFrequency = new Map();
cardsArray.forEach(card =>
const court = String(getCardCourt(card));
if (cardFrequency.get(court) != null)
cardFrequency.set(court, cardFrequency.get(court) + 1);
else
cardFrequency.set(court, 1);
);
return cardFrequency;
;
export const sortFrequencyDesc = cardsFrequency =>
new Map([...cardsFrequency.entries()].sort((a, b) =>
const aCardCourt = a[0];
const aFrequency = a[1];
const bCardCourt = b[0];
const bFrequency = b[1];
if (aFrequency < bFrequency)
return 1;
if (aFrequency === bFrequency && getCardValue(aCardCourt) < getCardValue(bCardCourt))
return 1;
return -1;
));
export const sortByCardValueAsc = cardsArray =>
cardsArray.sort((card1, card2) =>
const court1 = getCardCourt(card1);
const court2 = getCardCourt(card2);
if (getCardValue(court1) > getCardValue(court2))
return 1;
if (getCardValue(court1) < getCardValue(court2))
return -1;
return 0;
);
return cardsArray;
;
export default Hand;
Round
import React from 'react';
import propTypes from 'prop-types';
import connect from 'react-redux';
import Hand, calculateHandValue from '../Hand/Hand';
import './Round.scss';
const Round = ( cards, incrementScore ) =>
const playerHands = splitCards(cards);
if (playerHands[0] === '')
return <div />;
const winner = determineWinner(playerHands[0], playerHands[1]);
incrementScore(`player$winner`);
return (
<div className="round-root">
<div className=(winner === 1) ? 'winner' : ''>
<Hand cards=playerHands[0] />
</div>
<div className=(winner === 2) ? 'winner' : ''>
<Hand cards=playerHands[1] />
</div>
</div>
);
;
Round.propTypes =
cards: propTypes.string.isRequired,
incrementScore: propTypes.func.isRequired,
;
const mapStateToProps = state => ();
const mapDispatchToProps = dispatch => (
incrementScore: playerName =>
dispatch(
type: 'INCREMENT_SCORE',
payload:
name: playerName,
,
);
,
);
export const splitCards = cards =>
const playerHands = ;
playerHands.push(cards.substr(0, Math.ceil(cards.length / 2) - 1));
playerHands.push(cards.substr(Math.ceil(cards.length / 2)));
return playerHands;
;
export const determineWinner = (player1Cards, player2Cards) =>
const p1HandValue = calculateHandValue(player1Cards.split(' '));
const p2HandValue = calculateHandValue(player2Cards.split(' '));
let winner = compareFirstTuples(p1HandValue, p2HandValue);
if (winner === 0)
winner = compareSecondTuples(p1HandValue, p2HandValue);
if (winner === 0)
throw Error('No winner could be determined');
return winner;
;
export const compareFirstTuples = (p1HandValue, p2HandValue) =>
if (p1HandValue[0] === p2HandValue[0]) return 0;
return (p1HandValue[0] > p2HandValue[0]) ? 1 : 2;
;
export const compareSecondTuples = (p1HandValue, p2HandValue) =>
const p1Tuple = p1HandValue[1];
const p2Tuple = p2HandValue[1];
let winner = 0;
const minLength = Math.min(p1Tuple.length, p2Tuple.length);
for (let i = 0; i < minLength; i += 1)
if (p1Tuple[i] > p2Tuple[i])
winner = 1;
break;
if (p1Tuple[i] < p2Tuple[i])
winner = 2;
break;
return winner;
;
export default connect(mapStateToProps, mapDispatchToProps)(Round);
Game-Room
import React from 'react';
import propTypes from 'prop-types';
import Button from '@material-ui/core/Button';
import './Game-Room.scss';
import connect from 'react-redux';
import Game from '../Game/Game';
import WinnerDetails from '../Winner-Details/Winner-Details';
const possibleSuits = ['D', 'S', 'H', 'C'];
const possibleCourts = ['2', '3', '4', '5', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'];
const GameRoom = ( setMatches, matches, players, resetScore ) => ;
GameRoom.propTypes =
setMatches: propTypes.func.isRequired,
resetScore: propTypes.func.isRequired,
players: propTypes.shape().isRequired,
matches: propTypes.arrayOf(propTypes.string).isRequired,
;
const mapStateToProps = state => (
matches: state.gamesReducer,
players: state.playerReducer,
);
const mapDispatchToProps = dispatch => (
setMatches: games =>
dispatch(
type: 'SET_GAMES',
payload: games,
);
,
resetScore: () =>
dispatch(
type: 'RESET_SCORE',
);
,
);
export const generateMatches = numberOfGames =>
const games = ;
for (let i = 0; i < numberOfGames; i += 1)
const round = generateRound();
games.push(round);
return games;
;
export const generateRound = () =>
let cards = '';
let numberOfCards = 0;
while (numberOfCards < 10)
const card = createRandomCard();
if (cards.indexOf(card) === -1)
cards += `$card `;
numberOfCards += 1;
cards = cards.slice(0, -1);
return cards;
;
const createRandomCard = () => getRandomCourt() + getRandomSuit();
const getRandomSuit = () => possibleSuits[Math.floor(Math.random() * possibleSuits.length)];
const getRandomCourt = () => possibleCourts[Math.floor(Math.random() * possibleCourts.length)];
export default connect(mapStateToProps, mapDispatchToProps)(GameRoom);
Components Winner-detail and Game are emitted because they're small enough. Game is just a container for rounds.
javascript algorithm playing-cards react.js redux
add a comment |Â
up vote
0
down vote
favorite
I came across problem 54 on projecteuler.net and decided to give it a go using ReactJS. I have had Angular experience prior to this. I wrote a couple of fully tested components. I think that they only have one purpose each, but they're still very big. I did my best code-wise because it's also a project where I want to show off the things I learned from a programming book about clean code. Any feedback would be greatly appreciated. I'll start with the first component I created and end it with the last.
Playing card
import React from 'react';
import propTypes from 'prop-types';
import isNumeric from '../../Helper';
import './Playing-Card.scss';
const cardSuites =
D: 'diamonds',
S: 'spades',
H: 'hearts',
C: 'clubs',
;
const cardCourts =
K: 'king',
J: 'jack',
Q: 'queen',
A: 'ace',
T: '10',
;
const cardValues =
ace: '14',
king: '13',
queen: '12',
jack: '11',
;
const PlayingCard = ( cardSymbol ) =>
const url = convertCardSymbolToUrl(cardSymbol);
return <img alt="playing-card" className="playing-card" src=url />;
;
PlayingCard.propTypes = cardSymbol: propTypes.string.isRequired ;
export const convertCardSymbolToUrl = cardSymbol => `/cards/$getCardCourt(cardSymbol)_of_$getCardSuite(cardSymbol).svg`;
export const getCardSuite = cardSymbol => cardSuites[cardSymbol[1]];
export const getCardCourt = cardSymbol =>
const courtSymbol = cardSymbol[0];
if (isNumeric(courtSymbol))
return String(courtSymbol);
return String(cardCourts[courtSymbol]);
;
export const getCardValue = cardCourt =>
if (isNumeric(cardCourt))
return Number(cardCourt);
return Number(cardValues[cardCourt]);
;
export default PlayingCard;
Hand
import React from 'react';
import propTypes from 'prop-types';
import generateUniqueKeysForItems from '../../Helper';
import PlayingCard, getCardCourt, getCardValue, getCardSuite from '../Playing-Card/Playing-Card';
const Hand = ( cards ) =>
let cardsArray = cards.split(' ');
cardsArray = generateUniqueKeysForItems(cardsArray);
return cardsArray.map(card => <PlayingCard key=card.id cardSymbol=card.value />);
;
Hand.propTypes = cards: propTypes.string.isRequired ;
export const calculateHandValue = cardsArray =>
let cardsFrequency = calculateCardsFrequency(cardsArray);
cardsFrequency = sortFrequencyDesc(cardsFrequency);
const individualCardValues = calculateIndividualCardValues(cardsFrequency);
let handValue = 9;
const cardsCombinations = [
hasRoyalFlush,
hasStraightFlush,
hasFourOfAKind,
hasFullHouse,
hasFlush,
hasStraight,
hasThreeOfAKind,
hasTwoPairs,
hasTwoOfAKind,
];
for (let i = 0; i < cardsCombinations.length; i += 1)
const isCombinationValid = cardsCombinations[i];
if (isCombinationValid(cardsArray))
break;
handValue -= 1;
return [handValue, individualCardValues];
;
export const calculateIndividualCardValues = cardsFrequency =>
Array.from(cardsFrequency.keys()).map(key => getCardValue(key));
export const hasRoyalFlush = cardsArray =>
const cardCourtsRequired = ['10', 'jack', 'queen', 'king', 'ace'];
let qualifies = true;
if (!hasSameSuits(cardsArray))
return false;
cardsArray.forEach(card =>
const court = getCardCourt(card);
if (cardCourtsRequired.indexOf(court) === -1)
qualifies = false;
);
return qualifies;
;
export const hasStraightFlush = cardsArray =>
hasSameSuits(cardsArray) && hasIncrementalCourts(cardsArray);
export const hasStraight = cardsArray => hasIncrementalCourts(cardsArray);
export const hasFlush = cardsArray => hasSameSuits(cardsArray);
export const hasFourOfAKind = cardsArray => hasXOfAKind(cardsArray, 4);
export const hasThreeOfAKind = cardsArray => hasXOfAKind(cardsArray, 3);
export const hasTwoOfAKind = cardsArray => hasXOfAKind(cardsArray, 2);
const hasXOfAKind = (cardsArray, x) =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
return frequencyArray.indexOf(x) !== -1;
;
export const hasTwoPairs = cardsArray =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
let numberOfPairs = 0;
frequencyArray.forEach(frequencyNumber =>
if (frequencyNumber === 2)
numberOfPairs += 1;
);
return numberOfPairs === 2;
;
export const hasFullHouse = cardsArray =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
return frequencyArray.indexOf(3) !== -1 && frequencyArray.indexOf(2) !== -1;
;
export const hasSameSuits = cardsArray =>
const hasEqualSuits = (card1, card2) => getCardSuite(card1) === getCardSuite(card2);
for (let i = 1; i < cardsArray.length; i += 1)
const card = cardsArray[i];
const previousCard = cardsArray[i - 1];
if (!hasEqualSuits(card, previousCard))
return false;
return true;
;
export const hasIncrementalCourts = cardsArray =>
const hasIncrementalCardValues = (card1, card2) =>
getCardValue(getCardCourt(card1)) + 1 === getCardValue(getCardCourt(card2));
const sortedCards = sortByCardValueAsc(cardsArray);
for (let i = 1; i < sortedCards.length; i += 1)
const card = sortedCards[i];
const previousCard = sortedCards[i - 1];
if (!hasIncrementalCardValues(previousCard, card))
return false;
return true;
;
export const calculateCardsFrequency = cardsArray =>
const cardFrequency = new Map();
cardsArray.forEach(card =>
const court = String(getCardCourt(card));
if (cardFrequency.get(court) != null)
cardFrequency.set(court, cardFrequency.get(court) + 1);
else
cardFrequency.set(court, 1);
);
return cardFrequency;
;
export const sortFrequencyDesc = cardsFrequency =>
new Map([...cardsFrequency.entries()].sort((a, b) =>
const aCardCourt = a[0];
const aFrequency = a[1];
const bCardCourt = b[0];
const bFrequency = b[1];
if (aFrequency < bFrequency)
return 1;
if (aFrequency === bFrequency && getCardValue(aCardCourt) < getCardValue(bCardCourt))
return 1;
return -1;
));
export const sortByCardValueAsc = cardsArray =>
cardsArray.sort((card1, card2) =>
const court1 = getCardCourt(card1);
const court2 = getCardCourt(card2);
if (getCardValue(court1) > getCardValue(court2))
return 1;
if (getCardValue(court1) < getCardValue(court2))
return -1;
return 0;
);
return cardsArray;
;
export default Hand;
Round
import React from 'react';
import propTypes from 'prop-types';
import connect from 'react-redux';
import Hand, calculateHandValue from '../Hand/Hand';
import './Round.scss';
const Round = ( cards, incrementScore ) =>
const playerHands = splitCards(cards);
if (playerHands[0] === '')
return <div />;
const winner = determineWinner(playerHands[0], playerHands[1]);
incrementScore(`player$winner`);
return (
<div className="round-root">
<div className=(winner === 1) ? 'winner' : ''>
<Hand cards=playerHands[0] />
</div>
<div className=(winner === 2) ? 'winner' : ''>
<Hand cards=playerHands[1] />
</div>
</div>
);
;
Round.propTypes =
cards: propTypes.string.isRequired,
incrementScore: propTypes.func.isRequired,
;
const mapStateToProps = state => ();
const mapDispatchToProps = dispatch => (
incrementScore: playerName =>
dispatch(
type: 'INCREMENT_SCORE',
payload:
name: playerName,
,
);
,
);
export const splitCards = cards =>
const playerHands = ;
playerHands.push(cards.substr(0, Math.ceil(cards.length / 2) - 1));
playerHands.push(cards.substr(Math.ceil(cards.length / 2)));
return playerHands;
;
export const determineWinner = (player1Cards, player2Cards) =>
const p1HandValue = calculateHandValue(player1Cards.split(' '));
const p2HandValue = calculateHandValue(player2Cards.split(' '));
let winner = compareFirstTuples(p1HandValue, p2HandValue);
if (winner === 0)
winner = compareSecondTuples(p1HandValue, p2HandValue);
if (winner === 0)
throw Error('No winner could be determined');
return winner;
;
export const compareFirstTuples = (p1HandValue, p2HandValue) =>
if (p1HandValue[0] === p2HandValue[0]) return 0;
return (p1HandValue[0] > p2HandValue[0]) ? 1 : 2;
;
export const compareSecondTuples = (p1HandValue, p2HandValue) =>
const p1Tuple = p1HandValue[1];
const p2Tuple = p2HandValue[1];
let winner = 0;
const minLength = Math.min(p1Tuple.length, p2Tuple.length);
for (let i = 0; i < minLength; i += 1)
if (p1Tuple[i] > p2Tuple[i])
winner = 1;
break;
if (p1Tuple[i] < p2Tuple[i])
winner = 2;
break;
return winner;
;
export default connect(mapStateToProps, mapDispatchToProps)(Round);
Game-Room
import React from 'react';
import propTypes from 'prop-types';
import Button from '@material-ui/core/Button';
import './Game-Room.scss';
import connect from 'react-redux';
import Game from '../Game/Game';
import WinnerDetails from '../Winner-Details/Winner-Details';
const possibleSuits = ['D', 'S', 'H', 'C'];
const possibleCourts = ['2', '3', '4', '5', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'];
const GameRoom = ( setMatches, matches, players, resetScore ) => ;
GameRoom.propTypes =
setMatches: propTypes.func.isRequired,
resetScore: propTypes.func.isRequired,
players: propTypes.shape().isRequired,
matches: propTypes.arrayOf(propTypes.string).isRequired,
;
const mapStateToProps = state => (
matches: state.gamesReducer,
players: state.playerReducer,
);
const mapDispatchToProps = dispatch => (
setMatches: games =>
dispatch(
type: 'SET_GAMES',
payload: games,
);
,
resetScore: () =>
dispatch(
type: 'RESET_SCORE',
);
,
);
export const generateMatches = numberOfGames =>
const games = ;
for (let i = 0; i < numberOfGames; i += 1)
const round = generateRound();
games.push(round);
return games;
;
export const generateRound = () =>
let cards = '';
let numberOfCards = 0;
while (numberOfCards < 10)
const card = createRandomCard();
if (cards.indexOf(card) === -1)
cards += `$card `;
numberOfCards += 1;
cards = cards.slice(0, -1);
return cards;
;
const createRandomCard = () => getRandomCourt() + getRandomSuit();
const getRandomSuit = () => possibleSuits[Math.floor(Math.random() * possibleSuits.length)];
const getRandomCourt = () => possibleCourts[Math.floor(Math.random() * possibleCourts.length)];
export default connect(mapStateToProps, mapDispatchToProps)(GameRoom);
Components Winner-detail and Game are emitted because they're small enough. Game is just a container for rounds.
javascript algorithm playing-cards react.js redux
Please post a short problem description along with your question. Otherwise, it will be hard for us to judge your code properly with regards to correctness and suitability for the problem at hand, among other characteristics.
â Ben Steffan
Jul 29 at 23:34
add a comment |Â
up vote
0
down vote
favorite
up vote
0
down vote
favorite
I came across problem 54 on projecteuler.net and decided to give it a go using ReactJS. I have had Angular experience prior to this. I wrote a couple of fully tested components. I think that they only have one purpose each, but they're still very big. I did my best code-wise because it's also a project where I want to show off the things I learned from a programming book about clean code. Any feedback would be greatly appreciated. I'll start with the first component I created and end it with the last.
Playing card
import React from 'react';
import propTypes from 'prop-types';
import isNumeric from '../../Helper';
import './Playing-Card.scss';
const cardSuites =
D: 'diamonds',
S: 'spades',
H: 'hearts',
C: 'clubs',
;
const cardCourts =
K: 'king',
J: 'jack',
Q: 'queen',
A: 'ace',
T: '10',
;
const cardValues =
ace: '14',
king: '13',
queen: '12',
jack: '11',
;
const PlayingCard = ( cardSymbol ) =>
const url = convertCardSymbolToUrl(cardSymbol);
return <img alt="playing-card" className="playing-card" src=url />;
;
PlayingCard.propTypes = cardSymbol: propTypes.string.isRequired ;
export const convertCardSymbolToUrl = cardSymbol => `/cards/$getCardCourt(cardSymbol)_of_$getCardSuite(cardSymbol).svg`;
export const getCardSuite = cardSymbol => cardSuites[cardSymbol[1]];
export const getCardCourt = cardSymbol =>
const courtSymbol = cardSymbol[0];
if (isNumeric(courtSymbol))
return String(courtSymbol);
return String(cardCourts[courtSymbol]);
;
export const getCardValue = cardCourt =>
if (isNumeric(cardCourt))
return Number(cardCourt);
return Number(cardValues[cardCourt]);
;
export default PlayingCard;
Hand
import React from 'react';
import propTypes from 'prop-types';
import generateUniqueKeysForItems from '../../Helper';
import PlayingCard, getCardCourt, getCardValue, getCardSuite from '../Playing-Card/Playing-Card';
const Hand = ( cards ) =>
let cardsArray = cards.split(' ');
cardsArray = generateUniqueKeysForItems(cardsArray);
return cardsArray.map(card => <PlayingCard key=card.id cardSymbol=card.value />);
;
Hand.propTypes = cards: propTypes.string.isRequired ;
export const calculateHandValue = cardsArray =>
let cardsFrequency = calculateCardsFrequency(cardsArray);
cardsFrequency = sortFrequencyDesc(cardsFrequency);
const individualCardValues = calculateIndividualCardValues(cardsFrequency);
let handValue = 9;
const cardsCombinations = [
hasRoyalFlush,
hasStraightFlush,
hasFourOfAKind,
hasFullHouse,
hasFlush,
hasStraight,
hasThreeOfAKind,
hasTwoPairs,
hasTwoOfAKind,
];
for (let i = 0; i < cardsCombinations.length; i += 1)
const isCombinationValid = cardsCombinations[i];
if (isCombinationValid(cardsArray))
break;
handValue -= 1;
return [handValue, individualCardValues];
;
export const calculateIndividualCardValues = cardsFrequency =>
Array.from(cardsFrequency.keys()).map(key => getCardValue(key));
export const hasRoyalFlush = cardsArray =>
const cardCourtsRequired = ['10', 'jack', 'queen', 'king', 'ace'];
let qualifies = true;
if (!hasSameSuits(cardsArray))
return false;
cardsArray.forEach(card =>
const court = getCardCourt(card);
if (cardCourtsRequired.indexOf(court) === -1)
qualifies = false;
);
return qualifies;
;
export const hasStraightFlush = cardsArray =>
hasSameSuits(cardsArray) && hasIncrementalCourts(cardsArray);
export const hasStraight = cardsArray => hasIncrementalCourts(cardsArray);
export const hasFlush = cardsArray => hasSameSuits(cardsArray);
export const hasFourOfAKind = cardsArray => hasXOfAKind(cardsArray, 4);
export const hasThreeOfAKind = cardsArray => hasXOfAKind(cardsArray, 3);
export const hasTwoOfAKind = cardsArray => hasXOfAKind(cardsArray, 2);
const hasXOfAKind = (cardsArray, x) =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
return frequencyArray.indexOf(x) !== -1;
;
export const hasTwoPairs = cardsArray =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
let numberOfPairs = 0;
frequencyArray.forEach(frequencyNumber =>
if (frequencyNumber === 2)
numberOfPairs += 1;
);
return numberOfPairs === 2;
;
export const hasFullHouse = cardsArray =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
return frequencyArray.indexOf(3) !== -1 && frequencyArray.indexOf(2) !== -1;
;
export const hasSameSuits = cardsArray =>
const hasEqualSuits = (card1, card2) => getCardSuite(card1) === getCardSuite(card2);
for (let i = 1; i < cardsArray.length; i += 1)
const card = cardsArray[i];
const previousCard = cardsArray[i - 1];
if (!hasEqualSuits(card, previousCard))
return false;
return true;
;
export const hasIncrementalCourts = cardsArray =>
const hasIncrementalCardValues = (card1, card2) =>
getCardValue(getCardCourt(card1)) + 1 === getCardValue(getCardCourt(card2));
const sortedCards = sortByCardValueAsc(cardsArray);
for (let i = 1; i < sortedCards.length; i += 1)
const card = sortedCards[i];
const previousCard = sortedCards[i - 1];
if (!hasIncrementalCardValues(previousCard, card))
return false;
return true;
;
export const calculateCardsFrequency = cardsArray =>
const cardFrequency = new Map();
cardsArray.forEach(card =>
const court = String(getCardCourt(card));
if (cardFrequency.get(court) != null)
cardFrequency.set(court, cardFrequency.get(court) + 1);
else
cardFrequency.set(court, 1);
);
return cardFrequency;
;
export const sortFrequencyDesc = cardsFrequency =>
new Map([...cardsFrequency.entries()].sort((a, b) =>
const aCardCourt = a[0];
const aFrequency = a[1];
const bCardCourt = b[0];
const bFrequency = b[1];
if (aFrequency < bFrequency)
return 1;
if (aFrequency === bFrequency && getCardValue(aCardCourt) < getCardValue(bCardCourt))
return 1;
return -1;
));
export const sortByCardValueAsc = cardsArray =>
cardsArray.sort((card1, card2) =>
const court1 = getCardCourt(card1);
const court2 = getCardCourt(card2);
if (getCardValue(court1) > getCardValue(court2))
return 1;
if (getCardValue(court1) < getCardValue(court2))
return -1;
return 0;
);
return cardsArray;
;
export default Hand;
Round
import React from 'react';
import propTypes from 'prop-types';
import connect from 'react-redux';
import Hand, calculateHandValue from '../Hand/Hand';
import './Round.scss';
const Round = ( cards, incrementScore ) =>
const playerHands = splitCards(cards);
if (playerHands[0] === '')
return <div />;
const winner = determineWinner(playerHands[0], playerHands[1]);
incrementScore(`player$winner`);
return (
<div className="round-root">
<div className=(winner === 1) ? 'winner' : ''>
<Hand cards=playerHands[0] />
</div>
<div className=(winner === 2) ? 'winner' : ''>
<Hand cards=playerHands[1] />
</div>
</div>
);
;
Round.propTypes =
cards: propTypes.string.isRequired,
incrementScore: propTypes.func.isRequired,
;
const mapStateToProps = state => ();
const mapDispatchToProps = dispatch => (
incrementScore: playerName =>
dispatch(
type: 'INCREMENT_SCORE',
payload:
name: playerName,
,
);
,
);
export const splitCards = cards =>
const playerHands = ;
playerHands.push(cards.substr(0, Math.ceil(cards.length / 2) - 1));
playerHands.push(cards.substr(Math.ceil(cards.length / 2)));
return playerHands;
;
export const determineWinner = (player1Cards, player2Cards) =>
const p1HandValue = calculateHandValue(player1Cards.split(' '));
const p2HandValue = calculateHandValue(player2Cards.split(' '));
let winner = compareFirstTuples(p1HandValue, p2HandValue);
if (winner === 0)
winner = compareSecondTuples(p1HandValue, p2HandValue);
if (winner === 0)
throw Error('No winner could be determined');
return winner;
;
export const compareFirstTuples = (p1HandValue, p2HandValue) =>
if (p1HandValue[0] === p2HandValue[0]) return 0;
return (p1HandValue[0] > p2HandValue[0]) ? 1 : 2;
;
export const compareSecondTuples = (p1HandValue, p2HandValue) =>
const p1Tuple = p1HandValue[1];
const p2Tuple = p2HandValue[1];
let winner = 0;
const minLength = Math.min(p1Tuple.length, p2Tuple.length);
for (let i = 0; i < minLength; i += 1)
if (p1Tuple[i] > p2Tuple[i])
winner = 1;
break;
if (p1Tuple[i] < p2Tuple[i])
winner = 2;
break;
return winner;
;
export default connect(mapStateToProps, mapDispatchToProps)(Round);
Game-Room
import React from 'react';
import propTypes from 'prop-types';
import Button from '@material-ui/core/Button';
import './Game-Room.scss';
import connect from 'react-redux';
import Game from '../Game/Game';
import WinnerDetails from '../Winner-Details/Winner-Details';
const possibleSuits = ['D', 'S', 'H', 'C'];
const possibleCourts = ['2', '3', '4', '5', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'];
const GameRoom = ( setMatches, matches, players, resetScore ) => ;
GameRoom.propTypes =
setMatches: propTypes.func.isRequired,
resetScore: propTypes.func.isRequired,
players: propTypes.shape().isRequired,
matches: propTypes.arrayOf(propTypes.string).isRequired,
;
const mapStateToProps = state => (
matches: state.gamesReducer,
players: state.playerReducer,
);
const mapDispatchToProps = dispatch => (
setMatches: games =>
dispatch(
type: 'SET_GAMES',
payload: games,
);
,
resetScore: () =>
dispatch(
type: 'RESET_SCORE',
);
,
);
export const generateMatches = numberOfGames =>
const games = ;
for (let i = 0; i < numberOfGames; i += 1)
const round = generateRound();
games.push(round);
return games;
;
export const generateRound = () =>
let cards = '';
let numberOfCards = 0;
while (numberOfCards < 10)
const card = createRandomCard();
if (cards.indexOf(card) === -1)
cards += `$card `;
numberOfCards += 1;
cards = cards.slice(0, -1);
return cards;
;
const createRandomCard = () => getRandomCourt() + getRandomSuit();
const getRandomSuit = () => possibleSuits[Math.floor(Math.random() * possibleSuits.length)];
const getRandomCourt = () => possibleCourts[Math.floor(Math.random() * possibleCourts.length)];
export default connect(mapStateToProps, mapDispatchToProps)(GameRoom);
Components Winner-detail and Game are emitted because they're small enough. Game is just a container for rounds.
javascript algorithm playing-cards react.js redux
I came across problem 54 on projecteuler.net and decided to give it a go using ReactJS. I have had Angular experience prior to this. I wrote a couple of fully tested components. I think that they only have one purpose each, but they're still very big. I did my best code-wise because it's also a project where I want to show off the things I learned from a programming book about clean code. Any feedback would be greatly appreciated. I'll start with the first component I created and end it with the last.
Playing card
import React from 'react';
import propTypes from 'prop-types';
import isNumeric from '../../Helper';
import './Playing-Card.scss';
const cardSuites =
D: 'diamonds',
S: 'spades',
H: 'hearts',
C: 'clubs',
;
const cardCourts =
K: 'king',
J: 'jack',
Q: 'queen',
A: 'ace',
T: '10',
;
const cardValues =
ace: '14',
king: '13',
queen: '12',
jack: '11',
;
const PlayingCard = ( cardSymbol ) =>
const url = convertCardSymbolToUrl(cardSymbol);
return <img alt="playing-card" className="playing-card" src=url />;
;
PlayingCard.propTypes = cardSymbol: propTypes.string.isRequired ;
export const convertCardSymbolToUrl = cardSymbol => `/cards/$getCardCourt(cardSymbol)_of_$getCardSuite(cardSymbol).svg`;
export const getCardSuite = cardSymbol => cardSuites[cardSymbol[1]];
export const getCardCourt = cardSymbol =>
const courtSymbol = cardSymbol[0];
if (isNumeric(courtSymbol))
return String(courtSymbol);
return String(cardCourts[courtSymbol]);
;
export const getCardValue = cardCourt =>
if (isNumeric(cardCourt))
return Number(cardCourt);
return Number(cardValues[cardCourt]);
;
export default PlayingCard;
Hand
import React from 'react';
import propTypes from 'prop-types';
import generateUniqueKeysForItems from '../../Helper';
import PlayingCard, getCardCourt, getCardValue, getCardSuite from '../Playing-Card/Playing-Card';
const Hand = ( cards ) =>
let cardsArray = cards.split(' ');
cardsArray = generateUniqueKeysForItems(cardsArray);
return cardsArray.map(card => <PlayingCard key=card.id cardSymbol=card.value />);
;
Hand.propTypes = cards: propTypes.string.isRequired ;
export const calculateHandValue = cardsArray =>
let cardsFrequency = calculateCardsFrequency(cardsArray);
cardsFrequency = sortFrequencyDesc(cardsFrequency);
const individualCardValues = calculateIndividualCardValues(cardsFrequency);
let handValue = 9;
const cardsCombinations = [
hasRoyalFlush,
hasStraightFlush,
hasFourOfAKind,
hasFullHouse,
hasFlush,
hasStraight,
hasThreeOfAKind,
hasTwoPairs,
hasTwoOfAKind,
];
for (let i = 0; i < cardsCombinations.length; i += 1)
const isCombinationValid = cardsCombinations[i];
if (isCombinationValid(cardsArray))
break;
handValue -= 1;
return [handValue, individualCardValues];
;
export const calculateIndividualCardValues = cardsFrequency =>
Array.from(cardsFrequency.keys()).map(key => getCardValue(key));
export const hasRoyalFlush = cardsArray =>
const cardCourtsRequired = ['10', 'jack', 'queen', 'king', 'ace'];
let qualifies = true;
if (!hasSameSuits(cardsArray))
return false;
cardsArray.forEach(card =>
const court = getCardCourt(card);
if (cardCourtsRequired.indexOf(court) === -1)
qualifies = false;
);
return qualifies;
;
export const hasStraightFlush = cardsArray =>
hasSameSuits(cardsArray) && hasIncrementalCourts(cardsArray);
export const hasStraight = cardsArray => hasIncrementalCourts(cardsArray);
export const hasFlush = cardsArray => hasSameSuits(cardsArray);
export const hasFourOfAKind = cardsArray => hasXOfAKind(cardsArray, 4);
export const hasThreeOfAKind = cardsArray => hasXOfAKind(cardsArray, 3);
export const hasTwoOfAKind = cardsArray => hasXOfAKind(cardsArray, 2);
const hasXOfAKind = (cardsArray, x) =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
return frequencyArray.indexOf(x) !== -1;
;
export const hasTwoPairs = cardsArray =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
let numberOfPairs = 0;
frequencyArray.forEach(frequencyNumber =>
if (frequencyNumber === 2)
numberOfPairs += 1;
);
return numberOfPairs === 2;
;
export const hasFullHouse = cardsArray =>
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
return frequencyArray.indexOf(3) !== -1 && frequencyArray.indexOf(2) !== -1;
;
export const hasSameSuits = cardsArray =>
const hasEqualSuits = (card1, card2) => getCardSuite(card1) === getCardSuite(card2);
for (let i = 1; i < cardsArray.length; i += 1)
const card = cardsArray[i];
const previousCard = cardsArray[i - 1];
if (!hasEqualSuits(card, previousCard))
return false;
return true;
;
export const hasIncrementalCourts = cardsArray =>
const hasIncrementalCardValues = (card1, card2) =>
getCardValue(getCardCourt(card1)) + 1 === getCardValue(getCardCourt(card2));
const sortedCards = sortByCardValueAsc(cardsArray);
for (let i = 1; i < sortedCards.length; i += 1)
const card = sortedCards[i];
const previousCard = sortedCards[i - 1];
if (!hasIncrementalCardValues(previousCard, card))
return false;
return true;
;
export const calculateCardsFrequency = cardsArray =>
const cardFrequency = new Map();
cardsArray.forEach(card =>
const court = String(getCardCourt(card));
if (cardFrequency.get(court) != null)
cardFrequency.set(court, cardFrequency.get(court) + 1);
else
cardFrequency.set(court, 1);
);
return cardFrequency;
;
export const sortFrequencyDesc = cardsFrequency =>
new Map([...cardsFrequency.entries()].sort((a, b) =>
const aCardCourt = a[0];
const aFrequency = a[1];
const bCardCourt = b[0];
const bFrequency = b[1];
if (aFrequency < bFrequency)
return 1;
if (aFrequency === bFrequency && getCardValue(aCardCourt) < getCardValue(bCardCourt))
return 1;
return -1;
));
export const sortByCardValueAsc = cardsArray =>
cardsArray.sort((card1, card2) =>
const court1 = getCardCourt(card1);
const court2 = getCardCourt(card2);
if (getCardValue(court1) > getCardValue(court2))
return 1;
if (getCardValue(court1) < getCardValue(court2))
return -1;
return 0;
);
return cardsArray;
;
export default Hand;
Round
import React from 'react';
import propTypes from 'prop-types';
import connect from 'react-redux';
import Hand, calculateHandValue from '../Hand/Hand';
import './Round.scss';
const Round = ( cards, incrementScore ) =>
const playerHands = splitCards(cards);
if (playerHands[0] === '')
return <div />;
const winner = determineWinner(playerHands[0], playerHands[1]);
incrementScore(`player$winner`);
return (
<div className="round-root">
<div className=(winner === 1) ? 'winner' : ''>
<Hand cards=playerHands[0] />
</div>
<div className=(winner === 2) ? 'winner' : ''>
<Hand cards=playerHands[1] />
</div>
</div>
);
;
Round.propTypes =
cards: propTypes.string.isRequired,
incrementScore: propTypes.func.isRequired,
;
const mapStateToProps = state => ();
const mapDispatchToProps = dispatch => (
incrementScore: playerName =>
dispatch(
type: 'INCREMENT_SCORE',
payload:
name: playerName,
,
);
,
);
export const splitCards = cards =>
const playerHands = ;
playerHands.push(cards.substr(0, Math.ceil(cards.length / 2) - 1));
playerHands.push(cards.substr(Math.ceil(cards.length / 2)));
return playerHands;
;
export const determineWinner = (player1Cards, player2Cards) =>
const p1HandValue = calculateHandValue(player1Cards.split(' '));
const p2HandValue = calculateHandValue(player2Cards.split(' '));
let winner = compareFirstTuples(p1HandValue, p2HandValue);
if (winner === 0)
winner = compareSecondTuples(p1HandValue, p2HandValue);
if (winner === 0)
throw Error('No winner could be determined');
return winner;
;
export const compareFirstTuples = (p1HandValue, p2HandValue) =>
if (p1HandValue[0] === p2HandValue[0]) return 0;
return (p1HandValue[0] > p2HandValue[0]) ? 1 : 2;
;
export const compareSecondTuples = (p1HandValue, p2HandValue) =>
const p1Tuple = p1HandValue[1];
const p2Tuple = p2HandValue[1];
let winner = 0;
const minLength = Math.min(p1Tuple.length, p2Tuple.length);
for (let i = 0; i < minLength; i += 1)
if (p1Tuple[i] > p2Tuple[i])
winner = 1;
break;
if (p1Tuple[i] < p2Tuple[i])
winner = 2;
break;
return winner;
;
export default connect(mapStateToProps, mapDispatchToProps)(Round);
Game-Room
import React from 'react';
import propTypes from 'prop-types';
import Button from '@material-ui/core/Button';
import './Game-Room.scss';
import connect from 'react-redux';
import Game from '../Game/Game';
import WinnerDetails from '../Winner-Details/Winner-Details';
const possibleSuits = ['D', 'S', 'H', 'C'];
const possibleCourts = ['2', '3', '4', '5', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'];
const GameRoom = ( setMatches, matches, players, resetScore ) => ;
GameRoom.propTypes =
setMatches: propTypes.func.isRequired,
resetScore: propTypes.func.isRequired,
players: propTypes.shape().isRequired,
matches: propTypes.arrayOf(propTypes.string).isRequired,
;
const mapStateToProps = state => (
matches: state.gamesReducer,
players: state.playerReducer,
);
const mapDispatchToProps = dispatch => (
setMatches: games =>
dispatch(
type: 'SET_GAMES',
payload: games,
);
,
resetScore: () =>
dispatch(
type: 'RESET_SCORE',
);
,
);
export const generateMatches = numberOfGames =>
const games = ;
for (let i = 0; i < numberOfGames; i += 1)
const round = generateRound();
games.push(round);
return games;
;
export const generateRound = () =>
let cards = '';
let numberOfCards = 0;
while (numberOfCards < 10)
const card = createRandomCard();
if (cards.indexOf(card) === -1)
cards += `$card `;
numberOfCards += 1;
cards = cards.slice(0, -1);
return cards;
;
const createRandomCard = () => getRandomCourt() + getRandomSuit();
const getRandomSuit = () => possibleSuits[Math.floor(Math.random() * possibleSuits.length)];
const getRandomCourt = () => possibleCourts[Math.floor(Math.random() * possibleCourts.length)];
export default connect(mapStateToProps, mapDispatchToProps)(GameRoom);
Components Winner-detail and Game are emitted because they're small enough. Game is just a container for rounds.
javascript algorithm playing-cards react.js redux
edited Jul 30 at 2:56
Jamalâ¦
30.1k11114225
30.1k11114225
asked Jul 29 at 21:54
P_Andre
101
101
Please post a short problem description along with your question. Otherwise, it will be hard for us to judge your code properly with regards to correctness and suitability for the problem at hand, among other characteristics.
â Ben Steffan
Jul 29 at 23:34
add a comment |Â
Please post a short problem description along with your question. Otherwise, it will be hard for us to judge your code properly with regards to correctness and suitability for the problem at hand, among other characteristics.
â Ben Steffan
Jul 29 at 23:34
Please post a short problem description along with your question. Otherwise, it will be hard for us to judge your code properly with regards to correctness and suitability for the problem at hand, among other characteristics.
â Ben Steffan
Jul 29 at 23:34
Please post a short problem description along with your question. Otherwise, it will be hard for us to judge your code properly with regards to correctness and suitability for the problem at hand, among other characteristics.
â Ben Steffan
Jul 29 at 23:34
add a comment |Â
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f200555%2fplaying-cards-with-reactjs%23new-answer', 'question_page');
);
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Please post a short problem description along with your question. Otherwise, it will be hard for us to judge your code properly with regards to correctness and suitability for the problem at hand, among other characteristics.
â Ben Steffan
Jul 29 at 23:34