[LxcJie原创]贪吃蛇游戏(Javascript)

来源:互联网 发布:捕鱼达人 知乎 编辑:程序博客网 时间:2024/05/18 06:13

一个简版的贪吃蛇游戏。

另外,没有环境,没有在其他的浏览器上测试,不知道能不能跨。

〉〉〉〉〉〉〉〉2007.07.12改版,支持IE,FF,NS

要运行,需要注意下面这一点:

因为是基于prototype.js的脚本,所以prototype.js是必须的,大家可以到下面的链接去下载

http://www.prototypejs.org/download

下载后与下面的代码放置到同一个目录下(注意),就可以玩了。

下面是贪吃蛇的具体代码,随便保存一个文件就可以了

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=gb2312">
    <script language="javascript" src="prototype.js"></script>
    <script language="javascript">
        //###################
        //Created by 刘肖冲[LxcJie] 2007.07.09
        //* 2007.07.12改版,支持IE,FF,NS **
        //***** 请保留出处,谢谢 *****
        //***[prototype.js] Is Required***
        //###################
        ///////////////////////////////////////////////////
        var GameConfig = Class.create();
        GameConfig.snakeSize = 10;
        GameConfig.backWidthUnits = 50;
        GameConfig.backHeightUnits = 50;
        GameConfig.backBorderWidth = 1;
        GameConfig.backgroundZIndex = 3;
        GameConfig.snakeBodyID = 0;
        GameConfig.foodID = 0;
        GameConfig.snakeColor = "Blue";
        GameConfig.foodColor = "Red";
        GameConfig.eatedFood = 0;
        ///////////////////////////////////////////////////
        var BackgroundCreator = Class.create();
        BackgroundCreator.prototype = {
            initialize : function(){
                this.dataArray = new Array(GameConfig.backHeightUnits);
                this.backDiv = null;
                this.backLeft = null;
                this.backTop = null;
                for(var i=0; i<GameConfig.backHeightUnits; i++){
                    var arr = new Array(GameConfig.backWidthUnits);
                    for(var j=0; j<GameConfig.backWidthUnits; j++){
                        arr[j] = 0;
                    }
                    this.dataArray[i] = arr;
                }
            },
            drawBackground : function(){
                var backDiv = document.createElement("div");
                var shadowDiv = document.createElement("div");
                var controlDiv = $("control");
                backDiv.id = "backDiv";
                this.backDiv = backDiv;

                var styleObj = new Object();
                styleObj.width = GameConfig.backWidthUnits * GameConfig.snakeSize + GameConfig.backBorderWidth * 2;
                styleObj.height = GameConfig.backHeightUnits * GameConfig.snakeSize + GameConfig.backBorderWidth * 2;
                styleObj.position = "absolute";
                styleObj.backgroundColor = "#FFFF99";
                styleObj.border = GameConfig.backBorderWidth + "px solid orange";
                styleObj.margin = 0;
                styleObj.padding = 0;
                styleObj.left = Math.floor(screen.availWidth/2 - styleObj.width/2);
                styleObj.top = 10;
                styleObj.zIndex = 2;
                this.backLeft = styleObj.left;
                this.backTop = styleObj.top;
                Element.setStyle(backDiv,styleObj);

                //Shadow
                styleObj.backgroundColor = "#BABABA";
                styleObj.left = styleObj.left + 6;
                styleObj.top = styleObj.top + 6;
                styleObj.border = "";
                styleObj.zIndex = 1;
                Element.setStyle(shadowDiv,styleObj);

                //Control Container
                styleObj.left = styleObj.left + styleObj.width + 20;
                styleObj.top = styleObj.top - 6;
                styleObj.backgroundColor = "";
                Element.setStyle(controlDiv,styleObj);

                document.body.insertBefore(backDiv, $('snakeBody'));
                document.body.insertBefore(shadowDiv, $('snakeBody'));
            }
        };
        ////////////////////////////////////////
        var SnakeBodyCell = Class.create();
        SnakeBodyCell.prototype = {
            initialize : function( backObj, x, y, pWidth, pColor ) {
                this._id = "__SNAKECELL__" + GameConfig.snakeBodyID++;
                this._backObj = backObj;
                this._x = x;
                this._y = y;
                this._posX = this._backObj.backLeft + 1 + (this._y-1) * GameConfig.snakeSize;
                this._posY = this._backObj.backTop + 1 + (this._x-1) * GameConfig.snakeSize;
                this._width = pWidth==null?GameConfig.snakeSize:pWidth;
                this._color = pColor==null?GameConfig.snakeColor:pColor;
                this._isDrawed = false;
            },
            setX : function( x ){
                this._x = x;
                this._posY = this._backObj.backTop + 1 + (this._x-1) * GameConfig.snakeSize;
            },
            setY : function( y ){
                this._y = y;
                this._posX = this._backObj.backLeft + 1 + (this._y-1) * GameConfig.snakeSize;
            },
            draw : function() {
                this._isDrawed = true;
                var cellString =  "<table id="
                     + this._id + " border=0 cellspacing=0 cellpadding=0 style='position:absolute;top:"
                     + this._posY +";left:"
                     + this._posX +";z-index:"
                     + GameConfig.backgroundZIndex++ + "'>"
                     + "<tr><td style='width:" + this._width + "px;height:"
                     + this._width + "px;background-color:"
                     + this._color + ";border:0px solid black;font-size:12px;'></td></tr></table>";
                new Insertion.Top('snakeBody', cellString);
            },
            move : function(){
                var oTable = $( this._id );
                var styleObj = new Object();
                styleObj.left = this._posX;
                styleObj.top = this._posY;
                Element.setStyle(oTable,styleObj);
            }
        }
        ////////////////////////////////////////
        var Snake = Class.create();
        Snake.PosLeft = "LEFT";
        Snake.PosRight = "Right";
        Snake.PosUp = "Up";
        Snake.PosDown = "Down";
        Snake.prototype = {
            initialize : function(back){
                this._snakeArray = new Array();
                this._size = 4;
                this._back = back;
                this._position = Snake.PosLeft;
                this._timer = null;

                for(var i=1; i<=this._size; i++){
                    var snakeCell = new SnakeBodyCell(this._back, 10,10+i);
                    this._snakeArray[i-1] = snakeCell;
                }
            },
            drawSnake : function(isStart){
                for(var i=0; i<this._snakeArray.length; i++){
                    if(this._snakeArray[i]._isDrawed){
                        this._snakeArray[i].move();
                    } else {
                        this._snakeArray[i].draw();
                    }
                }
                //If the first time, set timer
                if(isStart != null) {
                    this._timer = setInterval( 'snake.moveSnake()',200);
                }
            },
            moveUp : function(){
                if( this._position != Snake.PosDown )
                    this._position = Snake.PosUp;
            },
            moveDown : function(){
                if( this._position != Snake.PosUp )
                    this._position = Snake.PosDown;
            },
            moveLeft : function(){
                if( this._position != Snake.PosRight )
                    this._position = Snake.PosLeft;
            },
            moveRight : function(){
                if( this._position != Snake.PosLeft )
                    this._position = Snake.PosRight;
            },
            moveSnake : function(){
                for(var i=this._snakeArray.length-1; i>=0; i--){
                    if( i == 0 ) {
                        //Move Left
                        if(this._position == Snake.PosLeft) {
                            this._snakeArray[i].setY( this._snakeArray[i]._y - 1 );
                        }
                        //Move Right
                        if(this._position == Snake.PosRight) {
                            this._snakeArray[i].setY( this._snakeArray[i]._y + 1 );
                        }
                        //Move Up
                        if(this._position == Snake.PosUp) {
                            this._snakeArray[i].setX( this._snakeArray[i]._x - 1 );
                        }
                        //Move Down
                        if(this._position == Snake.PosDown) {
                            this._snakeArray[i].setX( this._snakeArray[i]._x + 1 );
                        }
                        //Check hitting wall
                        if( this._snakeArray[i]._y<=0 || this._snakeArray[i]._x<=0
                              || this._snakeArray[i]._y>GameConfig.backWidthUnits
                              || this._snakeArray[i]._x>GameConfig.backHeightUnits ){
                            alert("Dead");
                            clearInterval(this._timer);
                            return;
                        }
                    } else {
                        this._snakeArray[i].setX( this._snakeArray[i-1]._x );
                        this._snakeArray[i].setY( this._snakeArray[i-1]._y );
                    }
                }
                //Check hitting self
                for(var a=1; a<this._snakeArray.length; a++){
                    if(this._snakeArray[0]._y==this._snakeArray[a]._y
                        && this._snakeArray[0]._x==this._snakeArray[a]._x ) {
                        alert("Dead");
                        clearInterval(this._timer);
                        return;
                    }
                }
                this.eatFood();
                this.drawSnake();
            },
            eatFood : function(){
                var food = FoodProducer.Food;
                if(food._x==this._snakeArray[0]._x && food._y==this._snakeArray[0]._y){
                    food.removeFood();
                    $("eatFood").innerHTML = ++GameConfig.eatedFood;

                    //Add body to snake
                    var snakeLen = this._snakeArray.length;
                    this._snakeArray[snakeLen] = new SnakeBodyCell(this._back, this._snakeArray[snakeLen-1]._x,
                        this._snakeArray[snakeLen-1]._y);

                    var food = new FoodProducer(back);
                    FoodProducer.Food = food;
                    food.drawFood();
                }
            }
        }
        ////////////////////////////////////////
        var FoodProducer = Class.create();
        FoodProducer.prototype = {
            initialize : function(backObj)
            {
                this._id = "__FOODCELL__" + GameConfig.foodID++;
                this._width = GameConfig.snakeSize;
                this._backObj = backObj;
                this._x = 0;
                this._y = 0;
            },
            drawFood : function(){
                this._x = Math.ceil(Math.random() * GameConfig.backWidthUnits);
                this._y = Math.ceil(Math.random() * GameConfig.backWidthUnits);
                this._posX = this._backObj.backLeft + 1 + (this._y-1) * GameConfig.snakeSize;
                this._posY = this._backObj.backTop + 1 + (this._x-1) * GameConfig.snakeSize;
                var foodString =  "<table id="
                     + this._id + " border=0 cellspacing=0 cellpadding=0 style='position:absolute;top:"
                     + this._posY +";left:"
                     + this._posX +";z-index:"
                     + GameConfig.backgroundZIndex++ + "'>"
                     + "<tr><td style='background-color:"
                     + GameConfig.foodColor + ";width:"
                     + GameConfig.snakeSize + ";height:"
                     + GameConfig.snakeSize + "'></td></tr></table>";
                new Insertion.Top('snakeBody', foodString);
            },
            removeFood : function(){
                var oFood = $(this._id);
                Element.remove( oFood );
            }
        };
    </script>
</head>
<body>
<div id="snakeBody"></div>
<div id="control" style="font-size:12px">
<span>Eated food : </span><span style="color:red" id="eatFood">0</span>
<br><br>
<div style="border:1px solid orange;background-color:#FFFF99;width:70;padding:10px">W:UP<br> A:LEFT<br> D:RIGHT<br> S:DOWN</div>
</div>
</body>
<script language="javascript">
//Draw background
var back = new BackgroundCreator();
back.drawBackground();

//Draw food
var food = new FoodProducer(back);
FoodProducer.Food = food;
food.drawFood();
//Draw snake
var snake = new Snake(back);
snake.drawSnake('snake');

Event.observe(document, 'keypress', function(event) {
    var key = 0;
    //If browser is netscape(NS)
    if(event.which){
        key = event.which;
    } else {
        key = event.keyCode;
    }
    //W Move Up
    if(key == 87 || key == 119){
        snake.moveUp();
    }
    //S Move Down
    if(key == 83 || key == 115){
        snake.moveDown();
    }
    //A Move Left
    if(key == 65 || key == 97){
        snake.moveLeft();
    }
    //D Move Right
    if(key == 68 || key == 100){
        snake.moveRight();
    }
});

</script>
</html>

原创粉丝点击