Exemple #1
0
        /// <summary>
        /// 移动蛇
        /// </summary>
        private void MoveSnake()
        {
            ControlHost host     = Native.Host;
            int         bodySize = m_bodys.Count;
            SnakeBody   lastBody = m_bodys[bodySize - 1];
            int         left     = lastBody.Left;
            int         top      = lastBody.Top;

            //改变蛇身每个关节的位置
            for (int i = 0; i < bodySize; i++)
            {
                SnakeBody body = m_bodys[i];
                switch (body.Direction)
                {
                //向下
                case SnakeDirection.Down:
                    body.Top += body.Height;
                    break;

                //向左
                case SnakeDirection.Left:
                    body.Left -= body.Width;
                    break;

                //向右
                case SnakeDirection.Right:
                    body.Left += body.Width;
                    break;

                //向上
                case SnakeDirection.Up:
                    body.Top -= body.Height;
                    break;
                }
            }
            //判断游戏失败
            if (IsLose())
            {
                m_play.GameState = GameState.Lose;
                m_play.BringToFront();
            }
            else
            {
                bool newFood = false;
                //判断吃食物
                int foodSize = m_foods.Count;
                for (int i = 0; i < foodSize; i++)
                {
                    Food food     = m_foods[i];
                    RECT tempRect = new RECT();
                    RECT bRect    = m_bodys[0].Bounds;
                    RECT fRect    = food.Bounds;
                    if (host.GetIntersectRect(ref tempRect, ref bRect, ref fRect) > 0)
                    {
                        m_eatCount++;
                        //添加关节
                        RECT      rc   = new RECT(left, top, left + SNAKE_SIZE, top + SNAKE_SIZE);
                        SnakeBody body = new SnakeBody(rc);
                        m_bodys.Add(body);
                        AddControl(body);
                        body.BringToFront();
                        //移除食物
                        RemoveControl(food);
                        m_foods.Remove(food);
                        newFood = true;
                        break;
                    }
                }
                //改变移动方向
                bodySize = m_bodys.Count;
                for (int i = bodySize - 1; i > 0; i--)
                {
                    m_bodys[i].Direction = m_bodys[i - 1].Direction;
                }
                //设置新的食物
                if (newFood)
                {
                    AddFood();
                }
            }
            Invalidate();
        }