zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    }
    

      

  • 相关阅读:
    Oracle数据库死锁和MySQL死锁构造和比较
    shell单引号中输出参数值
    视频流媒体服务器
    使用syncthing进行双机文件同步
    状态(State)模式--设计模式
    中介者(调停者)模式--设计模式
    链表的中间节点
    删除链表中的倒数第N个节点
    Logos讲解--逆向开发
    MonkeyDev安装--逆向开发
  • 原文地址:https://www.cnblogs.com/ruogu/p/10838005.html
Copyright © 2011-2022 走看看