JS实现3人斗地主发牌算法

//用1——54的数组代表54张牌
function myCreateArray(n){
	var arr = [];
	for(var i = 0; i < n; i++){
		arr[i] = i + 1;
	}
	return arr;
}

var cards = myCreateArray(54);
console.log('Get A Deck of Cards is: ' + cards);

//洗牌即是打乱数组顺序
function myShuffle(arr) {
    var len = arr.length;
    for (var i = 0; i < len - 1; i++) {
        var index = parseInt(Math.random() * (len - i));
        var temp = arr[index];
        arr[index] = arr[len - i - 1];
        arr[len - i - 1] = temp;
    }
}

myShuffle(cards);
console.log('Get A Disordered Cards is: ' + cards);

//玩家A,B,C各拿17张牌
var playerA = cards.slice(0,17);
console.log('playerA Has Cards: ' + playerA);

var playerB = cards.slice(17,34);
console.log('playerB Has Cards: ' + playerB);

var playerC = cards.slice(34,51);
console.log('playerC Has Cards: ' + playerC);

//留下3张底牌
var bottomCards = cards.slice(51,54);
console.log('Bottom Cards: ' + bottomCards);

运行结果如下(注:每次运行牌型结果都不一样):

JS实现3人斗地主发牌算法_第1张图片

你可能感兴趣的:(JS算法)