Writing Snake Game with Native JS

Writing Snake Game with Native JS

This article shares the specific code of writing a snake game in js for your reference. The specific content is as follows

I just finished learning js and imitated the tutorial to write my own js native applet.

HTML Part

<!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>Document</title>
    <link rel="stylesheet" href="./css/index.css" >
</head>
<body>
    <div class="content">
     <!-- Game start button-->
        <div class="btn startBtn"><button></button></div>
        <!-- Snake Body -->
        <div id="snakeWrap"></div>
    </div>
    <!-- Import external js files-->
    <script src="./js/index.js"></script>
</body>
</html>

CSS part

/* Overall style */
.content{
    width: 640px;
    height: 640px;
    margin: 100px auto;
    position: relative;
}
 .btn{
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    background-color: rgba(0, 0, 0, 0.3);
    z-index: 2;
}

.btn button{
    background: none;
    border: none;
    background-size: 100% 100%;

    cursor: pointer;
    outline: none;

    position: absolute;
    left: 50%;
    top: 50%;
}

.startBtn button{
    width: 200px;
    height: 80px;
    background: url(../images/Snipaste_2021-05-08_08-52-45.png) no-repeat;
    background-size: contain;
    margin-left: -100px;
    margin-top: 222px;
}

#snakeWrap{
    width: 600px;
    height: 600px;
    background: #73aad4;
    border: 20px solid #13649c;
    position: relative;
}

.snakeHead{
    background-color: yellowgreen;
    border-radius: 50%;
}

.snakeBody{
    background-color: black;
    border-radius: 50%;
}

.food{
    background-color: red;
    border-radius: 50%;
}

js part

var sw = 20, //width of a block sh = 20, //width of a block tr = 30, //number of rows td = 30; //number of columns var snake = null, //generate snake instance food = null; //generate food instance game = null; //create game instance //create and delete blocks when treating the whole as a small block moving (all subsequent blocks will be called)
// Square constructor function Square(x,y,classname){ //Corresponding to the three snake styles in CSS (snake head, snake body, snake tail)
    this.x = x * sw;
    this.y = y * sh;
    this.class = classname;
    this.viewContent = document.createElement('div');
    this.viewContent.className = this.class; //Add the corresponding css style to the created div this.parent = document.getElementById('snakeWrap');    
}

//Create the create method on the prototype chain of the block constructor to determine the specific information of the new div //this points to Square
Square.prototype.create = function(){
    this.viewContent.style.position = 'absolute';
    this.viewContent.style.width = sw + 'px';
    this.viewContent.style.height = sh + 'px';
    this.viewContent.style.left = this.x + 'px';
    this.viewContent.style.top = this.y + 'px';

    this.parent.appendChild(this.viewContent); //Add the newly created div to the page}

//Create a remove method on the prototype chain of the block constructor to delete the block when moving Square.prototype.remove = function(){
    this.parent.removeChild(this.viewContent);
}

//Snake function Snake(){
    this.head = null; //Store the snake's head information this.tail = null; //Store the snake's tail information this.pos = []; //Store the position of each block on the snake this.directionNum = { //Store the direction the snake is walking left : {
            x : -1,
            y : 0
        },
        right : {
            x : 1,
            y : 0
        },
        up : {
            x : 0,
            y : -1
        },
        down : {
            x : 0,
            y : 1
        }
    }
}

//this points to Snake
Snake.prototype.init = function(){ // Initialization // Create snake head var snakeHead = new Square(2,0,'snakeHead');
    snakeHead.create();
    this.head = snakeHead;
    this.pos.push([2,0]); //Store snake head information // Create snake body 1
    var snakeBody1 = new Square(1,0,'snakeBody');
    snakeBody1.create();
    this.pos.push([1,0]); //Store snake body information // Create snake tail var snakeBody2 = new Square(0,0,'snakeBody');
    snakeBody2.create();
    this.tail = snakeBody2;
    this.pos.push([0,0]); /Store the confidence of the snake's tail//Form a linked list relationship//The relationship between the snake's head, body and tail snakeHead.last = null;
    snakeHead.next = snakeBody1;

    snakeBody1.last = snakeHead;
    snakeBody1.next = snakeBody2;

    snakeBody2.last = snakeBody1;
    snakeBody2.next = null;

    //Add a default direction to the right for the snake this.direction = this.directionNum.right;
}

// Get the element corresponding to the next position of the snake head (this points to Snake)
// Get the coordinates of the next point and store them in the nextPos array Snake.prototype.getNextPos = function(){
    var nextPos = [
        this.head.x/sw + this.direction.x, //this.direction.x, y The following will bind the direction to the keyboard event to determine the location of the next point this.head.y/sh + this.direction.y
    ]
    
    // The next point is yourself. The game ends when you collide with yourself var selfCollied = false;
    this.pos.forEach(function(value){ //forEach traverses the array and compares the two arrays to see if there are duplicate coordinates if (value[0] == nextPos[0] && value[1] == nextPos[1]){
            selfCollied = true;
        }
    })
 
 //The game ends when you hit yourself if (selfCollied) {
        this.、
        .die.call(this);
        return;
    }

    // The next point is the wall game end if (nextPos[0] > 29 || nextPos[0] < 0 || nextPos[1] > 29 || nextPos[1] < 0) {
        this.strategies.die.call(this);
        return;
    }

    // The next point is food to eat if(food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]){
        this.strategies.eat.call(this);
        return;
    }

    // The next point is nothing, so go this.strategies.move.call(this);
}


// What to do after a collision Snake.prototype.strategies = {
    move : function(format){ //The parameter is used to determine whether to delete the snake tail // Create a newbody and delete the snake head var newBody = new Square(this.head.x/sw,this.head.y/sh,'snakeBody')
        newBody.next = this.head.next;
        newBody.next.last = newBody;
        newBody.last = null;
        this.head.remove();
        newBody.create();

        // Create a new snake head var newx = this.head.x/sw + this.direction.x;
        var newy = this.head.y/sh + this.direction.y;
        var newHead = new Square(newx,newy,'snakeHead')
        newHead.next = newBody;
        newBody.last = newHead;
        newHead.last = null;
        newHead.create();

        // Update the coordinates of the snake body this.pos.splice(0,0,[newx,newy]);
        this.head = newHead;

        //If it is false, then eat if(!format){
            this.tail.remove();
            this.tail = this.tail.last;

            this.pos.pop();
        }
    },
    eat : function(){
        this.strategies.move.call(this,true);
        game.score++;
        createFood();
    },
    die : function(){
        game.over();
    }
}


snake = new Snake();


// Create food function createFood(){
    // Food cube coordinates var x = null;
    var y = null;

    var include = true;
    while(include){
        x = Math.round(Math.random()*(td - 1));
        y = Math.round(Math.random()*(tr - 1));

        snake.pos.forEach(function(value){
            if(x != value[0] && y != value[1]){
                include = false;
            }
        });
    }
    // Generate food food = new Square(x,y,'food');
    food.pos = [x,y];

    var foodDom = document.querySelector('.food');
    if(foodDom){
        foodDom.style.left = x * sw + 'px';
        foodDom.style.top = y * sh + 'px';
    }else{
        food.create();
    }
}



// Create game logic function Game(){
    this.timer = null;
    this.score = 0;
}

Game.prototype.init = function(){
    snake.init();
    createFood();
 //The previous e.keycode e.which here has been disabled. Use e.key
    window.addEventListener('keydown',function(e){
        if(e.key == 'ArrowLeft' && snake.direction != snake.directionNum.right){
            snake.direction = snake.directionNum.left;
        }else if(e.key == 'ArrowUp' && snake.direction != snake.directionNum.down){
            snake.direction = snake.directionNum.up;
        }else if(e.key == 'ArrowRight' && snake.direction != snake.directionNum.left){
            snake.direction = snake.directionNum.right;
        }else if(e.key == 'ArrowDown' && snake.direction != snake.directionNum.up){
            snake.direction = snake.directionNum.down;
        }
    });
    this.start();
}

Game.prototype.start = function(){
    this.timer = setInterval(function(){
        snake.getNextPos();
    },0.0000000000000001)
}

Game.prototype.over = function(){
    clearInterval(this.timer);
    alert('Your score is' + this.score);


    // The game returns to the initial state var snakeWrap = document.getElementById('snakeWrap');
    snakeWrap.innerHTML = '';

    snake = new Snake();
    game = new Game();

    var startBtnWrap = document.querySelector('.startBtn');
    startBtnWrap.style.display = 'block';
}

// Start the game game = new Game();
var startBtn = document.querySelector('.startBtn button');
startBtn.onclick = function(){
    startBtn.parentNode.style.display = 'none';
    game.init();
}

This is a simple little game. If you have any questions, please correct me.

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
  • Native js to realize a simple snake game
  • js to implement the snake game with comments
  • JavaScript exquisite snake implementation process

<<:  Solution to the problem that MySQL in Windows system cannot input and display Chinese

>>:  Docker container from entry to obsession (recommended)

Recommend

How to use html table (to show the visual effect of web page)

We know that when using HTML on NetEase Blog, we ...

Basic security settings steps for centos7 server

Turn off ping scanning, although it doesn't h...

JavaScript implements AI tic-tac-toe game through the maximum and minimum algorithm

Without further ado, let’s run the screenshot dir...

Detailed explanation of the execution process of JavaScript engine V8

Table of contents 1. V8 Source 2. V8 Service Targ...

A brief discussion on CSS blocking merging and other effects

Non-orthogonal margins When margin is used, it wi...

Analysis of the Linux input subsystem framework principle

Input subsystem framework The linux input subsyst...

Full analysis of Vue diff algorithm

Table of contents Preface Vue update view patch s...

JavaScript BOM Explained

Table of contents 1. BOM Introduction 1. JavaScri...

vue-router hook function implements routing guard

Table of contents Overview Global hook function R...

Detailed explanation of Javascript basics loop

Table of contents cycle for for-in for-of while d...

The difference between name and value in input tag

type is the control used for input and output in t...

js to write the carousel effect

This article shares the specific code of js to ac...

Solve the problem of Navicat for Mysql connection error 1251 (connection failed)

Because what I wrote before was not detailed enou...