JavaScript 贪吃蛇

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>GreedySnake</title>
    <script type="text/javascript">

        var bgLongth = 40;  //背景的宽度(格子数量)
        var bgHight = 20;  //背景的宽度(格子数量)
        var long = 20;  //每个小格子的边长
      
        var myTime = null;  //定时器全局变量
        //var speed = [500, 400, 300, 200, 100];  //小蛇的速度
        //var addScore = [5, 10, 15, 20, 25];   //每次吃到食物增加的分数
        //var scoreGrade = [50, 100, 500, 800, 100]; //得分的等级  用来决定小蛇的速度和加分的
        //小蛇的速度     每次吃到食物增加的分数  得分的等级  用来决定小蛇的速度和加分的
        var grade = [[250, 5, 30], [230, 10, 50], [200, 15, 500], [180, 20, 800], [150, 25, 100]];
        var player = new Array();  //玩家数组
        var heroList = new Array(); //英雄榜
        

        // 绘制背景的方法
        function createBackground() {

            // 创建背景节点
            var background = document.createElement('div');
            background.style.width = bgLongth*long+"px";
            background.style.height = bgHight*long+"px";
            background.style.background = "url(./background.jpg)";
            // 把节点绑定到div上
            document.getElementById("background").appendChild(background);
        }

        // 食物的构造方法
        function Food() {
            this.pice = null;
            this.x = 0;
            this.y = 0;
            this.createFood = function() {
                // 创建div
                if(this.pice==null) {
                    this.pice = document.createElement("div");
                    document.getElementById("background").appendChild(this.pice);
                    this.pice.style.width = long+"px";
                    this.pice.style.height = long+"px";
                    this.pice.style.backgroundColor = "green";
                    this.pice.style.position = "absolute";
                }

                // 食物的定位
                this.x = Math.floor(Math.random()*bgLongth);
                this.y = Math.floor(Math.random()*bgHight);
                this.pice.style.left = this.x*long+"px";
                this.pice.style.top = this.y*long+"px";
            }
        }

        //蛇的构造方法
        function Snake() {
            
            //蛇头的前进方向 开始默认向右
            this.redirect = "right";
            //每个蛇节的位置
            this.location = [[0, 1, 'green', null], [1, 1, 'green', null], [2, 1, 'green', null], [3,1,'red',null]];
            //创建蛇 如果蛇已经创建就刷新一下位置
            this.createSnake = function() {
                for(var i=0; i<this.location.length; i++) {
                    if(!this.location[i][3]) {
                        var snake = document.createElement("div");
                        document.getElementById("background").appendChild(snake);
                        snake.style.width = long+"px";
                        snake.style.height = long+"px";
                        snake.style.backgroundColor = this.location[i][2];
                        snake.style.position = "absolute";
                        this.location[i][3] = snake;
                    }
                    this.location[i][3].style.left = this.location[i][0]*long+"px";
                    this.location[i][3].style.top = this.location[i][1]*long+"px";
                }
            }
            // 蛇的移动
            this.move = function() {
                // 身体的移动后一个元素往前推一个后的位置
                for(var i=0; i<this.location.length-1; i++) {
                    this.location[i][0] = this.location[i+1][0];
                    this.location[i][1] = this.location[i+1][1];
                }
                //蛇头的移动
                if(this.redirect=="right") {
                    this.location[this.location.length-1][0]++;
                }else if(this.redirect=="left") {
                    this.location[this.location.length-1][0]--;
                }else if(this.redirect=="up") {
                    this.location[this.location.length-1][1]--;
                }else if(this.redirect=="down") {
                    this.location[this.location.length-1][1]++;
                }
                //判断蛇头是否碰到食物
                if(this.location[this.location.length-1][0]==food.x && this.location[this.location.length-1][1]==food.y) {
                    console.log("吃到食物拉");
                    //分数增加
                    player[0][1] += grade[player[0][2]][1];
                    document.getElementById("score").getElementsByTagName("span")[0].innerHTML = player[0][1];  //刷新分数
                    //根据分数判断等级是否要增加
                    if(player[0][1] >= grade[player[0][2]][2]) {
                        //等级增加
                        player[0][2]++;
                        //刷新蛇的速度  即重新开启定时器
                        clearInterval(myTime);
                        myTime = null;
                        myTime = setInterval("snake.move()", grade[player[0][2]][0]);
                    }
                    //从新产生食物
                       food.createFood();
                    
                    //增加蛇节
                    snake.location.unshift([snake.location[0][0], snake.location[0][1], 'green', null]);
                    //更新排行榜
                    
                }
                
                //刷新蛇的位置
                this.createSnake();
            }

        }

        //监听键盘方向键的方法
        function listenRedirect() {
            console.log("开始监听方向键");
            document.onkeydown = function(evt) {
                var num = evt.keyCode;
                switch (num) {
                   case 37:
                       if(snake.redirect != "right") {  //控制蛇不能180°掉头  下同
                           snake.redirect = "left";
                       }  
                       break;
                   case 38:
                       if(snake.redirect != "down") {
                           snake.redirect = "up";
                       }
                       break;
                   case 39:
                       if(snake.redirect != "left") {
                           snake.redirect = "right";
                       }
                       break;
                   case 40:
                       if(snake.redirect != "up") {
                           snake.redirect = "down";
                       }
                       break;
                }
            }
           
        }
        window.onload = function() {
            
            

             //绘制背景
            createBackground();
             
            // 创建食物对象
            food = new Food();
            
               

            //给开始/暂停键绑定事件
            document.getElementById("start").onclick = function() {
                
                //开始
                if(this.getAttribute("flag")=="0") {
                    
                    console.log("开始");
                    //开始监听键盘方向键
                    listenRedirect();
                    //显示分数
                    document.getElementById("score").style.display = "inline-block";
                    //添加一个玩家信息到玩家数组
                    player.unshift(['libin', 0, 0]);  //姓名,初始化分数,等级
                    //显示分数
                    document.getElementById("score").style.display = "inline-block";
                    document.getElementById("score").getElementsByTagName("span")[0].innerHTML = player[0][1];
                    
                    food.createFood();
                    // 給开始按钮设置一个属性  开始标志
                    this.setAttribute("flag", "1");
                    this.innerHTML = "暂停";
                    
                    if(!myTime) {
                        //创建蛇
                        snake = new Snake();
                        snake.createSnake();
                    }
                    myTime = setInterval("snake.move()", grade[player[0][2]][0]);
                    console.log(myTime);
                    
                    

                }else if(this.getAttribute("flag")=="1"){
                    console.log("暂停");
                    
                    //給开始按钮设置一个属性  开始标志
                    this.setAttribute("flag", "2");
                    this.innerHTML = "继续";
                    
                    //暂停
                    clearInterval(myTime);
                }else if(this.getAttribute("flag")=="2") {
                    console.log("继续");
                    myTime = setInterval("snake.move()", grade[player[0][2]][0]);
                    this.innerHTML = "暂停";
                    // 給开始按钮设置一个属性  开始标志
                    this.setAttribute("flag", "1");
                    //开始监听键盘方向键
                    listenRedirect();
                }




            }
            
            //给“停止”键绑定单击停止时间
            document.getElementById("stop").onclick = function() {
                console.log("停止");
                //停止定时器
                clearInterval(myTime);
                myTime = null;
                
                try {
                    if(snake) {
                        //清除蛇
                        for(var i=0; i<snake.location.length; i++) {
                            console.log(i);
                            document.getElementById("background").removeChild(snake.location[i][3]);
                        }
                        
                        
                        //开始键不管是暂停状态还是开始状态恢复初始状态
                        document.getElementById("start").setAttribute("flag", "0");
                        document.getElementById("start").innerHTML = "开始";
                        
                        
                    }
                }catch(e) {
                    console.log("snake未定义");
                }
                try {
                    if(food.pice) {
                        //清除食物
                        document.getElementById("background").removeChild(food.pice);
                        food.pice = null;
                    }
                }catch(e) {
                    
                }
                
                
            }






        }
    </script>
    <style type="text/css">
        body {
            margin:0;
        }
        .background {
        }
    </style>
</head>
<body>
    <div id="background" class="background"></div>
    <p>
        <button id="start" flag="0">开始</button><button id="stop" >停止</button><span id="score" style="display: none;">SCORE:<span>0</span>分</span>
    </p>
</body>

</html>

<!-- 游戏失败的逻辑还没有写  我还打算写个排行榜的 -->

有以上代码我加个背景图片小蛇就能跑起来


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值