Make a snake game based on js

Foreword:

Playing games for a while after work and study can not only bring happiness, but also relieve the pressure of life. Follow this article to make a small game together.

Description:
Snake (also known as Snake) game is a casual puzzle game with multi-platform versions such as PC and mobile phone. It is simple and playable. The game eats eggs by controlling the direction of the snake head, so that the snake becomes longer and longer.

Function keys:
W: up
S: down
A: left
D: right
Others: all pause


Project effect display:

insert image description here


Code implementation idea:

  1. Set the parameters to be used
  2. The double for loop sets the mesh object and the food with random numbers.
  3. Set the snake object, first clear all, and then add the snake according to the saved location
  4. Set keyboard press event
  5. How many keys are needed for judging, w, s, a, d (up, down, left, right)
  6. Determine whether to hit the wall, and stop the game if it hits the wall.
  7. Judging whether to eat food, the food disappears, and the greedy snake grows up
  8. Click to restart the game

Instructions:

Create a new file with the suffix HTML, copy the following code into it, and double-click to open it.
Of course, you can also download directly through the link below. After the download is complete, double-click to open it.
Click to download: https://download.csdn.net/download/weixin_62897746/87377763


Implementation code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇</title>
    <style>
        body{
            text-align: center;
        }
        .box{
            margin: 0 auto;
            border: 1px solid #ddd;
            display: flex;
            flex-wrap: wrap;
        }
        .item{
            box-sizing: border-box;
            border: 1px solid #ddd;
        }
        .player{
            background-color: #444;
        }
        .eat{
            background-color: rosybrown;
        }
        #btn{
            margin-top: 20px;
            font-size: 23px;
            color: #fff;
            border: 1px solid #000;
            border-radius: 5px;
            padding: 10px 25px;
            background-image: linear-gradient(to right,#ff00ad,#f09876);
        }
    </style>
</head>
<body>
    <h1>贪吃蛇大作战</h1>
    <p id="text"></p>
    <div class="box"></div>
    <button id="btn">开始</button>
</body>
<script>
    sessionStorage.setItem('id',0)
    function kaishi(){
        // 行
        const x = 20
        // 列
        const y = 20
        // 盒子大小
        const size = 20
        // 地图
        const box = document.querySelectorAll('.box')[0]
        // 网格对象
        const result = []
        // 贪吃蛇对象
        const player = [
            [1,1]
        ]
        // 贪吃蛇对象
        const updatePlayer =()=>{
            // 清除所有对象
            document.querySelectorAll('.player').forEach(v=>v.classList.remove('player'))
            player.forEach(v=>{
                // 根据网格所在位置设置贪吃蛇对象,移动
                document.querySelector(`[data-v="${v.join('-')}"]`).classList.add('player')
            })
        }
        let key = ''
        // 循环设置网格
        for(let i=0; i<x; i++){
            for(let j=0; j<y; j++){
                // 随机数,食物
                const isEat = Math.random() > 0.9
                // 添加网格对象
                result.push(`<div data-v="${i}-${j}" class="item ${isEat ? 'eat' : ''}" style="width:${size}px;height:${size}px"></div>`)
            }
        }
        // 把内容转换为字符串
        box.innerHTML = result.join('')
        // 设置宽
        box.style.width = `${x*size}px`

        // 触发事件
        document.addEventListener('keydown',e=>{
            // 保存触发事件
            key = e.key
        })

        // 定时器
        const intervalId = setInterval(()=>{
            // 显示分数,和历史最高分
            document.getElementById('text').innerHTML = `当前分为${player.length}分,历史最高分为${sessionStorage.getItem('id')}`
            if(key){
                // 保存贪吃蛇所在位置
                const needPos = JSON.parse(JSON.stringify(player.slice(0,player.length-1)))
                // 判断触发事件
                switch(key){
                    case 'w':
                        player[0][0] -= 1
                        break;
                    case 'a':
                        player[0][1] -= 1
                        break;
                    case 's':
                        player[0][0] += 1
                        break;
                    case 'd':
                        player[0][1] += 1
                        break;
                }
                // 是否撞墙
                const el = document.querySelector(`[data-v="${player[0].join('-')}"]`)
                // 判断是否撞墙
                if(!el){
                    // 停止定时器
                    clearInterval(intervalId)
                    // 判断当前分是否超过历史最高分
                    if(sessionStorage.getItem('id') < player.length){
                        // 更改分数
                        sessionStorage.setItem('id',player.length)
                    }
                    alert('撞墙了')
                    isKey = true
                }else{
                    // 改变保存贪吃蛇的位置
                    for(let i=1; i<player.length; i++){
                        player[i] = needPos[i-1]
                    }
                    // 判断是否迟到食物
                    if(el.className.indexOf('eat') >= 0){
                        // 删除食物
                        el.classList.remove('eat')
                        // 贪吃蛇增长
                        player.push([...player[0]])
                    }
                    // 调用贪吃蛇使他发生改变
                    updatePlayer()
                }
            }
        },100)
        updatePlayer()
    }
    kaishi()
    let isKey = true
    // 点击开始
    document.getElementById('btn').onclick=()=>{
        if(isKey){
            kaishi()
            isKey = false
        }
    }
</script>
</html>

Summarize:

The above is a small snake game based on js. If you don’t understand it, you can ask me in the comment area or chat with me privately. I will continue to release some new functions in the future, so stay tuned.
My other articles: https://blog.csdn.net/weixin_62897746?type=blog

Guess you like

Origin blog.csdn.net/weixin_62897746/article/details/128630186