Skip to content

Instantly share code, notes, and snippets.

@navio
Created July 23, 2019 00:19
Show Gist options
  • Save navio/6f8a514568d104fa36d57a527388a62b to your computer and use it in GitHub Desktop.
Save navio/6f8a514568d104fa36d57a527388a62b to your computer and use it in GitHub Desktop.
BoardGame Example ♠♥♣♦
body {
background-color: #59A856;
}
.card{
background-color: white;
border: 1px solid red;
width: 100px;
height: 120px;
float:left;
margin-right: 10px;
}
.boardgame{
margin-top: 10px
}
<div class="boardgame">
<button>
Deal a new hand
</button>
</div>
const CARD_SUITS = {
spades: "♠",
hearts: "♥",
clubs: "♣",
diamonds: "♦",
};
const CARD_VALUES = [
2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"
];
class Deck{
constructor(){
this.deck = this.buildDeck();
}
buildDeck(){
const deck = []
for(const suit of Object.values(CARD_SUITS)) {
for(const value of CARD_VALUES){
deck.push({ suit, value });
}
}
return deck;
}
getRandom(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
deal(amount = 5) {
const toDeal = [];
for(let i = 0; i < amount; i++) {
const cardId = this.getRandom(0,this.deck.length);
const card = this.deck.splice(cardId,1);
toDeal.push(card[0]);
}
return toDeal;
}
reset(){
this.deck = this.buildDeck();
}
}
const deck = new Deck();
function boardGame(deck,domElement){
const container = document.createElement("div");
domElement.appendChild(container);
const cardFactory = (card) => {
const cardElement = document.createElement("div");
const cardValue = document.createElement("div");
cardElement.classList.add("card");
cardValue.innerHTML = `${card.suit} ${card.value}`;
cardElement.appendChild(cardValue);
return cardElement;
}
const renderCards = (cards) => {
container.innerHTML = '';
const cardElements = cards.forEach(card => {
container.appendChild(cardFactory(card));
});
}
const handler = (ev) => {
const cards = deck.deal();
renderCards(cards);
}
const button = domElement.querySelector("button");
button.addEventListener("click", handler);
}
boardGame(deck,document.getElementsByClassName("boardgame")[0]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment