js实现贪吃蛇

来源:互联网 发布:金太阳炒股软件官网 编辑:程序博客网 时间:2024/04/27 01:03

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh" lang="zh" dir="ltr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="generator" content="Editplus4PHP" />
    <meta name="keywords" content="Leo, HentStudio, Editplus4PHP, LeoPHP" />
    <meta name="description" content="LeoPHP - Powered by HentStduio" />
    <meta name="author" content="Leo" />
    <link rel="shortcut icon" href="images/favicon.ico" />

<style type="text/css">
#container {
  width: 800px;
  margin:auto;
  margin-top: 60px;

}
#map {
    position: absolute;
    width: 800px;
    height: 400px;
    background-color: #ccc;
    overflow: hidden;
    }
</style>


<script type="text/javascript">

function Food() {
 //var w = 20;
    this.w = 20;//宽
    this.h = 20;//高
    this.color = 'red';
   

    //显示食物
 //var display = function(){}
    this.display = function() {
        //位置 我们用 0,1,2
        //位置 宽 应该在0-39随机产
        //位置 高 应该在0-19随机
        //我们利用随机数和取整的方式获得
        this.x = Math.round(Math.random()*39);
        this.y = Math.round(Math.random()*19);
        //生成一个div
        //控制div的大小 位置 颜色
        //让这个div 出现在 id为map的div中
        var new_div = document.createElement('div');
        new_div.style.width = this.w + 'px';
        new_div.style.height = this.h + 'px';
        //位置
        //控制定位
        //我们的绝对定位是相对于那个元素来说的?
        //相对于 包含它的 第一个 非相对定位的元素。
        new_div.style.position = 'absolute';
        new_div.style.left = (this.x * this.w) + 'px';
        new_div.style.top = (this.y * this.h) + 'px';
        //颜色
        new_div.style.backgroundColor = this.color;

        //让这个食物 在 map中显示
        document.getElementById('map').appendChild(new_div);

        //记住这个旧的食物
        this.div = new_div;


    }
    this.reDisplay = function() {
       //删除旧的
        document.getElementById('map').removeChild(this.div);
        this.display();
    }


}

//设计蛇类
function Snake() {
    //蛇的方向
    this.direct = 'right';
    //蛇的大小
    this.w = 20;
    this.h = 20;
    //默认蛇身的属性
    //蛇身是3个div的组合,我定义一个数组,数组的每一个元素就是一个蛇节
    //默认有3个元素,下标为0的代表蛇头
    //每个蛇身元素应该包含哪些属性,最起码 应该表示出来位置 颜色
    this.body = [
    {x:5,
    y:3,
    color:'blue'},
    {x:4,
    y:3,
    color:'red'
    },
    {x:3,
    y:3,
    color:'red'}
    ];


    this.display = function() {
        //遍历蛇身,根据每节 产生一个div
        for(var i=0; i<this.body.length; i++) {
        //得到当前的蛇节,显示
            //创建一个div
           var snake_div = document.createElement('div');
           snake_div.style.position = 'absolute';
           snake_div.style.left = (this.w * this.body[i].x) + 'px';
           snake_div.style.top = (this.h * this.body[i].y) + 'px';

           snake_div.style.width = this.w + 'px';
           snake_div.style.height = this.h + 'px';

           snake_div.style.backgroundColor = this.body[i].color;

           document.getElementById('map').appendChild(snake_div);
           //将显示的div记录下来
           this.body[i].div = snake_div;
       }
      
           
    }

    //用于移动蛇身
    this.move = function() {
        //控制蛇身
        for (var 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;
        }

        //控制蛇头
        //up down left right
        switch(this.direct) {
            case 'up':
                this.body[0].y -= 1;
                break;
            case 'down':
                this.body[0].y += 1;
                break;
            case 'left':
                this.body[0].x -= 1;
                break;
            case 'right':
                this.body[0].x += 1;
        }

        //消灭旧蛇:
        this.removeSnake();

        //显示蛇
        this.display();

        //判断是否撞墙
        if(this.body[0].x < 0 || this.body[0].x > 39 || this.body[0].y < 0 || this.body[0].y >19) {
            //撞了
            alert('GAME OVER!');
            //清空定时器
            clearInterval(snake_id);
        }

        //判断是否撞到自己
        for(var i = this.body.length-1; i >= 4; i--){
            if(this.body[0].x == this.body[i].x && this.body[0].y == this.body[i].y) {
            //
                alert('GAME OVER!');
                //清空定时器
                clearInterval(snake_id);
                break;
            }
        }

        //判断是否吃上
        if(this.body[0].x == food.x && this.body[0].y == food.y) {
        //  头和食物撞上了
            //蛇要增加一个,需要在body中增加一个元素即可
            this.body[this.body.length] = {
            x:0,
            y:0,
            color:'red',
            div:null
            };

            //重新分配食物的地址,重新显示:
            food.reDisplay();

         }
        
    }

    this.removeSnake = function() {
        //遍历所有的蛇身,删除页面元素div
        var map = document.getElementById('map');
        for(var i=0; i<this.body.length; i++) {
            if(this.body[i].div != null) {
                map.removeChild(this.body[i].div);
            }
        }
       
    }

    this.setDirect = function(keyCode) {
        //判断4个可能
        switch(keyCode) {
            case 37:
                if(this.direct != 'right') {
                    this.direct = 'left';
                }
            break;
            case 38:
                if(this.direct != 'down') {
                    this.direct = 'up';
                }
            break;
            case 39:
                if(this.direct != 'left') {
                    this.direct = 'right';
                }
            break;
            case 40:
                if(this.direct != 'up') {
                    this.direct = 'down';
                }
            break;
        }
    }
   
}

//初始化操作
function init() {
    //得到食物对象
    food = new Food();
    //显示食物
    food.display();

    //得到蛇对象
    //显示蛇
    snake = new Snake();
    snake.display();
   
}

//点击开始的方法
function startGame() {
    snake_id = setInterval("snake.move();", 300);

}

//转弯的方法
function changeDirect(evt) {
    //调用蛇的设置方向方法
    snake.setDirect(evt.keyCode);
}
</script>
    <title>贪吃蛇</title>
</head>
<body onload="init();" onkeydown="changeDirect(event);">

<div id="container">
<button onclick="startGame();">开始</button>
<div id="map"></div>
</div>
   
</body>
</html>

原创粉丝点击