首先确实最基本元素,即蛇的每个身体单元 记为Class SnakeCell

为了标志每个单元的状态用一个in state 表示 

state=0  表示蛇头,  state=1表示蛇身, state=2 表示地图上零散的还没加入蛇身的单元

每个蛇身单元有一个前驱和后继单元 记为 SankeCell  frontCell,nextCell  如此即可完成基本元素的定义

下面写一下类的代码


        public SnakeCell frontCell;
        public SnakeCell nextCell;

        int state = 0;


        public SnakeCell(int _state)
        {

            SetStyle(Style_CanMove | Style_CanObserve, 1);

            state = _state;

            UnitID = GameEngine.GetUnitID("sankeCell");            

        }

 

 

 

此时再重载一下Behave函数 ,完成每个回合每个SnakeCell应做的事情  分为2种情况,对没加入蛇身的单元不做处理

 


        public override void Behave()
        {

            if (state == 0)  //蛇头
            {
               
                if (GameEngine.Keyboard.IsKeyDown(Keys.W))  direction = direction_up;  
                if (GameEngine.Keyboard.IsKeyDown(Keys.S))  direction = direction_down;
                if (GameEngine.Keyboard.IsKeyDown(Keys.A))  direction = direction_left;
                if (GameEngine.Keyboard.IsKeyDown(Keys.D))  direction = direction_right;
                              
                StepForward();

                return;
                
            }

            if (state == 1)  //蛇身
            {
                direction = frontCell.direction;

                StepForward();

                return;
            }

        }

 

 

最后再对蛇头重载一下其相撞事件的处理

 

        public override void RunInto(LifeObject p)
        {
            if (state == 0)   //只有蛇头处理相撞事件
            {
                SnakeCell pp = p as SnakeCell;

                 将pp加入蛇身,并赋值其坐标即可
            }

        }

 

如此 贪吃蛇的代码就完成了,然后生成一个虚拟世界,将SnakeCell加入进去

VirtualWorld world=new world(800,600,128,128);

world.AddElementObject(snakeCell);

 

 

再将world的显示和控件绑定

//将游戏画面绑定在控件上,每隔40ms刷新一次

 GameEngine.BindWorldShowControl(this,gameWorld,null,null, 40, null);

 

 如此 基本上大功告成,你也可以对蛇的不同单元使用不同的图片,将使游戏变的更漂亮

 

 游戏引擎(免费)请看前一篇的介绍

最后启动游戏
      
            while (true)
            {
                Thread.Sleep(30);
                
                gameWorld.TimeGo();
            }
      


  游戏引擎(免费)请看前一篇的介绍



 

 



 

posted on 2008-12-10 12:18  feathersky  阅读(1664)  评论(0编辑  收藏  举报