• JavaScript—面向对象 贪吃蛇_3 蛇对象


    蛇对象

    function Snake(element) {
        this.width = 20
        this.height = 20
    
        //蛇身 位置 颜色
        this.body = [
            {x: 6, y: 4, bc: 'red'},
            {x: 5, y: 4, bc: 'blue'},
            {x: 4, y: 4, bc: 'blue'},
        ]
        this.direction = 'right'
        this.elemen = element
        //保存当前蛇
        this.arr = []
    }
    
    //吃食物
    Snake.prototype.feed = function (food) {
    
        // 遇到食物 复制最后一个蛇身
        if (this.body[0].x * this.width === food.x && this.body[0].y * this.height === food.y) {
            let o = this.body[this.body.length - 1]
            let pro = {x: o.x, y: o.y, bc: o.bc}
            this.body.push(pro)
        }
    }
    
    Snake.prototype.remove = function () {
        for (let i = 0; i < this.arr.length; i++) {
            this.arr[i].parentNode.removeChild(this.arr[i])
        }
        this.arr = []
    }
    //蛇出现
    Snake.prototype.show = function () {
        this.remove()
        //console.log(this.arr)
        for (let i = 0; i < this.body.length; i++) {
            let div = document.createElement('div')
            this.elemen.appendChild(div)
            div.style.width = this.width + 'px';
            div.style.height = this.height + 'px'
            div.style.position = 'absolute'
            div.style.backgroundColor = this.body[i].bc
            div.style.left = this.body[i].x * this.width + 'px'
            div.style.top = this.body[i].y * this.height + 'px'
            this.arr.push(div)
        }
    
    }
    //移动方法
    Snake.prototype.udlr = function () {
        //蛇身移动 根据最后一个的位置等于上一个的位置
        for (let 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
        }
        // 边界
        let herfX = this.body[0].x * this.width >= this.elemen.offsetWidth - this.width || this.body[0].x * this.width <= 0
        let herfY = this.body[0].y * this.height >= this.elemen.offsetHeight - this.height || this.body[0].y * this.height <= 0
        if (herfX || herfY) {
            alert('完蛋')
            return
        }
        switch (this.direction) {
            case "right": {
                this.body[0].x += 1
                break;
            }
            case "letf": {
                this.body[0].x -= 1
                break;
            }
            case "up": {
                this.body[0].y -= 1
                break;
            }
            case "down": {
                this.body[0].y += 1
                break;
            }
        }
    }
    

      

  • 相关阅读:
    [转]检查浏览器是否支持javascript和cookie
    Ruby语法学习
    [转]Office Word 2007鼠标操作无效
    JS选择图片,显示缩略图
    IE开发工具条IEDevToolBar下载
    [转]120个 Web 开发工具 (下)
    JQuery收藏
    [转]120个 Web 开发工具 (上)
    [转]GridView自动序号
    [转]GridView 常用事件删除,更新,删除,取消等
  • 原文地址:https://www.cnblogs.com/ruogu/p/10838005.html
Copyright © 2020-2023  润新知