- 初始化撲克牌,有四個花色,各13張牌。
- 根據玩家數量,點選發牌按鈕後,做到自動發牌。
- 點選按鈕後的動作=>3-1洗牌、3-2根據玩家數量開始發牌
- 結果呈現
以下是程式碼:
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
//1.先初始化撲克牌
var suit = ["clubs", "hearts", "diamonds", "spades"];
var number = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
var poker = [];
$(document).ready(function () {
for (var i = 0; i < suit.length; i++) {
for (var j = 0; j < number.length; j++) {
var item = [suit[i], number[j]];
poker.push(item);
}
}
});
//洗牌
function shuffle(a, b) {
var num = Math.random() > 0.5 ? -1 : 1;
return num;
};
//2.點選發牌觸發事件
function deal() {
//3-1先洗牌
poker.sort(shuffle);
//取得玩家數量
var players = $("input[name='players']:checked").val();
var playercards = [];
var pokerarea = document.getElementById("pokerarea");
pokerarea.innerHTML = "";
//初始化存放玩家發到牌的陣列
for (var j = 0; j < players; j++) {
playercards[j] = [];
}
//3-2開始發牌
for (var i = 0; i < poker.length; i++) {
var x = i % players;
playercards[x].push(poker[i]);
}
//4.動態產生DOM
var top = 0;
var left = 0;
for (var j = 0; j < players; j++) {
if (document.getElementById('issort').checked) playercards[j].sort();
var div = document.createElement("div");
for (var i = 0; i < playercards[j].length; i++) {
var img = document.createElement("img");
img.setAttribute("id", playercards[i]);
img.setAttribute("style", "position:absolute;top:" + top + "px;left:" + left + "px");
img.src = playercards[j][i][0] + "/" + playercards[j][i][1] + ".gif";
div.appendChild(img);
left = left + 20;
}
pokerarea.appendChild(div);
top = top + 120;
left = 0;
}
}
</script>
</head>
<body>
玩家:
<input type="radio" name="players" value="2"> 2
<input type="radio" name="players" value="3"> 3
<input type="radio" name="players" value="4" checked> 4
<input type="radio" name="players" value="5"> 5
<input type="radio" name="players" value="6"> 6 人
是否根據花色排序:
<input type="checkbox" id="issort">
<input type="button" value="發牌" onclick="deal()">
<br>
<br>
<div id="pokerarea" style="position:relative;">
</div>
</body>
</html>
執行結果如下圖
沒有留言:
張貼留言