用js编写简单的贪吃蛇小游戏

 更新时间:2021年09月10日 16:04:27   作者:惊蛰skk  
这篇文章主要为大家详细介绍了用js编写简单的贪吃蛇小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了js编写简单的贪吃蛇小游戏的具体代码,供大家参考,具体内容如下

代码如下:

HTML 5 部分

<!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>
        #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部分

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]);
    }
}
//运动函数
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();
}
//计时运动
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;
        }
    }
}

//游戏结束
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.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]);


}
//蛇吃到食物
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();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 手把手教你用JS实现回车评论功能

    手把手教你用JS实现回车评论功能

    最近在写一个问答功能,类似于评论,下面这篇文章主要给大家介绍了关于如何用JS实现回车评论功能的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2023-06-06
  • js实现遍历含有input的table实例

    js实现遍历含有input的table实例

    这篇文章主要介绍了js实现遍历含有input的table方法,结合实例形式分析了jsp读取数据库动态生成table及JavaScript遍历table的相关技巧,需要的朋友可以参考下
    2015-12-12
  • 原生JS实现简单的无缝自动轮播效果

    原生JS实现简单的无缝自动轮播效果

    轮播效果是老生常谈的话题,今天小编通过实例代码给大家分享原生JS实现简单的无缝自动轮播效果,感兴趣的朋友跟随小编一起学习吧
    2018-09-09
  • 前端存储后端响应数据超详细的实现方式和注意事项

    前端存储后端响应数据超详细的实现方式和注意事项

    前端通过多种方式向后端获取数据,下面这篇文章主要介绍了前端存储后端响应数据超详细的实现方式和注意事项,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-03-03
  • networkInformation.downlink测用户网速方法详解

    networkInformation.downlink测用户网速方法详解

    这篇文章主要为大家介绍了networkInformation.downlink测用户网速方法详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • 本地JS文件批量压缩的操作方法

    本地JS文件批量压缩的操作方法

    这篇文章主要介绍了本地JS文件批量压缩的方法,由于之前压缩的JS文件都比较少,都是手动压缩的。这次需要压缩的文件比较多,所以用了批量压缩,特此记录一下,方便大家和自己以后再用到的时候备忘
    2022-12-12
  • JavaScript中获取随机数的几种方法小结

    JavaScript中获取随机数的几种方法小结

    本文总结了JavaScript中获取随机数的几种方法,包括Math.random()、生成指定范围的随机数和从数组中随机选择一个元素,具有一定的参考价值,感兴趣的可以了解一下
    2025-02-02
  • JS+DIV+CSS实现仿表单下拉列表效果

    JS+DIV+CSS实现仿表单下拉列表效果

    这篇文章主要介绍了JS+DIV+CSS实现仿表单下拉列表效果,涉及javascript鼠标事件及页面元素的动态操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-08-08
  • js点击选择文本的方法

    js点击选择文本的方法

    这篇文章主要介绍了js点击选择文本的方法,涉及针对html节点的操作与选中技巧,非常具有实用价值,需要的朋友可以参考下
    2015-02-02
  • Redux中进行异步操作(网络请求)的示例方案

    Redux中进行异步操作(网络请求)的示例方案

    这篇文章主要介绍了Redux中进行异步操作(网络请求)的方案,本文结合示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-12-12

最新评论