本文实例为大家分享了JS实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下

效果图:

完整代码如下:

html:

<!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="index.css" >
    <script src="index.js"></script>
</head>
 
<body>
    <div class="content">
        <div class="btn startBtn"><button></button></div>
        <div class="btn pauseBtn"><button></button></div>
        <div id="snakeWrap">
            <!-- <div class="snakeHead"></div>
            <div class="snakeBody"></div>
            <div class="food"></div> -->
        </div>
    </div>
 
</body>
 
</html>

css:

.content {
    position: relative;
    width: 640px;
    height: 640px;
    margin: 100px auto;
}
 
.btn {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background-color: black;
    opacity: .1;
    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-image: url(../贪吃蛇/img/btn.gif);
    margin-left: -100px;
    margin-top: -40px;
}
 
.pauseBtn {
    display: none;
}
 
.pauseBtn button {
    width: 70px;
    height: 70px;
    background-image: url(../贪吃蛇/img/btn4.png);
    margin-left: -35px;
    margin-top: -35px;
}
 
#snakeWrap {
    width: 600px;
    height: 600px;
    background-color: pink;
    border: 20px solid purple;
    position: relative;
}
 
 
/* #snakeWrap div {
    width: 20px;
    height: 20px;
} */
 
.snakeHead {
    background-image: url(../贪吃蛇/img/snake.png);
    background-size: cover;
}
 
.snakeBody {
    background-color: rgb(85, 146, 126);
    border-radius: 50%;
}
 
.food {
    background-image: url(../贪吃蛇/img/草莓.png);
    background-size: cover;
}

js:

window.addEventListener('load', function() {
    // 声明方块的宽高,行数和列数
    var sw = 20,
        sh = 20,
        tr = 30,
        td = 30;
 
    var snake = null, //蛇的实例
        food = null, //食物的实例
        game = null; //游戏的实例
 
    function Square(x, y, classname) {
        this.x = sw * x;
        this.y = sh * y;
        this.class = classname;
 
        this.viewContent = document.createElement('div'); //方块对应的DOM元素
        this.viewContent.className = this.class;
        this.parent = document.getElementById('snakeWrap'); //方块的父级
    }
    //创建方块DOM,并添加到页面里
    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);
 
    };
    Square.prototype.remove = function() {
        this.parent.removeChild(this.viewContent);
    };
    //蛇
    function Snake() {
        this.head = null //存蛇头的信息
        this.tail = null //存蛇尾的信息
        this.pos = []; //存蛇身上每个方块的位置
 
        //存储蛇走的方向,用一个对象来表示
        this.directionNum = {
            left: {
                x: -1,
                y: 0,
                rotate: 180
            },
            right: {
                x: 1,
                y: 0,
                rotate: 0
            },
            up: {
                x: 0,
                y: -1,
                rotate: -90
            },
            down: {
                x: 0,
                y: 1,
                rotate: 90
            }
        };
    }
    //初始化
    Snake.prototype.init = function() {
        //创建蛇头
        var snakeHead = new Square(2, 0, 'snakeHead');
        snakeHead.create();
        this.head = snakeHead; //存储蛇头信息
        this.pos.push([2, 0]); //把蛇头的位置存起来
 
        //创建蛇身体1
        var snakeBody1 = new Square(1, 0, 'snakeBody');
        snakeBody1.create();
        this.pos.push([1, 0]); //把蛇身1的坐标存起来
 
        //创建蛇身体2
        var snakeBody2 = new Square(0, 0, 'snakeBody');
        snakeBody2.create();
        this.tail = snakeBody2; //把蛇尾的信息存起来
        this.pos.push([0, 0]); //把蛇身1的坐标存起来
 
        //形成链表关系
        snakeHead.last = null;
        snakeHead.next = snakeBody1;
 
        snakeBody1.last = snakeHead;
        snakeBody1.next = snakeBody2;
 
        snakeBody2.last = snakeBody1;
        snakeBody2.next = null;
 
        //给蛇添加一条属性,用来表示蛇的走向
        this.direction = this.directionNum.right; //默认让蛇往右走
    };
 
    //该方法用来获取蛇头的下一个位置对应的元素,要根据元素做不同的事情
    Snake.prototype.getNextPos = function() {
        var nextPos = [ //蛇头要走的下一个点的坐标
            this.head.x / sw   this.direction.x,
            this.head.y / sh   this.direction.y
        ];
        // console.log(nextPos[0]);
 
        //下个点是自己,游戏结束
        var selfCollied = false; //是否撞到自己,默认是否
        //value表示数组中的某一项
        this.pos.forEach(function(value) {
            // console.log(nextPos[0], value[0]);
            if (value[0] == nextPos[0] && value[1] == nextPos[1]) {
                selfCollied = true;
                // console.log(2);
            }
        });
        if (selfCollied) {
            console.log('撞到自己了!');
            this.strategies.die.call(this);
            return;
        }
 
        // 下个点是墙,游戏结束
        if (nextPos[0] < 0 || nextPos[1] < 0 || nextPos[0] > td - 1 || nextPos[1] > tr - 1) {
            console.log('撞墙!');
            this.strategies.die.call(this);
            return;
        }
 
        // 下个点是食物,吃
        if (food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]) {
            //如这条件成立,说明蛇头走的下一点是食物的点
            console.log('撞到食物了');
            this.strategies.eat.call(this);
            return;
        }
 
        // 下个点什么都不是,继续走
        this.strategies.move.call(this);
 
    };
    // 处理碰撞后要做的事
    Snake.prototype.strategies = {
        move: function(format) { //format这个参数用于决定要不要删除最后一个方块(蛇尾),当传了这个参数就表示要做的事情是吃
            //创建新身体(在旧蛇头的位置)
 
            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();
 
            //创建新的蛇头(蛇头下一个要走到的点nextPos)
            var newHead = new Square(this.head.x / sw   this.direction.x, this.head.y / sh   this.direction.y, 'snakeHead');
 
            //更新链表关系
            newHead.next = newBody;
            newHead.last = null;
            newBody.last = newHead;
            newHead.viewContent.style.transform = 'rotate('   this.direction.rotate   'deg)';
            newHead.create();
 
            //蛇身上的每一个方块的坐标也要更新
            this.pos.splice(0, 0, [this.head.x / sw   this.direction.x, this.head.y / sh   this.direction.y])
            this.head = newHead; //还要把this.head的信息更新一下
 
            if (!format) { //如果format的值为false,表示需要删除(除了吃之外的操作)
                this.tail.remove();
                this.tail = this.tail.last;
                this.pos.pop();
            }
        },
        eat: function() {
            this.strategies.move.call(this, true);
            createFood();
            game.score  ;
        },
        die: function() {
            // console.log('die');
            game.over();
        }
    }
 
 
    snake = new Snake();
 
 
 
    //创建食物
    function createFood() {
        //食物小方块的随机坐标
 
        var x = null;
        var y = null;
 
        var include = true; //循环跳出的条件,true表示食物坐标在蛇身上。(需要继续循环)false表示食物的坐标不再蛇身上(不用继续循环)
        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;
                }
            });
        }
 
        //生成食物
        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();
        }
 
    }
    //创建游戏逻辑
    function Game() {
        this.timer = null;
        this.score = 0;
    }
    Game.prototype.init = function() {
        snake.init();
        // snake.getNextPos();
        createFood();
        var flag = true;
        document.onkeydown = function(ev) {
            //当蛇在往右走,不能按左键
            if (ev.which == 37 && snake.direction != snake.directionNum.right) {
                if (flag) {
                    flag = false;
                    setTimeout(function() {
                        snake.direction = snake.directionNum.left;
                        flag = true;
                    }, 150)
                }
 
            } else if (ev.which == 38 && snake.direction != snake.directionNum.down) {
                if (flag) {
                    flag = false;
                    setTimeout(function() {
                        snake.direction = snake.directionNum.up;
                        flag = true;
                    }, 150)
                }
            } else if (ev.which == 39 && snake.direction != snake.directionNum.left) {
                if (flag) {
                    flag = false;
                    setTimeout(function() {
                        snake.direction = snake.directionNum.right;
                        flag = true;
                    }, 150)
                }
            } else if (ev.which == 40 && snake.direction != snake.directionNum.up) {
                if (flag) {
                    flag = false;
                    setTimeout(function() {
                        snake.direction = snake.directionNum.down;
                        flag = true;
                    }, 150)
                }
            }
        }
        this.start();
    };
    //开始游戏
    Game.prototype.start = function() {
        this.timer = setInterval(function() {
            snake.getNextPos();
        }, 150);
    };
    //暂停游戏
    Game.prototype.pause = function() {
        clearInterval(this.timer);
    };
    //游戏结束
    Game.prototype.over = function() {
        clearInterval(this.timer);
        alert('你的得分为'   this.score);
 
        //游戏回到初始状态
        var snakeWrap = document.getElementById('snakeWrap');
        snakeWrap.innerHTML = '';
 
        snake = new Snake();
        game = new Game();
 
        var startBtnWrap = document.querySelector('.startBtn');
        startBtnWrap.style.display = 'block';
    };
    //开启游戏
    game = new Game();
    var startBtn = document.querySelector('.startBtn button');
    console.log(startBtn);
    startBtn.onclick = function() {
        startBtn.parentNode.style.display = 'none';
        game.init();
    };
    //暂停游戏
    var snakeWrap = document.getElementById('snakeWrap');
    console.log(snakeWrap);
    var pauseBtn = document.querySelector('.pauseBtn button');
    console.log(pauseBtn);
    snakeWrap.onclick = function() {
        game.pause();
        pauseBtn.parentNode.style.display = 'block';
        console.log(123);
    };
    pauseBtn.onclick = function() {
        game.start();
        pauseBtn.parentNode.style.display = 'none';
    }
})

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

用JS实现贪吃蛇游戏的更多相关文章

  1. html5 拖拽及用 js 实现拖拽功能的示例代码

    这篇文章主要介绍了html5 拖拽及用 js 实现拖拽,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  2. amaze ui 的使用详细教程

    这篇文章主要介绍了amaze ui 的使用详细教程,本文通过多种方法给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  3. H5 canvas实现贪吃蛇小游戏

    本篇文章主要介绍了H5 canvas实现贪吃蛇小游戏,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  4. swift皮筋弹动发射飞机ios源码

    这是一个款采用swift实现的皮筋弹动发射飞机游戏源码,游戏源码比较详细,大家可以研究学习一下吧。

  5. Swift与Js通过WebView交互

    开发环境:Swfit2.3XCode8.2基础概念jscontext,jscontext是代表JS的执行环境,通过-evaluateScript:方法就可以执行一JS代码JSValue,JSValue封装了JS与ObjC中的对应的类型,以及调用JS的API等JSExport,JSExport是一个协议,遵守此协议,就可以定义我们自己的协议,在协议中声明的API都会在JS中暴露出来,才能调用Swif

  6. JSCore swift

    如果双方相互引用,会造成循环引用,而导致内存泄露。以上是Jscore的基本使用,比较简单

  7. Swift WKWebView的js调用swift

    最近项目需求,需要用到JavaScriptCore和WebKit,但是网上的资源有限,而且比较杂,都是一个博客复制另外一个博客,都没有去实际敲代码验证,下面给大家分享一下我的学习过程。

  8. Swift WKWebView的swift调用js

    不多说,直接上代码:在html里面要添加的的代码,显示swift传过去的参数:这样就实现了swift给js传参数和调用!

  9. 在 Swift 專案中使用 Javascript:編寫一個將 Markdown 轉為 HTML 的編輯器

    你有強烈的好奇心,希望在你的iOS專案中使用JavaScript。jscontext中的所有值都是JSValue對象,JSValue類用於表示任意類型的JavaScript值。因此,我們既需要寫Swift代碼也要寫JavaScript代碼。此外,我們還會在JavaScript中按照這個類的定義來創建一個對象并對其屬性進行賦值。從Swift中呼叫JavaScript就如介紹中所言,JavaScriptCore中最主要的角色就是jscontext類。一個jscontext對象是位於JavaScript環境和本

  10. swift - WKWebView JS 交互

    本文介绍WKWebView怎么与js交互,至于怎么用WKWebView这里就不介绍了HTML代码APP调JS代码结果JS给APP传参数首先注册你需要监听的js方法名2.继承WKScriptMessageHandler并重写userContentController方法,在该方法里接收JS传来的参数3.结果

随机推荐

  1. js中‘!.’是什么意思

  2. Vue如何指定不编译的文件夹和favicon.ico

    这篇文章主要介绍了Vue如何指定不编译的文件夹和favicon.ico,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  3. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  4. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  5. AngularJs上传前预览图片的实例代码

    使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,怎么实现这样的功能呢?今天小编给大家分享AugularJs上传前预览图片的实现代码,需要的朋友参考下吧

  6. JavaScript面向对象编程入门教程

    这篇文章主要介绍了JavaScript面向对象编程的相关概念,例如类、对象、属性、方法等面向对象的术语,并以实例讲解各种术语的使用,非常好的一篇面向对象入门教程,其它语言也可以参考哦

  7. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  8. javascript 动态调整图片尺寸实现代码

    在自己的网站上更新文章时一个比较常见的问题是:文章插图太宽,使整个网页都变形了。如果对每个插图都先进行缩放再插入的话,太麻烦了。

  9. jquery ajaxfileupload异步上传插件

    这篇文章主要为大家详细介绍了jquery ajaxfileupload异步上传插件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. React学习之受控组件与数据共享实例分析

    这篇文章主要介绍了React学习之受控组件与数据共享,结合实例形式分析了React受控组件与组件间数据共享相关原理与使用技巧,需要的朋友可以参考下

返回
顶部