js贪吃蛇尝试(面向对象)

看了大佬的用js完成了贪吃蛇,就想自己尝试一下,灵感来自js实现贪吃蛇

html部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇</title>
    <link rel="stylesheet" href="./css/reset.css">
    <link rel="stylesheet" href="./css/index.css">
</head>
<body>
    <button id="playGame">开始游戏</button>
    <div id="app" class="snakeBox"></div>
    <script src="./js/snake.js"></script>
    <script>
        var snake = new Snake({
            el: '#app'
        })
        var play = document.querySelector('#playGame')
        play.onclick = function() {
            snake.run()
        }
    </script>
</body>
</html>

css

reset.css百度复制的

.snakeBox {
    width: 500px;
    height: 500px;
    background: black;
    border: 1px solid white;
    position: relative;
    top: 50%;
    left: 50%;
    margin-top: -270px;
    margin-left: -250px;
    z-index: 100;
}
.snakeItem {
    position: absolute;
    background: red;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
}
.snake {
    position: absolute;
    background: blue;
    width: 10px;
    height: 10px;
}
.dot {
    position: absolute;
    width: 10px;
    height: 10px;
    background: yellow;
    border-radius: 50%;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
}
#playGame {
    display: block;
    margin: 0 auto;
}
function Snake({el}) {
    this.el = document.querySelector(el)
    this.width = 10
    this.height = 10
    this.snakeBody = [
        {x: 2, y: 0}, // 蛇头
        {x: 1, y: 0}, // 身体
        {x: 0, y:0} // 蛇尾巴
    ]
    this.foodx = ''
    this.foody = ''
    this.deriction = 'right' // 前进方向
    this.timmer = null // 计时器
    this.food = null // 小球
    this.init()
}
Snake.prototype.init = function() {
    this.createSnake() // 创建蛇
    this.createFood() // 创建食物
    this.getDirection() // 监听键盘方向键
}
// 创建蛇身体
Snake.prototype.createSnake = function() {
    for (var i = 0; i < this.snakeBody.length; i++) {
        console.log(this.snakeBody[i])
        var div = document.createElement('div')
        div.style.left = this.snakeBody[i].x * this.width + 'px'
        div.style.top = this.snakeBody[i].y * this.height + 'px'
        div.classList.add('snakeItem')
        if (i === 0) {
            div.classList.add('snake')
        }
        this.el.appendChild(div)
    }
}
Snake.prototype.getDirection = function () {
    var that = this
    document.onkeydown = function (e) {
        var ev = e || window.event
        // 不允许往当前方向的相反方向走
        if (+ev.keyCode === 39) {
            // 向右走
            if (that.deriction !== 'left') {
                that.deriction = 'right'
            }
        } else if (+ev.keyCode === 37) {
            // 向左走
            if (that.deriction !== 'right') {
                that.deriction = 'left'
            }
        } else if (+ev.keyCode === 38) {
            // 向上走
            if (that.deriction !== 'down') {
                that.deriction = 'up'
            }
        } else if (+ev.keyCode === 40) {
            // 向下走
            if (that.deriction !== 'up') {
                that.deriction = 'down'
            }
        }
    }
}
// 跑起来
Snake.prototype.run = function() {
    var that = this
    this.timmer = setInterval(function() {
        // 后一个位置等于前一个位置
        for (var i = that.snakeBody.length - 1; i > 0; i--) {
            that.snakeBody[i].x = that.snakeBody[i-1].x
            that.snakeBody[i].y = that.snakeBody[i-1].y
        }
        switch(that.deriction) {
            case 'right':
                that.snakeBody[0].x += 1
                break
            case 'left':
                that.snakeBody[0].x -= 1
                break
            case 'up':
                that.snakeBody[0].y -= 1
                break
            case 'down':
                that.snakeBody[0].y += 1
                break
        }
        // 判断是否出界
        if (that.snakeBody[0].x > 49 || that.snakeBody[0].y > 49 || that.snakeBody[0].x < 0 || that.snakeBody[0].y < 0) {
            clearInterval(that.timmer)
            alert('当场去世')
            return false
        }
        that.isEat() // 是否吃到食物
        that.isEatSelf() // 是否吃到自己
        var snakeArr = document.querySelectorAll('.snakeItem')
        for (var j = 0; j < snakeArr.length; j ++) {
            snakeArr[j].style.left = that.snakeBody[j].x * that.width + 'px'
            snakeArr[j].style.top = that.snakeBody[j].y * that.height + 'px'
        }
    }, 500)
}
// 创建食物
Snake.prototype.createFood = function() {
    var food = document.createElement('div')
    food.classList.add('dot')
    var x = parseInt(Math.random()*49)
    var y = parseInt(Math.random()* 49)
    // 不能出生在蛇身上
    var isSnake = this.snakeBody.find(el => {
        return el.x == x && el.y == y
    })
    // 则重新生成
    if (isSnake !== undefined) {
        this.createFood()
    } else {
        this.foodx = x
        this.foody = y
        food.style.left = x * this.width + 'px'
        food.style.top = y * this.height + 'px'
        this.el.appendChild(food)
        this.food = food
    }
}
// 判断是否吃到食物
Snake.prototype.isEat = function() {
    if (this.foody === this.snakeBody[0].y && this.foodx === this.snakeBody[0].x) {
        // alert('奶奶的可算吃到了')
        // 吃到食物添加snakeBody
        var x = this.snakeBody[this.snakeBody.length - 1].x
        var y = this.snakeBody[this.snakeBody.length - 1].y
        this.snakeBody.push({x,y})
        var div = document.createElement('div')
        div.classList.add('snakeItem')
        div.style.left = x * this.width + 'px'
        div.style.top = y * this.height + 'px'
        this.el.appendChild(div)
        this.el.removeChild(this.food)
        // 重新生成食物
        this.createFood()
    }
}
// 判断是否吃到自己
Snake.prototype.isEatSelf = function () {
    // 从第四个个开始才能吃到自己
    var eatSelf = false
    for (var i = 4; i < this.snakeBody.length; i++) {
        eatSelf = false
        var headerX = this.snakeBody[0].x
        var headerY = this.snakeBody[0].y
        if (headerX == this.snakeBody[i].x && headerY == this.snakeBody[i].y) {
            alert('你是猪吗,能吃到自己')
            clearInterval(this.timmer)
            this.timmer = null
            eatSelf = true
            continue
        }
    }
    if (eatSelf) {
        var snakeArr = document.querySelectorAll('.snakeItem')
        snakeArr = [...snakeArr]
        for(var item in snakeArr) {
            this.el.removeChild(snakeArr[item])
        }
        this.el.removeChild(this.food)
        this.snakeBody = [
            {x: 2, y: 0}, // 蛇头
            {x: 1, y: 0}, // 身体
            {x: 0, y:0} // 蛇尾巴
        ]
        this.init()
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值