65 lines
2.3 KiB
JavaScript
65 lines
2.3 KiB
JavaScript
const 表情包 = Array.from('🐥🐦🎂🎑🌺🌼🌇💃🧋')
|
|
const 翻开的卡片 = []
|
|
let 开始时间, 翻对的数量
|
|
|
|
// 在body上添加点击事件监听
|
|
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) // 在剩下的表情中抓bie
|
|
const 卡片 = document.createElement('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('grayout')
|
|
翻开的卡片[1].classList.add('grayout')
|
|
// 全都完啦?
|
|
if (翻对的数量 == 表情包.length) {
|
|
if (confirm('恭喜你成功了!再玩一次吗?')) 开始游戏()
|
|
else startButton.style.display = 'inline-block'
|
|
}
|
|
} else {
|
|
// 两张卡片表情不一样
|
|
翻开的卡片[0].innerText = ''
|
|
翻开的卡片[1].innerText = ''
|
|
}
|
|
翻开的卡片.length = 0 // 清空数组
|
|
}, 600)
|
|
}
|
|
}
|
|
}
|
|
|
|
// 更新游戏时间
|
|
setInterval(() => {
|
|
if (翻对的数量 !== 表情包.length) {
|
|
const seconds = Math.round((new Date() - 开始时间) / 1000)
|
|
gameTime.innerText = `${seconds} 秒`
|
|
}
|
|
}, 500)
|
|
|
|
开始游戏() |