贪吃蛇 js 原型方法 事件 计时器

简介: 通过 原型方法 事件 计时器 等实现贪吃蛇效果。

键盘上下左右控制

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .map {
            width: 400px;
            height: 400px;
            background-color: #ccc;
            position: relative;
        }
    </style>
</head>
<body>
<div class="map">

</div>
<script>
    //food div
    (function () {
        var elements = [];

        function Food(x, y, width, height, color) {
            // 横纵坐标 width height backgroundColor
            this.x = x || 0;
            this.y = y || 0;
            this.width = width || 20;
            this.height = height || 20;
            this.color = color || "green";
        }

        Food.prototype.init = function (map) {
            // delete div
            reomve();
            // creat div
            var div = document.createElement('div');
            // add div
            map.appendChild(div);
            // set div style
            div.style.width = this.width + "px";
            div.style.height = this.height + "px";
            div.style.backgroundColor = this.color;
            // Out of document stream 脱离文档流
            div.style.position = "absolute";
            // random横纵坐标
            this.x = parseInt(Math.random() * (map.offsetWidth / this.width)) * this.width;
            this.y = parseInt(Math.random() * (map.offsetHeight / this.height)) * this.height;
            div.style.left = this.x + "px";
            div.style.top = this.y + "px";
            elements.push(div)
        };

        // private func delete div
        function reomve() {
            for (var i = 0; i < elements.length; i++) {
                var ele = elements[i];
                // find child element's father remove this
                ele.parentNode.removeChild(ele);
                // delete child
                elements.splice(i, 1);
            }
        }

        // global
        window.Food = Food;
    }());

    // snake
    (function () {
        var elements = [];

        function Snake(width, height, direction) {
            // snack Each part width
            this.width = width || 20;
            this.height = height || 20;

            // snack's body
            this.body = [
                {x: 3, y: 2, color: "red"}, //head
                {x: 2, y: 2, color: "black"}, //body
                {x: 1, y: 2, color: "black"} //tail
            ];

            // direction
            this.direction = direction || "right"
        }

        Snake.prototype.init = function (map) {
            // delete snake
            remove();
            // loop body
            for (var i = 0; i < this.body.length; i++) {
                var obj = this.body[i];
                var div = document.createElement("div");
                // add div to map
                map.appendChild(div);
                // set div style
                div.style.position = "absolute";
                div.style.width = this.width + "px";
                div.style.height = this.height + "px";
                // x,y
                div.style.left = obj.x * this.width + "px";
                div.style.top = obj.y * this.height + "px";
                div.style.backgroundColor = obj.color;
                // add div to elements
                elements.push(div);
            }
        };
        Snake.prototype.move = function (food, map) {
            // change body x, y
            for (i = this.body.length - 1; i > 0; i--) {
                this.body[i].x = this.body[i - 1].x;
                this.body[i].y = this.body[i - 1].y;
            }
            // select direction change x,y
            switch (this.direction) {
                case "right":
                    this.body[0].x += 1;
                    break;
                case "left":
                    this.body[0].x -= 1;
                    break;
                case "top":
                    this.body[0].y -= 1;
                    break;
                case "bottom":
                    this.body[0].y += 1;
                    break;
            }
            // judgement food x,y snake x,y
            let snakeX = this.body[0].x * this.width;
            let snakeY = this.body[0].y * this.height;
            let foodX = food.x;
            let foodY = food.y;
            // judgement snake or food x,y
            if (snakeX == foodX && snakeY == foodY) {
                // get last body
                var last = this.body[this.body.length - 1];
                this.body.push({
                    x: last.x,
                    y: last.y,
                    color: last.color,
                });
                // delete food init food
                food.init(map)

            }
            // console.log(foodX, foodY)
        };

        function remove() {
            for (var i = elements.length - 1; i > -1; i--) {
                // find parent remove child element
                var ele = elements[i];
                //from map remove child element
                ele.parentNode.removeChild(ele);
                elements.splice(i, 1)
            }
        }

        // Snake.prototype.init(document.querySelector(".map"));
        // global
        window.Snake = Snake;
    }());
    // game
    (function () {
        function Game(map) {
            this.food = new Food();
            this.snake = new Snake();
            this.map = map;
        }

        // init game food snake
        Game.prototype.init = function () {
            this.food.init(this.map);
            this.snake.init(this.map);
            // console.log(this);
            this.RunSnake();
            this.bindkey();
        };
        // run snake
        Game.prototype.RunSnake = function () {
            // run
            var IntervalId = setInterval(function () {
                // 此时this为window
                this.snake.move(this.food, this.map);
                this.snake.init(this.map);
                // max x,y
                let MaxX = this.map.offsetWidth / this.snake.width;
                let MaxY = this.map.offsetHeight / this.snake.height;
                let x = this.snake.body[0].x;
                let y = this.snake.body[0].y;
                // console.log(this.snake.body[0].x + " " + this.snake.body[0].y + "X" + MaxX + "Y" + MaxY);
                if (x < 0 || x > MaxX || y < 0 || y > MaxY) {
                    // console.log(this.x+" "+this.y);
                    clearInterval(IntervalId);
                    window.alert("ganmeover!")
                }
                // 使用bindl改变this的指向
            }.bind(this), 150)
        };
        //keyboard down event
        Game.prototype.bindkey = function () {
            // get keyboard down
            document.addEventListener('keydown', function (e) {
                //获取按键的值
                switch (e.keyCode) {
                    case 37:
                        this.snake.direction = "left";
                        break;
                    case 38:
                        this.snake.direction = "top";
                        break;
                    case 39:
                        this.snake.direction = "right";
                        break;
                    case 40:
                        this.snake.direction = "bottom";
                        break;
                }
            }.bind(this), false)
        };
        window.Game = Game
    }());
    var gm = new Game(document.querySelector(".map"));
    gm.init()

    // console.log(fd.x+"===="+fd.y)
    // console.log(fd.width)
</script>

</body>
</html>

想要试验效果的可以到我的个人网站上体验
夏溪辰的博客-贪吃蛇

目录
相关文章
|
11天前
|
JavaScript 前端开发 Java
js 垃圾回收机制的方法
JS回收机制方法讲解
|
2月前
|
前端开发 JavaScript
有没有方法可以保证在JavaScript中多个异步操作的执行顺序?
有没有方法可以保证在JavaScript中多个异步操作的执行顺序?
93 58
|
5月前
|
JavaScript 前端开发 程序员
前端原生Js批量修改页面元素属性的2个方法
原生 Js 的 getElementsByClassName 和 querySelectorAll 都能获取批量的页面元素,但是它们之间有些细微的差别,稍不注意,就很容易弄错!
107 1
|
1月前
|
JavaScript 前端开发 Java
深入理解 JavaScript 中的 Array.find() 方法:原理、性能优势与实用案例详解
Array.find() 是 JavaScript 数组方法中一个非常实用和强大的工具。它不仅提供了简洁的查找操作,还具有性能上的独特优势:返回的引用能够直接影响原数组的数据内容,使得数据更新更加高效。通过各种场景的展示,我们可以看到 Array.find() 在更新、条件查找和嵌套结构查找等场景中的广泛应用。 在实际开发中,掌握 Array.find() 的特性和使用技巧,可以让代码更加简洁高效,特别是在需要直接修改原数据内容的情形。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一
|
1月前
|
移动开发 运维 供应链
通过array.some()实现权限检查、表单验证、库存管理、内容审查和数据处理;js数组元素检查的方法,some()的使用详解,array.some与array.every的区别(附实际应用代码)
array.some()可以用来权限检查、表单验证、库存管理、内容审查和数据处理等数据校验工作,核心在于利用其短路机制,速度更快,节约性能。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
1月前
|
供应链 JavaScript 前端开发
通过array.every()实现数据验证、权限检查和一致性检查;js数组元素检查的方法,every()的使用详解,array.some与array.every的区别(附实际应用代码)
array.every()可以用来数据验证、权限检查、一致性检查等数据校验工作,核心在于利用其短路机制,速度更快,节约性能。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
5月前
|
监控 JavaScript Java
Node.js中内存泄漏的检测方法
检测内存泄漏需要综合运用多种方法,并结合实际的应用场景和代码特点进行分析。及时发现和解决内存泄漏问题,可以提高应用的稳定性和性能,避免潜在的风险和故障。同时,不断学习和掌握内存管理的知识,也是有效预防内存泄漏的重要途径。
412 62
|
3月前
|
JavaScript 前端开发 测试技术
盘点原生JavaScript中直接触发事件的方式
本文全面探讨了原生JavaScript中触发事件的多种方式,包括`dispatchEvent`、`Event`构造函数、`CustomEvent`构造器、直接调用事件处理器以及过时的`createEvent`和`initEvent`方法。通过技术案例分析,如模拟点击事件、派发自定义数据加载事件和实现提示框系统,帮助开发者掌握这些方法在实际开发中的应用,提升灵活性与兼容性。
76 3
|
3月前
|
JavaScript 前端开发 开发者
JavaScript字符串的常用方法
在JavaScript中,字符串处理是一个非常常见的任务。JavaScript提供了丰富的字符串操作方法,使开发者能够高效地处理和操作字符串。本文将详细介绍JavaScript字符串的常用方法,并提供示例代码以便更好地理解和应用这些方法。
79 13
|
5月前
|
JavaScript 前端开发
js+jquery实现贪吃蛇经典小游戏
本项目采用HTML、CSS、JavaScript和jQuery技术,无需游戏框架支持。通过下载项目文件至本地,双击index.html即可启动贪吃蛇游戏。游戏界面简洁,支持方向键控制蛇移动,空格键实现游戏暂停与恢复功能。
116 14