Javascript example teaches you to implement the card shuffle function

  • 2020-03-30 03:00:24
  • OfStack

Generally, we will arrange the random CARDS in the order from small to large (remember that when I was a child, I could not catch two pairs of players). This essay is intended to realize this function to familiarize myself with the sorting array in js and other relevant knowledge.

Use of knowledge:

1. Create objects in factory mode

2. Js array sort() method


  var testArr = [1, 3, 4, 2];
     testArr.sort(function (a,b) {
         return a - b;
     })
     alert(testArr.toString());//1,2,3,4
     testArr.sort(function (a, b) {
         return b- a;
     })
     alert(testArr.toString());//4,3,2,1

3. Js - Math. Radom random number ()

Math. The random (); //0 minus 1 gets a random number that is greater than or equal to 0 and less than 1

4. Js array splice usage


//The first parameter is the starting position of the insert
//The second parameter deletes the number of elements from the starting position
//The third parameter is the element that is inserted at the starting position & NBSP;  
// example 
var testArr = [1, 3, 4, 2];
testArr.splice(1, 0, 8);
alert(testArr.toString());//1,8,3,4,2
var testArr1 = [1, 3, 4, 2];
testArr1.splice(1, 1, 8);
alert(testArr1.toString());//1,8,3,4,2

5. Js array shift usage


    //Returns the first element in the array, and the array deletes the first element
   // example  
    var testArr = [1, 3, 4, 2];
     var k=  testArr.shift();
     alert(testArr.toString());//3,4,2
     alert(k);//1

With these basic knowledge, we can start to play, assuming that a person to touch the CARDS, the card is random, every time we touch a card when he will be inserted into the hand of the CARDS, ensure that the order is from small to large!

Step 1: first we need to write a method to produce poker objects:



var Cards = (function () {
var Card = function (number, type) {
this.number = number;
this.type = type;
}
return function (number, type) {
return new Card(number, type);
}
})()

Step 2: create playing CARDS, shuffle them, and store them


    var RadomCards = [];//Random CARDS store an array
    var MyCards = [];//Store the CARDS touched

 
    //Suit 0- spades 1- clubs 2- diamonds & NBSP; 3- the 4 of hearts - the devil & NBSP; 5 - imp
    //The number 0-13 on behalf of ghosts, 1,2,3,4,5,6,7,8,9,10, J, Q, K;
    function CreatCompeleteCard() {
        var index = 2;
        var arr = [];
        for (var i = 0; i <= 13; i++) {
            if (i == 0) {
                arr[0] = new Cards(i, 4);
                arr[1] = new Cards(i, 5);
            } else {
                for (var j = 0; j <= 3; j++) {
                    arr[index] = new Cards(i, j);
                    index++;
                }
            }
        }
        RadomCards = SortCards(arr);
        Show();//Displays the current card on the page
    }
    // Shuffle the deck 
    function SortCards(arr) {
        arr.sort(function (a, b) {
            return 0.5 - Math.random();
        })
        return arr;
    }

Step 3: begin to touch the CARDS. When we touch the CARDS, we should first judge the position of insertion, and then insert the new CARDS into the specified position, forming a new orderly order


//You draw method
    function GetCards(CardObj) {
        var k = InCardsIndex(MyCards, CardObj);//So let's think about the insertion position
        MyCards.splice(k, 0, CardObj); //Inserts form a new order
    }
    
    function InCardsIndex(arr, obj) {
        var len = arr && arr.length || 0;
        if (len == 0) {
            return 0;
        }else if (len == 1) {
            if (obj.number >= arr[0].number) {
                return 1;
            } else {
                return 0;
            }
        } else {
            var backi = -1;
            for (var i = 0; i < len; i++) {

                if (obj.number <= arr[i].number) {
                    backi = i;
                    break;
                } 
            }
            if (backi == -1) {
                backi = len;
            }
            return backi;
        }
    }

Come on! Touch the card by starting with the HTML button button, one card at a time! And show it


  function Start() {//Touch one card at a time
        if (RadomCards.length > 0) {
            GetCards(RadomCards.shift());
            Show();
        } else {
            alert(" Without the ");
        }
    }
//The show method is used to display the current card movement on the page
    function Show() {
        var lenOld = RadomCards.length;
        var lenNew = MyCards.length;
        var html = "";
        for (var i = 0; i < lenOld; i++) {
            html += "<div class='pai'><b>" + RadomCards[i].type + "</b>-<div class='nu'>" + RadomCards[i].number + "</div></div>";
        }
        document.getElementById("old").innerHTML=html;
        html = "";
        for (var i = 0; i < lenNew; i++) {
            html += "<div class='pai new'><b>" + MyCards[i].type + "</b>-<div class='nu'>" + MyCards[i].number + "</div></div>";
        }
        document.getElementById("new").innerHTML=html;
    }

HTML and CSS on the code


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <style type="text/css">
        .boom{
            width: 50px;
            height: 50px;
            border: solid 1px red;
            position: absolute;
            top: 5px;
            left: 5px;
        }
        .pai
        {
            width: 50px;
            height: 100px;
            border: solid 1px red;
            margin-left: 3px;
            float: left;
        }
        .new
        {
            border: solid 1px blue;
        }
        .nu
        {
            text-align:center;
            font-size:24px;
            margin-top:25px;         
        }
    </style>
</head>
<body>
    <!-- <div class="boom"></div>-->
    <input type="button" value=" start " onclick="CreatCompeleteCard()" />
    <input type="button" value=" Touch a card " onclick="Start()" />
    <br/>
     Card: <div id="old"></div>
    <div style="clear: both"></div>
    <hr />
     The CARDS I touched: <div id="new"></div>
</body>
</html>


Related articles: