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


键盘上下左右控制

Title

源码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .map {
            width: 800px;
            height: 800px;
            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>