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

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

目录
相关文章
|
2天前
|
JavaScript 前端开发 容器
vue组件封装——固定宽高比的容器(2种方法:纯CSS实现 + JS实现)
vue组件封装——固定宽高比的容器(2种方法:纯CSS实现 + JS实现)
8 2
|
2天前
|
前端开发 JavaScript
js 等待接口访问成功后执行指定代码【3种方法】(含async await Promise的使用)
js 等待接口访问成功后执行指定代码【3种方法】(含async await Promise的使用)
6 1
|
2天前
|
JavaScript 前端开发 索引
JavaScript编码之路 【JavaScript之操作数组、字符串方法汇总】(三)
JavaScript编码之路 【JavaScript之操作数组、字符串方法汇总】(三)
8 1
|
1天前
|
JavaScript
JS 数组去重(含简单数组去重【5种方法】、对象数组去重【2种方法】)
JS 数组去重(含简单数组去重【5种方法】、对象数组去重【2种方法】)
7 0
|
1天前
|
JavaScript
js 内建对象的拓展 shim/polyfill ( 内含js 判断对象的属性是否存在的方法)
js 内建对象的拓展 shim/polyfill ( 内含js 判断对象的属性是否存在的方法)
3 0
|
1天前
|
JavaScript 前端开发 UED
|
2天前
|
JavaScript 前端开发 Java
JavaScript中的hasOwnProperty方法详解
JavaScript中的hasOwnProperty方法详解
|
2天前
|
JavaScript
js document.compatMode【详解】(含准确获取浏览器宽高等尺寸的方法)
js document.compatMode【详解】(含准确获取浏览器宽高等尺寸的方法)
8 0
|
2天前
|
前端开发 JavaScript C++
前端 JS 经典:判断数组的准确方法
前端 JS 经典:判断数组的准确方法
6 0
|
2天前
|
JavaScript 前端开发 索引
JavaScript编码之路 【JavaScript之操作数组、字符串方法汇总】(一)
JavaScript编码之路 【JavaScript之操作数组、字符串方法汇总】(一)
5 0