大佬二/鬥地主的 JavaScript 版洗牌實現


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<script lanugage="javascript" type="text/javascript">
/*
* Author: Zeuxis.Lo
* Description: random cards on Big2 / DuDiZhu
*/
(function(window, undefined) {

var DealCard = function() {
this.roleA = [];
this.roleB = [];
this.roleC = [];
this.roleD = [];
this.remnant = [];
this.id = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53];

this.icon = ['葵扇', '紅心', '梅花', '街塼'];
this.name = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
this.joker= ["Joker S", "Joker B"];

this.cardName = [];
for (var i=0, k = 0; i<this .icon.length; i++) {
for(var j=0; j<this.name.length; j++) {
this.cardName[k++] = this.icon[i] + " " + this.name[j];
}
}
this.cardName[52] = this.joker[0];
this.cardName[53] = this.joker[1];
}

DealCard.prototype.rand = function() {
var i, j;
for(var k=0; k&lt;1000; k++) {
i = Math.ceil(Math.random() * 51);
j = Math.ceil(Math.random() * 51);

if (i != j) {
this.permute(i, j);
}
}
}

DealCard.prototype.permute = function(a, b) {
this.id[a] = parseInt(this.id[a]) + parseInt(this.id[b]);
this.id[b] = parseInt(this.id[a]) - parseInt(this.id[b]);
this.id[a] = parseInt(this.id[a]) - parseInt(this.id[b]);
}

DealCard.prototype.deal = function() {
for (var i=0; i&lt;13; i++) {
this.roleA.push(this.id[i*4].toString());
this.roleB.push(this.id[i*4 + 1].toString());
this.roleC.push(this.id[i*4 + 2].toString());
this.roleD.push(this.id[i*4 + 3].toString());
}

this.remnant.push(this.id[52].toString());
this.remnant.push(this.id[53].toString());
}

DealCard.prototype.roleName = function(cards) {
var temp = [];
for(var id in cards) {
temp.push( this.cardName[cards[id]] );
}
return temp.join(" ");
}

var dealCard = new DealCard();
dealCard.rand();
dealCard.deal();
console.log("A: " + dealCard.roleA.join(" "));
console.log("*: " + dealCard.roleName(dealCard.roleA));

console.log("B: " + dealCard.roleB.join(" "));
console.log("*: " + dealCard.roleName(dealCard.roleB));

console.log("C: " + dealCard.roleC.join(" "));
console.log("*: " + dealCard.roleName(dealCard.roleC));

console.log("D: " + dealCard.roleD.join(" "));
console.log("*: " + dealCard.roleName(dealCard.roleD));

console.log("=: " + dealCard.remnant.join(" "));
console.log("*: " + dealCard.roleName(dealCard.remnant));

})(window);
</script>
</this></script>