blog/source/_posts/作品/游戏/记忆游戏.md
2022-08-31 10:22:04 +08:00

6.4 KiB

title keywords categories tags sitemap date
记忆游戏
网页
游戏
作品
游戏
JavaScript
CSS
true 2022-08-30 17:31:35

复刻了一个小游戏...

演示

游戏时间 重新开始

源码

<style>
#gameContainer {
    width: 100%;
    margin: 0 auto;
    max-width: 320px
}

#gameBoard {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: repeat(4, 1fr);
    gap: 10px;
}

#gameBoard card {
    margin: auto;
    width: 72px;
    height: 72px;
    font-size: 48px;
    line-height: 72px;
    text-align: center;
    border-radius: 8px;
    background-color: #66c;
    cursor: pointer;
}

#gameBoard .gray { filter: grayscale(75%); }
#gameBoard time { font-size: 20px; }
#gameBoard button { padding: 5px; }
</style>

<div id="gameContainer">
    <div>游戏时间 <time id="gameTime"></time> <button id="startButton">重新开始</button></div>
    <div id="gameBoard"></div>
</div>

<script>
const 表情包 = Array.from('🐭🐮🐯🐰🐲🐍🐴🐐🐵🐔🐶🐷')
const 翻开的卡片 = []
let 开始时间, 翻对的数量

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')
        卡片.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 // 清空数组
            }, 600)
        }
    }
}

gameContainer.addEventListener('click', (e) => {
    if (e.target.tagName == 'CARD') 翻开(e.target)
})

// 更新游戏时间
setInterval(() => {
    if (翻对的数量 !== 表情包.length) {
        const seconds = Math.round((new Date() - 开始时间) / 1000)
        gameTime.innerText = `${seconds} 秒`
    }
}, 500)

开始游戏()
startButton.onclick = 开始游戏
</script>