贪吃蛇 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>

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

目录
相关文章
|
5月前
|
监控 负载均衡 JavaScript
有哪些有效的方法可以优化Node.js应用的性能?
有哪些有效的方法可以优化Node.js应用的性能?
292 69
|
5月前
|
人工智能 自然语言处理 JavaScript
通义灵码2.5实战评测:Vue.js贪吃蛇游戏一键生成
通义灵码基于自然语言需求,快速生成完整Vue组件。例如,用Vue 2和JavaScript实现贪吃蛇游戏:包含键盘控制、得分系统、游戏结束判定与Canvas动态渲染。AI生成的代码符合规范,支持响应式数据与事件监听,还能进阶优化(如增加启停按钮、速度随分数提升)。传统需1小时的工作量,使用通义灵码仅10分钟完成,大幅提升开发效率。操作简单:安装插件、输入需求、运行项目即可实现功能。
253 4
 通义灵码2.5实战评测:Vue.js贪吃蛇游戏一键生成
|
4月前
|
JavaScript Linux 内存技术
Debian 11系统下Node.js版本更新方法详解
本指南详细介绍在Linux系统中安装和管理Node.js的步骤。首先检查现有环境,包括查看当前版本和清除旧版本;接着通过NodeSource仓库安装最新版Node.js并验证安装结果。推荐使用nvm(Node Version Manager)进行多版本管理,便于切换和设置默认版本。同时,提供常见问题解决方法,如权限错误处理和全局模块迁移方案,以及版本回滚操作,确保用户能够灵活应对不同需求。
289 0
|
4月前
|
JavaScript Linux 内存技术
Debian 11系统下Node.js版本更新方法
Debian 11更新Node.js主要就是这三种方式,无论你是初涉其中的新手还是找寻挑战的专家,总有一种方式能满足你的需求。现在,你已经是这个
314 80
|
6月前
|
JavaScript 前端开发 Java
【Java进阶】详解JavaScript事件
总的来说,JavaScript事件是JavaScript交互设计的核心,理解和掌握JavaScript事件对于编写高效、响应式的网页应用至关重要。
98 15
|
8月前
|
前端开发 JavaScript
有没有方法可以保证在JavaScript中多个异步操作的执行顺序?
有没有方法可以保证在JavaScript中多个异步操作的执行顺序?
299 58
|
6月前
|
JavaScript 前端开发 Java
js 垃圾回收机制的方法
JS回收机制方法讲解
|
7月前
|
JavaScript 前端开发 Java
深入理解 JavaScript 中的 Array.find() 方法:原理、性能优势与实用案例详解
Array.find() 是 JavaScript 数组方法中一个非常实用和强大的工具。它不仅提供了简洁的查找操作,还具有性能上的独特优势:返回的引用能够直接影响原数组的数据内容,使得数据更新更加高效。通过各种场景的展示,我们可以看到 Array.find() 在更新、条件查找和嵌套结构查找等场景中的广泛应用。 在实际开发中,掌握 Array.find() 的特性和使用技巧,可以让代码更加简洁高效,特别是在需要直接修改原数据内容的情形。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一
|
7月前
|
移动开发 运维 供应链
通过array.some()实现权限检查、表单验证、库存管理、内容审查和数据处理;js数组元素检查的方法,some()的使用详解,array.some与array.every的区别(附实际应用代码)
array.some()可以用来权限检查、表单验证、库存管理、内容审查和数据处理等数据校验工作,核心在于利用其短路机制,速度更快,节约性能。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
7月前
|
供应链 JavaScript 前端开发
通过array.every()实现数据验证、权限检查和一致性检查;js数组元素检查的方法,every()的使用详解,array.some与array.every的区别(附实际应用代码)
array.every()可以用来数据验证、权限检查、一致性检查等数据校验工作,核心在于利用其短路机制,速度更快,节约性能。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~