Native js to realize a simple snake game

Native js to realize a simple snake game

This article shares the specific code of js to implement the snake game for your reference. The specific content is as follows

First picture

Without further ado, here is the code. If you like it, please leave your little stars♥(ˆ◡ˆԅ)

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
 
        .l {
            float: left;
        }
 
        .r {
            float: right;
        }
 
        .clear_fix::after {
            content: '';
            height: 0;
            width: 100%;
            display: block;
            clear: both;
            overflow: hidden;
            visibility: hidden;
        }
 
        .body {
            margin: 50px 0 0 50px;
            width: 700px;
        }
 
        .cont {
            width: 500px;
            height: 500px;
            border: 1px solid green;
            margin-right: 8px;
            position: relative;
        }
 
        .cont div {
            position: absolute;
            width: 10px;
            height: 10px;
            background-color: orange;
            border: 1px solid #000;
            box-sizing: border-box;
        }
 
        .cont .snakeHead {
            border-radius: 50%;
        }
 
        .cont span {
            position: absolute;
            display: inline-block;
            width: 10px;
            height: 10px;
            border: 1px solid #000;
            box-sizing: border-box;
            border-radius: 50%;
            background: green;
 
        }
 
        .score {
            width: 188px;
            height: 500px;
            border: 1px solid red;
 
        }
 
        .score p {
            text-align: center;
            height: 50px;
            line-height: 50px;
            font-size: 30px;
            margin: 20px 0;
            color: brown
        }
        .score .time{
            color:chartreuse;
            font-size: 20px;
        }
        .btn {
            margin-left: 50px
        }
 
        .btn .active {
            background-color: green;
        }
 
        button {
            width: 100px;
            height: 30px;
            font-size: 24px;
        }
    </style>
</head>
 
<body>
    <div id="wrap">
        <div class="body clear_fix">
            <div class="cont l">
            </div>
            Score:
                </br>
                <p>0 points</p>
                <hr>
                time:
                <p class="time"></p>
            </div>
        </div>
        <div class="btn">
            <button>Start</button>
            <button class="active">Normal</button>
            <button>Difficult</button>
            <button>Hell</button>
        </div>
    </div>
    <script>
        var snake = {
            /* Initialize global events, add initial event listener*/
            init: function () {
                this.btns = document.querySelectorAll('button');
                this.score = document.querySelector('p');
                this.cont = document.querySelector('.cont');
                //Container for time display this.time = document.querySelector('.time');
                //Direction of the snake, 'r' means right this.dir = 'r';
 
                /* Timer */
                this.timer = '';
                /* Initial snake head position */
                this.head = {
                    l: 30,
                    t: 10
                }
                //Snake tail this.ender = {
                    l: '',
                    t: ''
                };
                this.foodItem = {
                    l: '',
                    t: ''
                };
                //Starting state this.isStart = false;
                /* Score counter */
                this.counter = 0;
                //Easy status is 1, difficult is 2, hell is 3
                this.status = 1;
                this.speed = 10
                this.btns[0].onclick = this.startFn //Start or pause this.btns[1].onclick = this.simpleFn //Simple mode listening this.btns[2].onclick = this.difcultFn //Difficult mode listening this.btns[3].onclick = this.hardFn //Hell mode listening this.initCreate();
                this.getTime()
                //A random food this.getfood()
            },
            initCreate() {
                //Create an initial snake head and 3 snake bodies for (let i = 0; i <= 3; i++) {
                    let item = document.createElement('div');
                    Object.assign(item.style, {
                        left: this.head.l - 10 * i + 'px',
                        top: this.head.t + 'px',
                        /* borderRaduis: '50%' */
                    })
                    if (i == 0) {
                        item.className = 'snakeHead'
                    }
                    snake.cont.appendChild(item);
                }
            },
            /* Add a section of the snake body*/
            createSnake: function (obj) {
                clearInterval(snake.timer)
                var div = document.createElement('div');
                div.style.left = snake.ender.l;
                div.style.top = snake.ender.t;
                snake.cont.appendChild(div);
                console.log(snake.cont.children);
                snake.move();
                /* console.log(snake.cont); */
            },
            /* Check if it is the start time*/
            startFn: function () {
                if (!snake.isStart) {
                    snake.move();
                    snake.btns[0].innerHTML = 'Pause';
                    snake.isStart = true;
                } else {
                    snake.stop();
                    snake.btns[0].innerHTML = 'Start';
                    snake.isStart = false;
                }
 
            },
            /* Start moving, core module*/
            move: function () {
                document.onkeydown = snake.controlFn;
                var itemsAll = snake.cont.children;
                /* console.log(itemsAll);
                console.log(itemsAll,itemsAll[0].nodeName); */
                /* Array to store each section of the snake body*/
                var items = [];
                var span;
                /* var items = Array.from(itemsAll).filter(function (v, k) {
                    return v.nodeName === 'DIV'
                }); */
                /* console.log(items); */
                /* Filter div (snake body) and span (food) */
                for (var j = 0; j < itemsAll.length; j++) {
                    if (itemsAll[j].nodeName == 'DIV') {
                        items.push(itemsAll[j])
                    } else {
                        span = itemsAll[j]
                    }
                }
                /* Get the position of the snake head */
                var l = snake.head.l;
                var t = snake.head.t;
                console.log(l, t);
                console.log(items)
                clearInterval(snake.timer)
                /* Keyboard monitoring */
                document.onkeydown = snake.controlFn
                /* Start moving */
                snake.timer = setInterval(function () {
                    /* Record the position of the snake's tail and update it to the object storing the snake's tail*/
                    snake.ender.l = items[items.length - 1].style.left;
                    snake.ender.t = items[items.length - 1].style.top;
                    /* Update the snake's position*/
                    for (var i = items.length - 1; i > 0; i--) {
                        items[i].style.left = items[i - 1].style.left;
                        items[i].style.top = items[i - 1].style.top;
                    }
 
                    /* Determine the direction of the snake head and update its position*/
                    if (snake.dir == 'l') {
                        l -= snake.speed;
                    }
                    if (snake.dir == 'r') {
                        l += snake.speed;
                    }
                    if (snake.dir == 't') {
                        t -= snake.speed;
                    }
                    if (snake.dir == 'b') {
                        t += snake.speed;
                    }
                    /* Out of boundary y */
                    if (l < 0 || l > 490 || t < 0 || t > 490) {
                        clearInterval(snake.timer)
                        snake.reStart(confirm('Snake monster, you hit the wall! Do you want to start over?'))
                    }
 
                    items[0].style.left = l + 'px';
                    items[0].style.top = t + 'px';
                    /* Update the object that records the snake head*/
                    snake.head.l = l
                    snake.head.t = t
                    /* console.log(items[0].style); */
                    /* Insert snake head */
                    snake.cont.appendChild(items[0])
                    for (var k = 1; k < items.length; k++) {
                        /* Determine whether the snake head has bitten itself*/
                        if (items[0].style.left == items[k].style.left && items[0].style.top == items[k]
                            .style.top) {
                            snake.reStart(confirm('Snake monster, you bit yourself to death, do you want to start over?'))
                            /* console.log(items[0].style.left,items[0].style.top);
                            console.log(items[0].style.left,items[0].style.top); */
                            clearInterval(snake.timer)
                            /* alert('Game Over!');
                            window.location.reload(true) */
                            return
                        }
                        /* Insert the snake body */
                        snake.cont.appendChild(items[k])
                    }
                    /* Ate the food */
                    console.log(span.style.left, span.style.top);
                    /* console.log(l, 'eat the food'); */
                    if (l == parseInt(span.style.left) && t == parseInt(span.style.top)) {
                        snake.eat()
                    }
                }, parseInt(300 / snake.status))
            },
            eat() {
                snake.createSnake()
                snake.getfood()
                snake.counter++;
                snake.score.innerHTML = `${snake.counter*100} points`
            },
            /* Game ends and determines whether to restart*/
            reStart: function (value) {
                if (value) {
                    window.location.reload(true)
                }
            },
            /* Produce food */
            getfood: function () {
                if (document.querySelector('span')) {
                    console.log('come in');
                    document.querySelector('span').remove();
                }
 
                var span = document.createElement('span');
                var l = snake.randM(0, 49) * 10
                var t = snake.randM(0, 49) * 10
                console.log('get food', l, t);
 
                span.style.left = l + 'px';
                span.style.top = t + 'px';
 
                snake.cont.appendChild(span);
                if (snake.isStart) {
                    snake.move()
                }
            },
            /* Generate random numbers */
            getTime() {
                let time,h,m,s
                
                setInterval(function () {
                    time = new Date()
                    h = time.getHours()
                    m = time.getMinutes();
                    s = time.getSeconds();
                     if (h < 10) {
                         h = '0' + h
                     }
                     if (m < 10) {
                         m = '0' + m
                     }
                     if (s < 10) {
                         s = '0' + s
                     }
                    snake.time.innerHTML = `${h}: ${m}: ${s}`
                }, 1000)
            },
            randM: function (min, max) {
                return Math.round(Math.random() * (max - min) + min)
            },
            /* pause*/
            stop: function () {
                clearInterval(snake.timer)
            },
            /* Simple mode */
            simpleFn: function () {
                snake.status = 1;
                snake.btnFn()
                snake.btns[1].className = 'active'
            },
            /* Complex mode */
            differenceFn: function () {
                snake.status = 3;
                snake.btnFn()
                snake.btns[2].className = 'active'
            },
            /* Hell Mode */
            hardFn: function () {
                snake.status = 5;
                snake.btnFn()
                snake.btns[3].className = 'active'
            },
            btnFn: function () {
                snake.btns.forEach(function (v, k) {
                    v.className = ''
                });
                if (snake.isStart) {
                    snake.move();
                }
            },
            /* Buttons to move the snake*/
            controlFn: function (el) {
                var el = el || window.event;
                var code = el.keycode || el.which;
                console.log(code);
                if ((code == 40 || code == 83)&&snake.dir != 't') {
                    snake.dir = 'b'
                }
                if ((code == 39 || code == 68)&&snake.dir != 'l') {
                    snake.dir = 'r'
                }
                if ((code == 38 || code == 87)&&snake.dir != 'b') {
                    snake.dir = 't'
                }
                if ((code == 37 || code == 65)&&snake.dir != 'r') {
                    snake.dir = 'l'
                }
            }
        }
        snake.init();
    </script>
</body>
</html>

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JS implements the snake game
  • JavaScript to achieve the idea of ​​​​snake game
  • JavaScript implementation of classic snake game
  • Use js to write a simple snake game
  • JavaScript Snake Implementation Code
  • JavaScript to implement the web version of the snake game
  • Implementing the Snake Game in JavaScript
  • Writing Snake Game with Native JS
  • js to implement the snake game with comments
  • JavaScript exquisite snake implementation process

<<:  A detailed analysis of the murder caused by a misplaced double quote in MySQL

>>:  Install Ubuntu 18 without USB drive under Windows 10 using EasyUEFI

Recommend

Detailed explanation of MySQL clustered index and non-clustered index

1. Clustered Index Table data is stored in the or...

Process analysis of deploying ASP.NET Core applications on Linux system Docker

Table of contents 1. System environment 2. Operat...

The best explanation of HTTPS

Good morning everyone, I haven’t updated my artic...

MySQL database constraints and data table design principles

Table of contents 1. Database constraints 1.1 Int...

Steps to install MySQL on Windows using a compressed archive file

Recently, I need to do a small verification exper...

Detailed installation tutorial of mysql-8.0.11-winx64.zip

Download the zip installation package: Download a...

Docker image loading principle

Table of contents Docker images What is a mirror?...

jQuery canvas generates a poster with a QR code

This article shares the specific code for using j...

Examples of new selectors in CSS3

Structural (position) pseudo-class selector (CSS3...

A brief discussion on the role of Vue3 defineComponent

Table of contents defineComponent overload functi...