top of page

#7 A small card game demo

  • Aaron
  • Nov 27, 2020
  • 2 min read

Before I begin making my real project, I started with making a smaller and simpler card game. One player vs one computer. Using plain vanilla Javascript.


ree

You can check out the GitHub repo here:


I found a great tutorial on youtube by "Web Dev Simplified"

I implemented a very simple "high-card" game. But some concepts like deck classes and shuffle methods can be applied to bigger and more complex projects.


Creating a deck of cards

// array with card suits metadata
const SUITS = ["♠", "♣", "♦", "♥"];

// array with card values
const VALUES = ["A","2","3","4","5","6","7", 
                "8", "9", "10", "J","Q","K",];

VALUES here are just the display values. You could also pass your "real values" (J => 11, Q => 12, K => 13, A => 14) or you can map your values later like I did with a "value map".

const CARD_VALUE_MAP = {2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, J: 11, Q: 12, K: 13, A: 14};

Create a card class object

export class Card{
    constructor(suit,value {
        this.suit=suit;
        this.value=value;
    }
    get color(){
        return this.suit==="♣"||"♠" ? "black" : "red";
    }
}

Loop through all the values & suits to create your full deck.

const newDeck = () => {
 //flatMap combines multiple arrays within an array to one array [[0,1], 2] => [0,1,2]
 return SUITS.flatMap(suit => {
 // return for each suit an array of values
 return VALUES.map(value => {
 return new Card(suit, value);
    });
  });
};

The shuffle function

One of the core requirements of any card game is a randomly shuffled deck of cards.


After you have created a deck containing all of the cards, you will have to shuffle them.

At first, you might write a shuffle function like this:

// don't do this
shuffle() {
  this.cards.sort((a, b) => Math.random() - .5)
}

Half of the time Math.random will give us a number less than 0, half of the time a number greater than zero, which means it will randomly sort those cards.


But the sort function is actually meant to, you know, sort things (in an actual order and not a random order). So we won't get a perfectly randomized order if we use the sort function, because some cards would appear way more in the same slot.


I recommend reading this article:


Learn more about the Durstenfeld shuffle:


So, instead of sort() use this:

shuffle(){
// flip all cards, go from the back of your list to the front
// take current card and swap with a card that comes earlier in the deck

for(let i = this.cards.length - 1; i > 0; i--){
//get a random index before current card
const newIndex = Math.floor(Math.random() * (i+1));

const oldValue = this.cards[newIndex];
//swap card we are currently on with the new card we got randomly
this.cards[newIndex]=this.cards[i];
this.cards[i]=oldValue;
    }
}

Feel free to give it a try!

Yorumlar


  • iconmonstr-github-1-240

©2020

bottom of page