Use js to write a simple snake game

Use js to write a simple snake game

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

The code is as follows:

HTML 5 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>Greedy Snake</title>
    <style>
        #scence{
            width: 800px;
            height: 600px;
            border: 1px solid #000;
            margin: 50px auto;
            background-color: aliceblue;
            position: relative;
            overflow: hidden;
        }
       .head{
           position: absolute;
           width: 20px;
           height: 20px;
           background-color: #000;
       }
       .tail{
        position: absolute;
           width: 20px;
           height: 20px;
           background-color: grey;       
       }
    </style>
</head>
<body>
    <div id="scence">

    </div>
</body>
</html>
<script src="tools.js"></script>
<script src="../贪吃蛇/snake.js"></script>
<script src="food.js"></script>
<script src="game.js"></script>

js part

tools.js

function getStyle(ele, styleObj) {
    for (const key in styleObj) {
        ele.style[key] = styleObj[key];
    }   
}
function getRandom(a, b) {
    return Math.floor(Math.random() * (b - a) + a +1)
}

snake.js

function Snake() {
    this.scence = document.querySelector('#scence');
    this.body = [
        [0, 0, 'grey', null],
        [0, 1, 'grey', null],
        [0, 2, '#000', null]
    ];
    this.dir = 'right';
    this.lastdir = 'right';
    this.width = 20;
    this.height = 20;
    this.scence_w = scence.offsetWidth;
    this.scence_h = scence.offsetHeight;
}
Snake.prototype.found = function () {
    for (let i = 0; i < this.body.length; i++) {
        if (this.body[i][3] == null) {
            this.body[i][3] = document.createElement('div');
        }
        getStyle(this.body[i][3], {
            width: this.width + 'px',
            height: this.height + 'px',
            position: 'absolute',
            top: this.height * (this.body[i][0]) + 'px',
            left: this.width * (this.body[i][1]) + 'px',
            backgroundColor: this.body[i][2]
        });
        this.scence.appendChild(this.body[i][3]);
    }
}
//Movement function Snake.prototype.move = function () {
    var length = this.body.length;
    for (let i = 0; i < length - 1; i++) {
        this.body[i][0] = this.body[i + 1][0];
        this.body[i][1] = this.body[i + 1][1];
    }
    let snakehead = this.body[length - 1]
    switch (this.dir) {
        case 'right':
            snakehead[1] += 1;
            break;
        case 'left':
            snakehead[1] -= 1
            break;
        case 'up':
            snakehead[0] -= 1
            break;
        case 'down':
            snakehead[0] += 1
            break;
    }
    this.lastdir = this.dir;
    snake.found();
}
// Timing movement Snake.prototype.shift = function () {
    document.onkeydown = (e) => {
        e = e || window.event;
        let key = e.keyCode;
        switch (key) {
            case 39:
                if (this.lastdir == 'left') {
                    this.dir = 'left'
                } else {
                    this.dir = 'right'
                };
                break;
            case 37:
                if (this.lastdir == 'right') {
                    this.dir = 'right'
                } else {
                    this.dir = 'left'
                };
                break;
            case 38:
                if (this.lastdir == 'down') {
                    this.dir = 'down'
                } else {
                    this.dir = 'up'
                };
                break;
            case 40:
                if (this.lastdir == 'up') {
                    this.dir = 'up'
                } else {
                    this.dir = 'down'
                };
                break;
        }
    }
}

//Game over Snake.prototype.over = function () {
    let top = this.body[this.body.length - 1][0];
    let left = this.body[this.body.length - 1][1];
    let width = this.scence_w / this.width - 1;
    let height = this.scence_w / this.height - 1;
    if (top < 0 || left < 0 || top > width || left > height) {
        clearInterval(timeid)
        alert('game over');
    }
    for (let i = 0; i < this.body.length - 1; i++) {
        if (top == this.body[i][0] && left == this.body[i][1]) {
            clearInterval(timeid)
            alert('game over');
        }
    }
}


let snake = new Snake();
snake.found();
snake.shift();
timeid = setInterval(function () {
    snake.move();
    food.eat();
    snake.over()
}, 100)

food.js

function Food() {
  this.scence = document.querySelector('#scence');
  this.width = 20;
  this.height = 20;
  this.body = [-1, -1, 'red', null];
  this.scence_w = scence.offsetWidth;
  this.scence_h = scence.offsetHeight;
  
}
//Food generation Food.prototype.crteate = function () {
  this.body[1] = getRandom(0, this.scence_w / this.width-1);
  this.body[0] = getRandom(0, this.scence_h / this.height-1);
  this.body[3] = document.createElement('div');
  getStyle(this.body[3], {
    width: this.width + 'px',
    height: this.height + 'px',
    position: 'absolute',
    top: this.height * (this.body[0] ) + 'px',
    left: this.width * (this.body[1] ) + 'px',
    backgroundColor: this.body[2],
    borderRadius: '50%',
  });
  this.scence.appendChild(this.body[3]);


}
//The snake eats the food Food.prototype.eat=function(){
  // const new = [0, 0, 'grey', null]
if(snake.body[snake.body.length-1][0]==this.body[0] && snake.body[snake.body.length-1][1]==this.body[1]){
  this.scence.removeChild(this.body[3]);
  this.crteate();
  snake.body.unshift([-1,-1,"grey",null])
}
}
let food = new Food();
food.crteate();
food.eat();

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
  • 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
  • Writing Snake Game with Native JS
  • js to implement the snake game with comments
  • JavaScript exquisite snake implementation process

<<:  Detailed explanation of the usage and differences of MySQL views and indexes

>>:  Detailed explanation of Linux redirection usage

Recommend

How to choose the right index in MySQL

Let’s take a look at a chestnut first EXPLAIN sel...

How to implement checkbox & radio alignment

Not only do different browsers behave differently...

Summary of commonly used SQL in MySQL operation tables

1. View the types of fields in the table describe...

How to implement rounded corners with CSS3 using JS

I found an example when I was looking for a way t...

Linux system calls for operating files

Table of contents 1. Open the file Parameter Intr...

Vue realizes the card flip effect

This article example shares the specific code of ...

Border-radius IE8 compatible processing method

According to canisue (http://caniuse.com/#search=...

js to implement file upload style details

Table of contents 1. Overview 2. Parameters for c...

Vue implements tab navigation bar and supports left and right sliding function

This article mainly introduces: using Vue to impl...

Summary of basic SQL statements in MySQL database

This article uses examples to describe the basic ...

CSS flex several multi-column layout

Basic three-column layout .container{ display: fl...

CSS cleverly uses gradients to achieve advanced background light animation

accomplish This effect is difficult to replicate ...