study/记忆游戏/game.js

61 lines
2.1 KiB
JavaScript
Raw Normal View History

2022-08-04 04:30:02 +00:00
const 表情包 = Array.from("🐈🐕🐟🔮🍎⚡⛵🐰");
const 翻开的卡片 = [];
let 开始时间, 翻对的数量;
document.body.addEventListener("click", (e) => {
if (e.target.tagName == "BUTTON") 开始游戏();
else if (e.target.tagName == "CARD") 翻开(e.target);
});
function 开始游戏() {
startButton.style.display = "none";
gameBoard.replaceChildren(); // 清空元素的所有子元素
翻开的卡片.length = 0; // 清空数组
开始时间 = new Date();
翻对的数量 = 0;
const 候选表情 = [...表情包, ...表情包];
while (候选表情.length > 0) {
const x = Math.floor(Math.random() * 候选表情.length);
const 卡片 = document.createElement("card"); //创建一个card元素
卡片.dataset["表情"] = 候选表情[x];
gameBoard.appendChild(卡片);
候选表情.splice(x, 1);
}
}
function 翻开(卡片) {
if (翻开的卡片.length < 2 && 卡片.innerText == '') {
翻开的卡片.push(卡片)
卡片.innerText = 卡片.dataset['表情']
if (翻开的卡片.length == 2) {
setTimeout(() => {
if (翻开的卡片[0].innerText == 翻开的卡片[1].innerText) {
翻对的数量++
翻开的卡片[0].classList.add('gray')
翻开的卡片[1].classList.add('gray')
if (翻对的数量 == 表情包.length) {
if (confirm('恭喜你成功了!再玩一次么?')) 开始游戏()
else startButton.style.display = 'inline-block'
}
} else {
翻开的卡片[0].innerText = ''
翻开的卡片[1].innerText = ''
}
翻开的卡片.length = 0 // 清空数组
}, 400)
}
}
}
setInterval(() => {
if (翻对的数量 !== 表情包.length) {
const seconds = Math.round((new Date() - 开始时间) / 1000)
gameTime.innerText = `${seconds}`
}
}, 500)
开始游戏()