JS实现简单斗地主效果
let play = document.querySelectorAll(".play");
let dizhupai = document.getElementById("dizhupai");
function creatPoker(){
let paidui = [];
let color = ["黑桃", "红桃", "梅花", "方块"];
let number = ["3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"]
for (let i = 0; i < number.length; i++) {
let forColor = number[i];
for (let j = 0; j < color.length; j++) {
let forNum = color[j];
paidui.push(
{
name:forColor + forNum,
order:i * 4 + j,
path:"../img/" + (i + 3) + "_" + (j + 1) + ".jpg"
}
)
}
}
paidui.push(
{
name:"小王",
order:52,
path:"../img/16_1.jpg"
}
);
paidui.push(
{
name:"大王",
order:53,
path:"../img/17_1.jpg"
}
);
return paidui;
}
function shufflePoker(pokers){
for (let i = 0; i < pokers.length; i++) {//通过循环随机的将牌进行交换,实现洗牌
let ranNum = parseInt(Math.random() * pokers.length);
[pokers[i], pokers[ranNum]] = [pokers[ranNum], pokers[i]];
}
}
function dealPoker(pokers,...players){
// let player = [[], [], []];
while (pokers.length > 3) {//只要牌堆的牌大于3张,玩家继续摸牌
for (let i = 0; i < players.length; i++) {//玩家3人轮流摸牌
players[i].push(pokers.pop());
}
}
}
function orderPoker(...players){
players.forEach(function (player) {//每个玩家将手里的牌理好
// players
player.sort(function (a, b) {//a,b代表着排序过程中两个相互比较的元素
return a.order - b.order;
})
});
}
function renderPocker(pokers,...players){
dizhupai.innerHTML = "";
let flag = true;
for (let i = 0; i < players.length; i++) {
let nowPlay = play[i];
nowPlay.innerHTML = "";
let k = 0;
let timer = setInterval(function(){
let newImg = document.createElement("img");
nowPlay.appendChild(newImg);
newImg.src = players[i][k].path;
if (i == 0) {
newImg.style.left = (k * 20) + "px"
} else if (i == 1 || i == 2) {
newImg.style.top = (k * 27) + "px"
}
if(k == players[i].length - 1){
clearInterval(timer);
if(flag){
for (let i = 0; i < pokers.length; i++) {
let pokerImg = document.createElement("img");
dizhupai.appendChild(pokerImg);
pokerImg.src = pokers[i].path;
pokerImg.style.left = (i * 20) + "px";
}
}
flag = false;
}
k++;
},200);
// for (let k = 0; k < players[i].length; k++) {
// let newImg = document.createElement("img");
// nowPlay.appendChild(newImg);
// newImg.src = players[i][k].path;
// if (i == 0) {
// newImg.style.left = (k * 20) + "px"
// } else if (i == 1 || i == 2) {
// newImg.style.top = (k * 27) + "px"
// }
// }
}
}
function run(){
let pokers = creatPoker()
shufflePoker(pokers);
let players = [[],[],[]];
dealPoker(pokers,...players)
orderPoker(...players)
renderPocker(pokers,...players)
}
let rePlaybtn = document.getElementById("rePlayBtn");
rePlaybtn.addEventListener("click", () => {
run();
});