admin管理员组

文章数量:1130349

用lua写popStar

考虑问题( 会有三种情况出现): 先想有几种情况,每种情况有份几种   --- 见折半查找 于豆豆。 如果遇到问题没有现成解决方案时, 就有用了(参考  消除 搜素算法) ---------------------------------------------------------------------------------------------------- owner()huidioao
1:   MatrixStars = {{},{},{},{},{},{},{},{}}   -- 星星矩阵 .  直接  ={}不对 
for i=1, 8, 1 do MatrixStars[i] = {} for j=1,  8,  1 do -- 随机数      local _temp =  math.random(1,5); -- 创建星星矩阵 local star = StarSprite.new(_temp); star:setPosition(cc.p(display.width/2, display.height/2)) self:addChild(star);
MatrixStars[i][j] = "star”;    — (a nil value) 此时键不存在,就无法引用 2:  A  当调用local star = StarSprite.new(_temp); 时,参数会自动传给ctor(var)/function(var)中, B     local imagePath = StarSprite.getImageFile(var), 用冒号为啥不对, 因为此时 无self,  (源码) StarSprite = class("StarSprite", function (var) local imagePath = StarSprite.getImageFile(var) return cc.Sprite:create(imagePath); end);
3:星星类也可以继承Node类。做法(Node是一个小方块, 在小方块上创建一个星星,即内部创建星星) local StarSprite = class("StarSprite", function () return cc.Node:create(); end);
4: coocsbuilder 中的变量不会自动对应, 要binding起来 ---------------------------------------------------------------------------------------------------
#ifndef __popStar__starSprite__

#define __popStar__starSprite__


#include <stdio.h>

#include "cocos2d.h"


USING_NS_CC;


class  Star : public Sprite

{

public:

    static Star*  createStar(int color);

    void init(int color);

    

  

    // 获得星星颜色  死局

    int  getColor() { return  m_color; }

    

    bool isSelect() { return m_select; }

    // 把星星设为已选

    void setSelect(bool select) {   m_select = select ; }

     // 获取坐标索引

    int getIndexX() { return m_indexX; }  // 隐式定义内联函数

    inline int getIndexY() { return m_indexY; }

    

    void setIndexXY(int x, int y) {   m_indexX = x; m_indexY = y; }

    

public:

    static const int STAR_WIDTH  = 80;   //单个 星星宽度

    static const int STAR_HEIGHT = 80;   //单个 星星高度

    

private:

      std::string setColor(int color);

    

private:

    bool m_select;

    int m_color;   //m_colore

    int m_indexX;

    int m_indexY;

    int m_moveDelay;

    

};



#endif /* defined(__popStar__starSprite__) */

//

//  starSprite.cpp

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#include "data.h"

#include "starSprite.h"


Star* Star::createStar(int color)

{

    Star *star = new Star();

    

    if(star && star->initWithFile(star->setColor(color)))

    {

        star->init(color);

        star->autorelease();

        return  star;

    }

    else

    {

        CC_SAFE_DELETE(star);

        star = nullptr;        //

        return  nullptr;

    }

}


void Star::init(int color)

{

    m_select = false;

    m_color = color;


}


std::string Star::setColor(int color)

{

    switch (color)

    {

        case  GREEN:  return "green.png";

        case  BLUE:   return "blue.png";

        case  YELLOW: return "orange.png";

        case  RED:    return "red.png";

        case  PURPLE: return "purple.png";

            

        default:

            CC_ASSERT(0);  // false

    }

}    

—————————————————————————————————————————————

//

//  starArry.h

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#ifndef __popStar__starArry__

#define __popStar__starArry__


#include <stdio.h>

#include <string.h>

#include <deque>

#include <vector>

#include <algorithm>


#include "starSprite.h"

#include "Publics.h"



using namespace std;


// 商店的高度

#define   STOREFEIHT  100

#define   DROPTIME     0.3   // 调整时单个星星下落时间


class StarArry  : public Sprite   // ?? scene()

{

public:

    static StarArry* createMatrix();

    bool init();

    void onTouch(Point& _pos);


    void empty(Ref* obj, Control::EventType);

    void produceBack(Star *);

public:

   

    void initMatrix();

    

    static const int ROW_NUM = 8;

    static const int COL_NUM = 8;

//private:

//public的全局可见,private类内可见  private函数一般是用来给public函数调中A.f1();

    

    void getSelectedList(Star *s) ;  // 获取相同颜色的星星

    void deleteSelectedList();      // 删除数组中同颜色的星星

    void adjustMatrix();           // 消除后,调整二维数组中的内容 即: 调整位置

    void produceStars();           // 消除后产生新的星星

    bool isEnd();                  //判断是否死局

    void clearStarOneByOne();      // 一个接一个的删除星星

    void removeStar(int i,int j);

    int  getLeftStar();

    

    //响应商店函数

    void cleanSameRowAndCol(int _row, int _col);  // 消除同行同列的星星

    void cleanSameColor(int _color);              //  消除相同颜色的星星

    void cleanEightStar(int _i, int _j);                        //  消除八字形

    

    // 通过坐标获取 星星

    Star *getStarByTouchPoint(Point &pos);

    // 通过index获取坐标

    Point getPositionByIndex(int i, int j);

    

private:

    Size  m_size;

    bool  m_overTimer;  // 标志超时

   

    Star* stars[ROW_NUM][COL_NUM];  // 二维数组 来存放星星

    std::vector<Star *> selectedList;   // 用于记录相同颜色的星星

};




#endif /* defined(__popStar__starArry__) */



//

//  starArry.cpp

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#include <time.h>

#include "data.h"

#include "starSprite.h"

#include "starArry.h"

#include "levelShared.h"

#include "jsonRead.h"

#include "starParticle.h"



 StarArry* StarArry::createMatrix()

{

    StarArry *starArry = new StarArry();

  

    if( starArry )

    {

       starArry->autorelease();

       starArry->init();

       return starArry;

    }

    else

    {

        CC_SAFE_DELETE(starArry);

        starArry = nullptr;

        return nullptr;

    }

}


static int oneScore = 0;  // 消除星星得分数

bool StarArry::init()

{

    if( !Sprite::init())

    {

        return false;

    }

    

    m_size = Director::getInstance()->getWinSize();

 

    initMatrix();   //创建星星矩阵

    


    LevelFeature::getInstance()->setScore(0);

    return true;

}

 

void StarArry::initMatrix()

{

    srand(unsigned(time(0)));

    

    int i, j;

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            int _color = rand()%5; // 0~4  随机生成几种颜色

            CCLOG("----: %d", _color);

            Star *s = Star::createStar(_color);

            stars[i][j] = s;

            s->setIndexXY(i, j);   // 为后面 删除 查找用

            s->setPosition(getPositionByIndex(i, j) + Point(0, 100));

           

            // 开始的 运动

            MoveBy *by = MoveBy::create(0.40f,  Point(0, -100));

            s->runAction(by);

            

            addChild(stars[i][j]);

        } // for

    }// for

    

}


// 通过坐标获取 星星

Star * StarArry::getStarByTouchPoint(Point &pos)  // 没问题这个

{   static int a=0;

     CCLOG(" - - --  - touch times: %d ", a++);

    int j = pos.x/Star::STAR_WIDTH; // 列索引

    

    int t = (pos.y - STOREFEIHT)/Star::STAR_HEIGHT;

    int i = ROW_NUM - 1 - t;

    

    // 如果 不存在 或 未点击到星星 返回空

    if(i >=0 && i< ROW_NUM && j>=0 && j< COL_NUM && stars[i][j] != nullptr)

    {

        return stars[i][j];

    }

    else

    {

        return  nullptr;

    }

}


// 通过index获取坐标

Point StarArry::getPositionByIndex(int i, int j)

{

    float _x = j*Star::STAR_WIDTH + Star::STAR_WIDTH/2;

    float _y = (COL_NUM - i)*Star::STAR_HEIGHT - Star::STAR_HEIGHT/2 + STOREFEIHT;

    

    return  Point(_x, _y);

}


void StarArry::onTouch(Point &_pos)

{

    

    Star*_s = getStarByTouchPoint(_pos);

 

    if(_s)

    {

        getSelectedList(_s);

        

        deleteSelectedList();

    }

}


// 搜索相同颜色的 星星

void StarArry::getSelectedList(Star *s)

{

    selectedList.clear();

    

    std::deque<Star *>  _travelList;

    _travelList.push_back(s);

    deque<Star*>::iterator it;

    

    for(  it= _travelList.begin();    it != _travelList.end(); ++it)

   // for(auto &t : _travelList)    //  通过下标来 搜索 上下左右

    {

        Star *_star = *it;   //返回引用值

        Star *_linkStar = nullptr;

        

        int _indexX = _star->getIndexX();

        int _indexY = _star->getIndexY();

      

        //  上

        if(_indexX-1 >=0 && (_linkStar = stars[_indexX-1][_indexY])!= NULL )

        {

            if(_linkStar->isSelect()== false && _linkStar->getColor() == _star->getColor() )

            {

                _travelList.push_back(stars[_indexX-1][_indexY]);

            }

        }

        // 下

        if(_indexX+1 <= ROW_NUM-1 && (_linkStar = stars[_indexX+1][_indexY])!= NULL)

        {

            if(_linkStar->isSelect() == false && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX+1][_indexY]);

            }

        }

        

        //  左   判断是存在

        if(_indexY-1 >=0 && (_linkStar=stars[_indexX][_indexY-1]))

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY-1]);

            }

        }

        // 右

        if(_indexY+1 <= COL_NUM-1 && (_linkStar=stars[_indexX][_indexY+1])!= nullptr )

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY+1]);

              //  _linkStar->setSelect(true); //不用标记;目前只是发现同色 但自身为搜索

            }

        }

        

        if( !_star->isSelect())

        {

            _star->setSelect(true);  // 标记已搜索过

            selectedList.push_back(_star);

        }

        

//        _travelList.pop_front();

//        it =  _travelList.begin(); // 取出第一个

    } // for

    

//    selectedList.clear();

     CCLOG(" -- - getSelectedList  - -- ");

}


// 消除矩阵中 同颜色的星星

void StarArry::deleteSelectedList()

{

//    oneScore = 0;  // 每次清空

    int _score = 0;

    

    if(selectedList.size() <= 2)       // 如果没有搜到

    {

        selectedList.at(0)->setSelect(false);

        if(selectedList.size() == 2)    // 如果2个颜色相同

        {

            selectedList.at(1)->setSelect(false);

        }

        return ;

    }

    

    // 若果存在同颜色的   就消除 同色的星星

    for(auto it = selectedList.begin(); it != selectedList.end(); it++)

    {

        Star* _star = *it;        // 下标删除

        removeStar(_star->getIndexX(),_star->getIndexY());

        

        _score = _score + 20;  //每消除一个的20分

    }

    

    // 放在for外面 优化效率 减少对文件操作    判断:应为存储分的模式不同

    if(UserDefault::getInstance()->getBoolForKey("IsForeverModel", false) == true)

    {

        // 无限模式

        int _scoreForever = UserDefault::getInstance()->getIntegerForKey("foreverScore");

        // 之前消除的得分 + 本次消除得分

        UserDefault::getInstance()->setIntegerForKey("foreverScore", _score+_scoreForever);

    }

    else

    {   // 关卡模式

        LevelFeature::getInstance()->setScore(LevelFeature::getInstance()->getScore() + _score);

    }

    

    selectedList.clear();

    CCLOG(" -- - getSelectedList  - - @ - ");

    

    adjustMatrix();  //如果执行了 删除操作;就调整

    

    produceStars();   // 产生星星

}


 static int  s_count[StarArry::ROW_NUM];

// 调整主要改变 索引

void StarArry::adjustMatrix()

{

    memset(s_count, 0, sizeof(s_count));

    

  

    //*************************************************************

    for(int i = ROW_NUM-1;i>=0;i--)

    {

         for(int j = 0;j <= COL_NUM-1; j++){

            if(stars[i][j] == nullptr)

            {

                int up = i;

                int dis = 0;

                while(stars[up][j] == nullptr)

                {

                    dis++;    // 空的个数

                    up--;

                    if(up<0)

                       {   break;   }

                }

                

                if(s_count[j] == 0 )     // 记录 "该列" 要移动星星个数

                {

                    int pp = s_count[j] = i-dis+1;

                }

          //   int pp = s_count[j] = i-dis+1;    //记录 "该列" 要移动星星个数

                int k=0;

                for(int begin_i = i - dis;  begin_i >= 0;  begin_i--) //循环次数为要移动星星个数

                {

                    if(stars[begin_i][j] == nullptr)  // 为空 不用移动

                        continue;

                

                    //              目标位置                     原始位置

                    Star* s = stars[begin_i + dis][j] = stars[begin_i][j];

                    s->setIndexXY(begin_i + dis,j);   // 不能少  删除查找iyong

//                    s->setIndexXY(<#int x#>, <#int y#>)

               //     s->setDesPosition(getPositionByIndex(begin_i + dis,j));

                    Point _pos = getPositionByIndex(begin_i+dis, j);

                    

                    DelayTime* _time = DelayTime::create(0.05*k); // 延迟时间

                    k++;

                    MoveTo *to = MoveTo::create(DROPTIME, _pos);

                    stars[begin_i][j]->stopAllActions();

                    stars[begin_i][j]->runAction(Sequence::create(_time, to, NULL));

                    

                    stars[begin_i][j]->setOpacity(255);

                    stars[begin_i][j] = nullptr;

                }

            }

            else{

                continue;

            }

        } // for

    }  // for

    

   //    produceStars();

}


// 产生新的星星

void StarArry::produceStars()

{

    srand((unsigned)time(0));

    int i, j;

    

    for(j=0; j<COL_NUM; j++)

    {

        for(i=ROW_NUM-1; i>=0; i--)

        {

            if(stars[i][j] )

            {

                continue;

            }

            

            if(stars[i][j] == nullptr )

            {

                //  首先找出    空的星星个数

                int up = i;

                int dis = 0;

                while(stars[up][j] == nullptr)

                {

                    dis++;    // 空的个数

                    up--;

                    if(up<0)

                    {   break;   }

                }


                //***************

                int k =  s_count[j];  //读取 "该列" 移动星星个数

                while( i>=0 ) // =0  -1

                {

                 int _color = rand()%5;

                    Star *_s = Star::createStar(_color);

           

                    stars[i][j] = _s;

                    _s->setIndexXY(i, j);

                    _s->setPosition(getPositionByIndex(i, j)+Point(0, Star::STAR_HEIGHT*dis));//100

                    

                    DelayTime *_time = DelayTime::create(0.05*k);

                    k++;

                    _s->setOpacity(0);

                    FadeTo *_fadeTo =  FadeTo::create(DROPTIME, 255); //bug

                    MoveTo *_to = MoveTo::create( DROPTIME, getPositionByIndex(i, j));

                    Spawn *_spawn = Spawn::create(_fadeTo, _to, NULL);

           

                    CallFunc *_fun = CallFunc::create([this]()

                    {

                        if(this->isEnd() == true)

                        {

                            UserDefault::getInstance()->setBoolForKey("IsEnd", true);

                            UserDefault::getInstance()->setBoolForKey("DeadLayer", true);

                        }

//                        _s->setOpacity(255);     // 解决bug 出现半透明现象

                     });

                    

                    _s->runAction(Sequence::create( _time, _spawn, _fun, NULL));

                    i--;

                    addChild(_s);  //添加到矩阵中

        

                }

            }  //if

         

        }  // for

    } //for

    

    

}


void StarArry::produceBack(Star *)

{

    

}


void StarArry::empty(cocos2d::Ref *obj, Control::EventType)

{

    

}



void StarArry::cleanSameRowAndCol(int _row, int _col)

{

    int i, j;

    

    // 消除同一行的星星

    for(j=0; j<COL_NUM; j++)

    {

        removeStar(_row,j);

    }

    //adjustMatrix();

    for(i=0; i<ROW_NUM; i++)

    {

        removeStar(i,_col);

    }

    

     adjustMatrix();

     produceStars();

}


// 消除同颜色的星星

void StarArry::cleanSameColor(int _color)

{

    int i, j;

    

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            if(stars[i][j] && stars[i][j]->getColor() == _color)

            {

                removeStar(i,j);

            } // if

            else

                continue;

        }

    }

    

     adjustMatrix();

  //   this->scheduleOnce(schedule_selector(StarArry::intervalProduce), 0.50f);

     produceStars();

}


void StarArry::cleanEightStar(const int i, const int j)

{

    removeStar(i, j);//本身

    removeStar(i-1, j-1);//左上

    removeStar(i, j-1);//左

    removeStar(i, j-2);//左2

    removeStar(i+1, j-1);//左下

    removeStar(i+1, j);//下

    removeStar(i+2, j);//下2

    removeStar(i+1, j+1);//右下

    removeStar(i, j+1);//右

    removeStar(i, j+2);//右2

    removeStar(i-1, j+1);//右上

    removeStar(i-1, j);//上

    removeStar(i-2, j);//上2

    int _i = i, _j = j;

 

//    while(_i>=0 && _j>=0)    // 左上

//    {

//        _i--;

//        _j--;

      removeStar(_i,_j);

//        if(stars[_i][_j])

//                    {

//                        stars[_i][_j]->removeFromParentAndCleanup(true);

//                        stars[_i][_j] = nullptr;

//                    }

//    }

//

//    _i = i, _j = j;

//        CCLOG("touch  index :  i=%d,j=%d", _i, _j);

//    while (_i <ROW_NUM && _j<COL_NUM)   // 右下

//    {

//        

//        _i++;

//        _j++;

//        if(stars[_i][_j])

//                                {

//                                    stars[_i][_j]->removeFromParentAndCleanup(true);

//                                    stars[_i][_j] = nullptr;

//                                }

//    }

//

//    _i = i, _j = j;

//    while ( _i>=0 && _j<COL_NUM)   // 右上

//    {

//        _i--;

//        _j++;

//        if(stars[_i][_j])

//        {

//            stars[_i][_j]->removeFromParentAndCleanup(true);

//            stars[_i][_j] = nullptr;

//        }

//    }

//    

//    _i = i, _j = j;

//    while (_i < ROW_NUM && _j>=0)   // 左下

//    {

//        _i++;

//        _j--;

//        if(stars[_i][_j])

//        {

//            stars[_i][_j]->removeFromParentAndCleanup(true);

//            stars[_i][_j] = nullptr;

//        }

//    }

//    

    

    adjustMatrix();

    produceStars();

}

 


void StarArry::clearStarOneByOne()  // 为啥出来红线

{

    int i,j;

 

    for(i=0; i<ROW_NUM; i++)   //安列来消除 死局星星

    {

        for(j=0; j<COL_NUM; j++)

        {

            removeStar(i,j);

        }

    } // for

    

 

}


// 单独写个函数

void StarArry::removeStar(int i,int j)

{

    if (i >=0 && i < ROW_NUM && j >= 0 && j < COL_NUM && stars[i][j])

    {

        showStarParticleEffect(stars[i][j]->getColor(), stars[i][j]->getPosition(), this);

        

        stars[i][j]->removeFromParentAndCleanup(true);

        stars[i][j] = nullptr;

    }

}


// 判断是否死局

bool StarArry::isEnd()

{

    std::vector<Star *> deadEnd;

    

    int i,j, k;

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

          

            for(k=0; k< deadEnd.size(); k++)

            {

                if(deadEnd.at(k)->isSelect() == true)

                deadEnd.at(k)->setSelect(false);   // 回复标记 false

            }

            

            deadEnd.clear();

    std::deque<Star *>  _travelList;

    _travelList.push_back(stars[i][j]);

    deque<Star*>::iterator it;

    

    for(  it= _travelList.begin();    it != _travelList.end(); ++it)

    {

        Star *_star = *it;   //返回引用值

        Star *_linkStar = nullptr;

        

        int _indexX = _star->getIndexX();

        int _indexY = _star->getIndexY();

        

        //  上

        if(_indexX-1 >=0 && (_linkStar = stars[_indexX-1][_indexY])!= NULL )

        {

            if(_linkStar->isSelect()== false && _linkStar->getColor() == _star->getColor() )

            {

                _travelList.push_back(stars[_indexX-1][_indexY]);

            }

        }

        // 下

        if(_indexX+1 <= ROW_NUM-1 && (_linkStar = stars[_indexX+1][_indexY])!= NULL)

        {

            if(_linkStar->isSelect() == false && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX+1][_indexY]);

            }

        }

        

        //  左   判断是存在

        if(_indexY-1 >=0 && (_linkStar=stars[_indexX][_indexY-1]))

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY-1]);

            }

        }

        // 右

        if(_indexY+1 <= COL_NUM-1 && (_linkStar=stars[_indexX][_indexY+1])!= nullptr )

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY+1]);

            }

        }

        

        if( !_star->isSelect())

        {

            _star->setSelect(true);  // 标记已搜索过

            deadEnd.push_back(_star);

        }

        

        if(deadEnd.size()>=3)

        {

            for(k=0; k< deadEnd.size(); k++)

            {

                if(deadEnd.at(k)->isSelect() == true)

                deadEnd.at(k)->setSelect(false);   // 回复标记 false

            }

            

            return  false;

        }

    } // 最里层 for

            

        }

    }


    // 如果小于3个

    for(k=0; k< deadEnd.size(); k++)

    {

        if(deadEnd.at(k)->isSelect() == true)

        deadEnd.at(k)->setSelect(false);   // 回复标记 false

    }


    return true;

}


int  StarArry::getLeftStar()

{

    int i,j, count = 0;

    

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            if(stars[i][j])

            {

                count++;

            }

            else

            {

                continue;

            } //if

        }

    } // for

   

    return count;

}


/*

 

 stars[i][j] = _s;

 _s->setIndexXY(i, j);

 _s->setPosition(getPositionByIndex(i, j)+Point(0, 100));

 MoveTo *_to = MoveTo::create(0.50f, getPositionByIndex(i, j));

 CallFunc *_fun = CallFunc::create([this]()

 {

 if(this->isEnd() == true)

 {

 UserDefault::getInstance()->setBoolForKey("IsEnd", true);

 UserDefault::getInstance()->setBoolForKey("DeadLayer", true);

 

 }

 });

 

 _s->runAction(Sequence::create(_to, _fun, NULL));

 i--;

 addChild(_s);  //添加到矩阵中


 

 */


#ifndef __popStar__starSprite__

#define __popStar__starSprite__


#include <stdio.h>

#include "cocos2d.h"


USING_NS_CC;


class  Star : public Sprite

{

public:

    static Star*  createStar(int color);

    void init(int color);

    

  

    // 获得星星颜色  死局

    int  getColor() { return  m_color; }

    

    bool isSelect() { return m_select; }

    // 把星星设为已选

    void setSelect(bool select) {   m_select = select ; }

     // 获取坐标索引

    int getIndexX() { return m_indexX; }  // 隐式定义内联函数

    inline int getIndexY() { return m_indexY; }

    

    void setIndexXY(int x, int y) {   m_indexX = x; m_indexY = y; }

    

public:

    static const int STAR_WIDTH  = 80;   //单个 星星宽度

    static const int STAR_HEIGHT = 80;   //单个 星星高度

    

private:

      std::string setColor(int color);

    

private:

    bool m_select;

    int m_color;   //m_colore

    int m_indexX;

    int m_indexY;

    int m_moveDelay;

    

};



#endif /* defined(__popStar__starSprite__) */

//

//  starSprite.cpp

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#include "data.h"

#include "starSprite.h"


Star* Star::createStar(int color)

{

    Star *star = new Star();

    

    if(star && star->initWithFile(star->setColor(color)))

    {

        star->init(color);

        star->autorelease();

        return  star;

    }

    else

    {

        CC_SAFE_DELETE(star);

        star = nullptr;        //

        return  nullptr;

    }

}


void Star::init(int color)

{

    m_select = false;

    m_color = color;


}


std::string Star::setColor(int color)

{

    switch (color)

    {

        case  GREEN:  return "green.png";

        case  BLUE:   return "blue.png";

        case  YELLOW: return "orange.png";

        case  RED:    return "red.png";

        case  PURPLE: return "purple.png";

            

        default:

            CC_ASSERT(0);  // false

    }

}    

—————————————————————————————————————————————

//

//  starArry.h

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#ifndef __popStar__starArry__

#define __popStar__starArry__


#include <stdio.h>

#include <string.h>

#include <deque>

#include <vector>

#include <algorithm>


#include "starSprite.h"

#include "Publics.h"



using namespace std;


// 商店的高度

#define   STOREFEIHT  100

#define   DROPTIME     0.3   // 调整时单个星星下落时间


class StarArry  : public Sprite   // ?? scene()

{

public:

    static StarArry* createMatrix();

    bool init();

    void onTouch(Point& _pos);


    void empty(Ref* obj, Control::EventType);

    void produceBack(Star *);

public:

   

    void initMatrix();

    

    static const int ROW_NUM = 8;

    static const int COL_NUM = 8;

//private:

//public的全局可见,private类内可见  private函数一般是用来给public函数调中A.f1();

    

    void getSelectedList(Star *s) ;  // 获取相同颜色的星星

    void deleteSelectedList();      // 删除数组中同颜色的星星

    void adjustMatrix();           // 消除后,调整二维数组中的内容 即: 调整位置

    void produceStars();           // 消除后产生新的星星

    bool isEnd();                  //判断是否死局

    void clearStarOneByOne();      // 一个接一个的删除星星

    void removeStar(int i,int j);

    int  getLeftStar();

    

    //响应商店函数

    void cleanSameRowAndCol(int _row, int _col);  // 消除同行同列的星星

    void cleanSameColor(int _color);              //  消除相同颜色的星星

    void cleanEightStar(int _i, int _j);                        //  消除八字形

    

    // 通过坐标获取 星星

    Star *getStarByTouchPoint(Point &pos);

    // 通过index获取坐标

    Point getPositionByIndex(int i, int j);

    

private:

    Size  m_size;

    bool  m_overTimer;  // 标志超时

   

    Star* stars[ROW_NUM][COL_NUM];  // 二维数组 来存放星星

    std::vector<Star *> selectedList;   // 用于记录相同颜色的星星

};




#endif /* defined(__popStar__starArry__) */



//

//  starArry.cpp

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#include <time.h>

#include "data.h"

#include "starSprite.h"

#include "starArry.h"

#include "levelShared.h"

#include "jsonRead.h"

#include "starParticle.h"



 StarArry* StarArry::createMatrix()

{

    StarArry *starArry = new StarArry();

  

    if( starArry )

    {

       starArry->autorelease();

       starArry->init();

       return starArry;

    }

    else

    {

        CC_SAFE_DELETE(starArry);

        starArry = nullptr;

        return nullptr;

    }

}


static int oneScore = 0;  // 消除星星得分数

bool StarArry::init()

{

    if( !Sprite::init())

    {

        return false;

    }

    

    m_size = Director::getInstance()->getWinSize();

 

    initMatrix();   //创建星星矩阵

    


    LevelFeature::getInstance()->setScore(0);

    return true;

}

 

void StarArry::initMatrix()

{

    srand(unsigned(time(0)));

    

    int i, j;

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            int _color = rand()%5; // 0~4  随机生成几种颜色

            CCLOG("----: %d", _color);

            Star *s = Star::createStar(_color);

            stars[i][j] = s;

            s->setIndexXY(i, j);   // 为后面 删除 查找用

            s->setPosition(getPositionByIndex(i, j) + Point(0, 100));

           

            // 开始的 运动

            MoveBy *by = MoveBy::create(0.40f,  Point(0, -100));

            s->runAction(by);

            

            addChild(stars[i][j]);

        } // for

    }// for

    

}


// 通过坐标获取 星星

Star * StarArry::getStarByTouchPoint(Point &pos)  // 没问题这个

{   static int a=0;

     CCLOG(" - - --  - touch times: %d ", a++);

    int j = pos.x/Star::STAR_WIDTH; // 列索引

    

    int t = (pos.y - STOREFEIHT)/Star::STAR_HEIGHT;

    int i = ROW_NUM - 1 - t;

    

    // 如果 不存在 或 未点击到星星 返回空

    if(i >=0 && i< ROW_NUM && j>=0 && j< COL_NUM && stars[i][j] != nullptr)

    {

        return stars[i][j];

    }

    else

    {

        return  nullptr;

    }

}


// 通过index获取坐标

Point StarArry::getPositionByIndex(int i, int j)

{

    float _x = j*Star::STAR_WIDTH + Star::STAR_WIDTH/2;

    float _y = (COL_NUM - i)*Star::STAR_HEIGHT - Star::STAR_HEIGHT/2 + STOREFEIHT;

    

    return  Point(_x, _y);

}


void StarArry::onTouch(Point &_pos)

{

    

    Star*_s = getStarByTouchPoint(_pos);

 

    if(_s)

    {

        getSelectedList(_s);

        

        deleteSelectedList();

    }

}


// 搜索相同颜色的 星星

void StarArry::getSelectedList(Star *s)

{

    selectedList.clear();

    

    std::deque<Star *>  _travelList;

    _travelList.push_back(s);

    deque<Star*>::iterator it;

    

    for(  it= _travelList.begin();    it != _travelList.end(); ++it)

   // for(auto &t : _travelList)    //  通过下标来 搜索 上下左右

    {

        Star *_star = *it;   //返回引用值

        Star *_linkStar = nullptr;

        

        int _indexX = _star->getIndexX();

        int _indexY = _star->getIndexY();

      

        //  上

        if(_indexX-1 >=0 && (_linkStar = stars[_indexX-1][_indexY])!= NULL )

        {

            if(_linkStar->isSelect()== false && _linkStar->getColor() == _star->getColor() )

            {

                _travelList.push_back(stars[_indexX-1][_indexY]);

            }

        }

        // 下

        if(_indexX+1 <= ROW_NUM-1 && (_linkStar = stars[_indexX+1][_indexY])!= NULL)

        {

            if(_linkStar->isSelect() == false && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX+1][_indexY]);

            }

        }

        

        //  左   判断是存在

        if(_indexY-1 >=0 && (_linkStar=stars[_indexX][_indexY-1]))

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY-1]);

            }

        }

        // 右

        if(_indexY+1 <= COL_NUM-1 && (_linkStar=stars[_indexX][_indexY+1])!= nullptr )

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY+1]);

              //  _linkStar->setSelect(true); //不用标记;目前只是发现同色 但自身为搜索

            }

        }

        

        if( !_star->isSelect())

        {

            _star->setSelect(true);  // 标记已搜索过

            selectedList.push_back(_star);

        }

        

//        _travelList.pop_front();

//        it =  _travelList.begin(); // 取出第一个

    } // for

    

//    selectedList.clear();

     CCLOG(" -- - getSelectedList  - -- ");

}


// 消除矩阵中 同颜色的星星

void StarArry::deleteSelectedList()

{

//    oneScore = 0;  // 每次清空

    int _score = 0;

    

    if(selectedList.size() <= 2)       // 如果没有搜到

    {

        selectedList.at(0)->setSelect(false);

        if(selectedList.size() == 2)    // 如果2个颜色相同

        {

            selectedList.at(1)->setSelect(false);

        }

        return ;

    }

    

    // 若果存在同颜色的   就消除 同色的星星

    for(auto it = selectedList.begin(); it != selectedList.end(); it++)

    {

        Star* _star = *it;        // 下标删除

        removeStar(_star->getIndexX(),_star->getIndexY());

        

        _score = _score + 20;  //每消除一个的20分

    }

    

    // 放在for外面 优化效率 减少对文件操作    判断:应为存储分的模式不同

    if(UserDefault::getInstance()->getBoolForKey("IsForeverModel", false) == true)

    {

        // 无限模式

        int _scoreForever = UserDefault::getInstance()->getIntegerForKey("foreverScore");

        // 之前消除的得分 + 本次消除得分

        UserDefault::getInstance()->setIntegerForKey("foreverScore", _score+_scoreForever);

    }

    else

    {   // 关卡模式

        LevelFeature::getInstance()->setScore(LevelFeature::getInstance()->getScore() + _score);

    }

    

    selectedList.clear();

    CCLOG(" -- - getSelectedList  - - @ - ");

    

    adjustMatrix();  //如果执行了 删除操作;就调整

    

    produceStars();   // 产生星星

}


 static int  s_count[StarArry::ROW_NUM];

// 调整主要改变 索引

void StarArry::adjustMatrix()

{

    memset(s_count, 0, sizeof(s_count));

    

  

    //*************************************************************

    for(int i = ROW_NUM-1;i>=0;i--)

    {

         for(int j = 0;j <= COL_NUM-1; j++){

            if(stars[i][j] == nullptr)

            {

                int up = i;

                int dis = 0;

                while(stars[up][j] == nullptr)

                {

                    dis++;    // 空的个数

                    up--;

                    if(up<0)

                       {   break;   }

                }

                

                if(s_count[j] == 0 )     // 记录 "该列" 要移动星星个数

                {

                    int pp = s_count[j] = i-dis+1;

                }

          //   int pp = s_count[j] = i-dis+1;    //记录 "该列" 要移动星星个数

                int k=0;

                for(int begin_i = i - dis;  begin_i >= 0;  begin_i--) //循环次数为要移动星星个数

                {

                    if(stars[begin_i][j] == nullptr)  // 为空 不用移动

                        continue;

                

                    //              目标位置                     原始位置

                    Star* s = stars[begin_i + dis][j] = stars[begin_i][j];

                    s->setIndexXY(begin_i + dis,j);   // 不能少  删除查找iyong

//                    s->setIndexXY(<#int x#>, <#int y#>)

               //     s->setDesPosition(getPositionByIndex(begin_i + dis,j));

                    Point _pos = getPositionByIndex(begin_i+dis, j);

                    

                    DelayTime* _time = DelayTime::create(0.05*k); // 延迟时间

                    k++;

                    MoveTo *to = MoveTo::create(DROPTIME, _pos);

                    stars[begin_i][j]->stopAllActions();

                    stars[begin_i][j]->runAction(Sequence::create(_time, to, NULL));

                    

                    stars[begin_i][j]->setOpacity(255);

                    stars[begin_i][j] = nullptr;

                }

            }

            else{

                continue;

            }

        } // for

    }  // for

    

   //    produceStars();

}


// 产生新的星星

void StarArry::produceStars()

{

    srand((unsigned)time(0));

    int i, j;

    

    for(j=0; j<COL_NUM; j++)

    {

        for(i=ROW_NUM-1; i>=0; i--)

        {

            if(stars[i][j] )

            {

                continue;

            }

            

            if(stars[i][j] == nullptr )

            {

                //  首先找出    空的星星个数

                int up = i;

                int dis = 0;

                while(stars[up][j] == nullptr)

                {

                    dis++;    // 空的个数

                    up--;

                    if(up<0)

                    {   break;   }

                }


                //***************

                int k =  s_count[j];  //读取 "该列" 移动星星个数

                while( i>=0 ) // =0  -1

                {

                 int _color = rand()%5;

                    Star *_s = Star::createStar(_color);

           

                    stars[i][j] = _s;

                    _s->setIndexXY(i, j);

                    _s->setPosition(getPositionByIndex(i, j)+Point(0, Star::STAR_HEIGHT*dis));//100

                    

                    DelayTime *_time = DelayTime::create(0.05*k);

                    k++;

                    _s->setOpacity(0);

                    FadeTo *_fadeTo =  FadeTo::create(DROPTIME, 255); //bug

                    MoveTo *_to = MoveTo::create( DROPTIME, getPositionByIndex(i, j));

                    Spawn *_spawn = Spawn::create(_fadeTo, _to, NULL);

           

                    CallFunc *_fun = CallFunc::create([this]()

                    {

                        if(this->isEnd() == true)

                        {

                            UserDefault::getInstance()->setBoolForKey("IsEnd", true);

                            UserDefault::getInstance()->setBoolForKey("DeadLayer", true);

                        }

//                        _s->setOpacity(255);     // 解决bug 出现半透明现象

                     });

                    

                    _s->runAction(Sequence::create( _time, _spawn, _fun, NULL));

                    i--;

                    addChild(_s);  //添加到矩阵中

        

                }

            }  //if

         

        }  // for

    } //for

    

    

}


void StarArry::produceBack(Star *)

{

    

}


void StarArry::empty(cocos2d::Ref *obj, Control::EventType)

{

    

}



void StarArry::cleanSameRowAndCol(int _row, int _col)

{

    int i, j;

    

    // 消除同一行的星星

    for(j=0; j<COL_NUM; j++)

    {

        removeStar(_row,j);

    }

    //adjustMatrix();

    for(i=0; i<ROW_NUM; i++)

    {

        removeStar(i,_col);

    }

    

     adjustMatrix();

     produceStars();

}


// 消除同颜色的星星

void StarArry::cleanSameColor(int _color)

{

    int i, j;

    

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            if(stars[i][j] && stars[i][j]->getColor() == _color)

            {

                removeStar(i,j);

            } // if

            else

                continue;

        }

    }

    

     adjustMatrix();

  //   this->scheduleOnce(schedule_selector(StarArry::intervalProduce), 0.50f);

     produceStars();

}


void StarArry::cleanEightStar(const int i, const int j)

{

    removeStar(i, j);//本身

    removeStar(i-1, j-1);//左上

    removeStar(i, j-1);//左

    removeStar(i, j-2);//左2

    removeStar(i+1, j-1);//左下

    removeStar(i+1, j);//下

    removeStar(i+2, j);//下2

    removeStar(i+1, j+1);//右下

    removeStar(i, j+1);//右

    removeStar(i, j+2);//右2

    removeStar(i-1, j+1);//右上

    removeStar(i-1, j);//上

    removeStar(i-2, j);//上2

    int _i = i, _j = j;

 

//    while(_i>=0 && _j>=0)    // 左上

//    {

//        _i--;

//        _j--;

      removeStar(_i,_j);

//        if(stars[_i][_j])

//                    {

//                        stars[_i][_j]->removeFromParentAndCleanup(true);

//                        stars[_i][_j] = nullptr;

//                    }

//    }

//

//    _i = i, _j = j;

//        CCLOG("touch  index :  i=%d,j=%d", _i, _j);

//    while (_i <ROW_NUM && _j<COL_NUM)   // 右下

//    {

//        

//        _i++;

//        _j++;

//        if(stars[_i][_j])

//                                {

//                                    stars[_i][_j]->removeFromParentAndCleanup(true);

//                                    stars[_i][_j] = nullptr;

//                                }

//    }

//

//    _i = i, _j = j;

//    while ( _i>=0 && _j<COL_NUM)   // 右上

//    {

//        _i--;

//        _j++;

//        if(stars[_i][_j])

//        {

//            stars[_i][_j]->removeFromParentAndCleanup(true);

//            stars[_i][_j] = nullptr;

//        }

//    }

//    

//    _i = i, _j = j;

//    while (_i < ROW_NUM && _j>=0)   // 左下

//    {

//        _i++;

//        _j--;

//        if(stars[_i][_j])

//        {

//            stars[_i][_j]->removeFromParentAndCleanup(true);

//            stars[_i][_j] = nullptr;

//        }

//    }

//    

    

    adjustMatrix();

    produceStars();

}

 


void StarArry::clearStarOneByOne()  // 为啥出来红线

{

    int i,j;

 

    for(i=0; i<ROW_NUM; i++)   //安列来消除 死局星星

    {

        for(j=0; j<COL_NUM; j++)

        {

            removeStar(i,j);

        }

    } // for

    

 

}


// 单独写个函数

void StarArry::removeStar(int i,int j)

{

    if (i >=0 && i < ROW_NUM && j >= 0 && j < COL_NUM && stars[i][j])

    {

        showStarParticleEffect(stars[i][j]->getColor(), stars[i][j]->getPosition(), this);

        

        stars[i][j]->removeFromParentAndCleanup(true);

        stars[i][j] = nullptr;

    }

}


// 判断是否死局

bool StarArry::isEnd()

{

    std::vector<Star *> deadEnd;

    

    int i,j, k;

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

          

            for(k=0; k< deadEnd.size(); k++)

            {

                if(deadEnd.at(k)->isSelect() == true)

                deadEnd.at(k)->setSelect(false);   // 回复标记 false

            }

            

            deadEnd.clear();

    std::deque<Star *>  _travelList;

    _travelList.push_back(stars[i][j]);

    deque<Star*>::iterator it;

    

    for(  it= _travelList.begin();    it != _travelList.end(); ++it)

    {

        Star *_star = *it;   //返回引用值

        Star *_linkStar = nullptr;

        

        int _indexX = _star->getIndexX();

        int _indexY = _star->getIndexY();

        

        //  上

        if(_indexX-1 >=0 && (_linkStar = stars[_indexX-1][_indexY])!= NULL )

        {

            if(_linkStar->isSelect()== false && _linkStar->getColor() == _star->getColor() )

            {

                _travelList.push_back(stars[_indexX-1][_indexY]);

            }

        }

        // 下

        if(_indexX+1 <= ROW_NUM-1 && (_linkStar = stars[_indexX+1][_indexY])!= NULL)

        {

            if(_linkStar->isSelect() == false && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX+1][_indexY]);

            }

        }

        

        //  左   判断是存在

        if(_indexY-1 >=0 && (_linkStar=stars[_indexX][_indexY-1]))

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY-1]);

            }

        }

        // 右

        if(_indexY+1 <= COL_NUM-1 && (_linkStar=stars[_indexX][_indexY+1])!= nullptr )

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY+1]);

            }

        }

        

        if( !_star->isSelect())

        {

            _star->setSelect(true);  // 标记已搜索过

            deadEnd.push_back(_star);

        }

        

        if(deadEnd.size()>=3)

        {

            for(k=0; k< deadEnd.size(); k++)

            {

                if(deadEnd.at(k)->isSelect() == true)

                deadEnd.at(k)->setSelect(false);   // 回复标记 false

            }

            

            return  false;

        }

    } // 最里层 for

            

        }

    }


    // 如果小于3个

    for(k=0; k< deadEnd.size(); k++)

    {

        if(deadEnd.at(k)->isSelect() == true)

        deadEnd.at(k)->setSelect(false);   // 回复标记 false

    }


    return true;

}


int  StarArry::getLeftStar()

{

    int i,j, count = 0;

    

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            if(stars[i][j])

            {

                count++;

            }

            else

            {

                continue;

            } //if

        }

    } // for

   

    return count;

}


/*

 

 stars[i][j] = _s;

 _s->setIndexXY(i, j);

 _s->setPosition(getPositionByIndex(i, j)+Point(0, 100));

 MoveTo *_to = MoveTo::create(0.50f, getPositionByIndex(i, j));

 CallFunc *_fun = CallFunc::create([this]()

 {

 if(this->isEnd() == true)

 {

 UserDefault::getInstance()->setBoolForKey("IsEnd", true);

 UserDefault::getInstance()->setBoolForKey("DeadLayer", true);

 

 }

 });

 

 _s->runAction(Sequence::create(_to, _fun, NULL));

 i--;

 addChild(_s);  //添加到矩阵中


 

 */

----------------------------------------------------------------老师Demo

// //  GameStart.cpp //  Chapt16-TestPlaneGame // //  Created by ibokan on 13-11-7. // // #include "GameStart.h" #include "GameMap.h" #include "Bullet.h" #include "SimpleAudioEngine.h" #include "Enemy.h" #include <time.h> using namespace cocos2d; using namespace CocosDenshion; static GameStart* my = NULL; GameStart* GameStart::shared() {      if (my != NULL)      {          return my;      }      else          return NULL; } CCScene* GameStart::scene() {      CCScene* scene = CCScene::create();      GameStart* layer = GameStart::create();      scene->addChild(layer);      return scene; } bool GameStart::init() {      if (!CCLayer::init())      {          return false ;      }            // 设置随机数种子      srand ( time (NULL));            SimpleAudioEngine::sharedEngine()->playBackgroundMusic( "gameMusic.mp3" );            my = this ;            GameMap* map = GameMap::create( "map.png" );      addChild(map);            HeroPlayer* player = HeroPlayer::createPlayer( "player.png" );      addChild(player,20,tag_player);            // 敌人数组      enemies = CCArray::create();      CC_SAFE_RETAIN(enemies);            this ->schedule(schedule_selector(GameStart::autoCreateBullet), 0.3);      this ->schedule(schedule_selector(GameStart::autoCreateEnemy), 1.0f);            return true ; } void GameStart::autoCreateEnemy() {      int count = CCRANDOM_0_1()*10;      for ( int i = 0; i < count; i++)      {          int randomType = rand ()%3;                    const char * name = "enemy_bug.png" ;                    switch (randomType)          {              case 0:              {                  name = "enemy_bug.png" ;              }                  break ;              case 1:              {                  name = "enemy_duck.png" ;              }                  break ;              case 2:              {                  name = "enemy_pig.png" ;              }                  break ;                                default :                  break ;          // switch()                              int type = rand ()%2;          Enemy* enemy = Enemy::createEnemy(name, type);          enemies->addObject(enemy);          addChild(enemy);                } } void GameStart::autoCreateBullet() {      HeroPlayer* player = this ->getHeroPlayer();      Bullet* bullet = Bullet::create(ccpAdd(player->getPosition(), ccp(0, player->getContentSize().height/2)), 180.0, "p_bullet.png" );      addChild(bullet);            SimpleAudioEngine::sharedEngine()->playEffect( "effect_bullet.mp3" ); } HeroPlayer* GameStart::getHeroPlayer() {      return (HeroPlayer*) this ->getChildByTag(tag_player); } void GameStart::gameLost() {       } void GameStart::gameWin() {       } GameStart::~GameStart() {      CC_SAFE_RELEASE_NULL(enemies); }
// //  Bullet.cpp //  Chapt16-TestPlaneGame // //  Created by ibokan on 13-11-7. // // #include "Bullet.h" #include "GameStart.h" #include "Enemy.h" #include "SimpleAudioEngine.h" using namespace cocos2d; using namespace CocosDenshion; Bullet* Bullet::create(cocos2d::CCPoint position, float speed, const char *fileName) {      Bullet* bullet = new Bullet();      if (bullet && bullet->initWithFile(fileName))      {          bullet->autorelease();          bullet->init(position, speed);          return bullet;      }      else      {          CC_SAFE_DELETE(bullet);          return NULL;      } } void Bullet::init(cocos2d::CCPoint position, float speed) {      this ->setPosition(position);      m_speed = speed;      this ->scheduleUpdate();            this ->move(); } void Bullet::move() {      CCSize size = CCDirector::sharedDirector()->getWinSize();      float h = size.height - this ->getPosition().y;      CCMoveBy* move = CCMoveBy::create(h / m_speed, ccp(0, h));      CCCallFuncN* call = CCCallFuncN::create( this , callfuncN_selector(Bullet::removeBullet));      CCSequence* sequence = CCSequence::create(move,call);      this ->runAction(sequence); } void Bullet::removeBullet() {      this ->removeFromParentAndCleanup( true );  关闭定时器 -- 好像是在这调用 ??? } void Bullet::update( float delta) {      CCArray* enemies = GameStart::shared()->enemies;      CCObject* enemy = NULL;      CCARRAY_FOREACH(enemies, enemy)      {          Enemy* ene = (Enemy*)enemy;                    if (ene->boundingBox().intersectsRect( this ->boundingBox()))          {              // 击中了敌人              SimpleAudioEngine::sharedEngine()->playEffect( "effect_boom.mp3" );                            // 添加粒子效果              CCParticleSystemQuad* particle = CCParticleSystemQuad::create( "particle_boom.plist" );              particle->setPosition(ene->getPosition());              particle->setAutoRemoveOnFinish( true );              GameStart::shared()->addChild(particle);                            HeroPlayer* player = GameStart::shared()->getHeroPlayer();              player->addScore(ene->m_scoreValue);              player->addKillCount(1);                            enemies->removeObject(ene);              ene->removeFromParentAndCleanup( true );                        }      } } //  合适调用:该节点从父节点中移除是  -- 退出场景是 void Bullet::onExit() {      this ->CCSprite::onExit();     // 一定要调用父的 -- OR bug      this ->unscheduleUpdate();     //关闭定时器 --- 耗费CPU时间 }
// //  HeroPlayer.cpp //  Chapt16-TestPlaneGame // //  Created by ibokan on 13-11-8. // // #include "HeroPlayer.h" #include "GameStart.h" using namespace cocos2d; using namespace std; HeroPlayer* HeroPlayer::createPlayer( const char *fileName) {      HeroPlayer* player = new HeroPlayer();      if (player && player->initWithFile(fileName))      {          player->autorelease();          player->initPlayer();          return player;      }      else      {          CC_SAFE_DELETE(player);          return NULL;      } } void HeroPlayer::initPlayer() {      CCSize size = CCDirector::sharedDirector()->getWinSize();            this ->setPosition(ccp(size.width/2, this ->getContentSize().height/2+5));      // 初始化基本数据      m_hpMax = 3;      m_hp = 3;      m_score = 0;      m_killCount = 0;      m_isStrong = false ;      isDead = false ;                  // 初始化三滴血      for ( int i = 0; i < 3; i++)      {          CCSprite* spriteHp = CCSprite::create( "icon_hp.png" );          spriteHp->setPosition(ccp(size.width - spriteHp->getContentSize().width*i-20, spriteHp->getContentSize().height/2+5));          switch (i) {              case 0:                  spriteHp->setTag(tag_playerHp1);                  break ;              case 1:                  spriteHp->setTag(tag_playerHp2);                  break ;              case 2:                  spriteHp->setTag(tag_playerHp3);                  break ;                                default :                  break ;          }                    GameStart::shared()->addChild(spriteHp,20);      }            // 得分label      CCLabelTTF* label = CCLabelTTF::create( "分数:" , "Marker Felt" , 25);      label->setColor(ccWHITE);      label->setPosition(ccp(30, size.height-20));      GameStart::shared()->addChild(label, 20);            string scoreStr = ConvertToString(m_score);      CCLabelTTF* labelScore = CCLabelTTF::create(scoreStr.c_str(), "Marker Felt" , 25);      labelScore->setPosition(ccp(110, size.height-20));      labelScore->setColor(ccc3(255,255,0));      GameStart::shared()->addChild(labelScore,20,tag_scoreLabel);            // 杀敌label      CCLabelTTF* labelC = CCLabelTTF::create( "得分:" , "Marker Felt" , 25);      labelC->setPosition(ccp(30, size.height-50));      GameStart::shared()->addChild(labelC,20);            string killStr = ConvertToString(m_killCount);      killStr += "/100" ;      CCLabelTTF* labelKill = CCLabelTTF::create(killStr.c_str(), "Marker Felt" , 25);      labelKill->setPosition(ccp(110, size.height-50));      labelKill->setColor(ccc3(255, 255, 0));      GameStart::shared()->addChild(labelKill,20,tag_killCountLabel);       } void HeroPlayer::addScore( int value) {      m_score += value;      string addScore = ConvertToString(m_score); //    addScore += "/100";      CCLabelTTF* label = (CCLabelTTF*)GameStart::shared()->getChildByTag(tag_scoreLabel);      label->setString(addScore.c_str());       } void HeroPlayer::addKillCount( int value) {      m_killCount += value;      string killCountStr = ConvertToString(m_killCount);      killCountStr += "/100" ;      CCLabelTTF* label = (CCLabelTTF*)GameStart::shared()->getChildByTag(tag_killCountLabel);      label->setString(killCountStr.c_str());            if (m_killCount >= 100)      {          // 最高分本地化存储          /*           * 回去自行研究CCUserDefault           */                    // 游戏胜利          GameStart::shared()->gameWin();      } } void HeroPlayer::downHp() {      if (m_isStrong)      {          return ;      }            m_hp -= 1;      if (m_hp <= 0)      {          isDead = true ;                    // 英雄挂掉后,读取本地存储的最高分,如果分数更高,将当前得分写入本地          //CCUserDefault::sharedUserDefault()->setStringForKey(<#const char *pKey#>, <#const std::string &value#>)          //CCUserDefault::sharedUserDefault()->getStringForKey(<#const char *pKey#>, <#const std::string &defaultValue#>)                    GameStart::shared()->gameLost();                }      else      {          switch (m_hp) {              case 2:                  GameStart::shared()->removeChildByTag(tag_playerHp3);                  break ;              case 1:                  GameStart::shared()->removeChildByTag(tag_playerHp2);                  break ;                                default :                  break ;          }                    // 设置主角无敌          m_isStrong = true ;                    CCBlink* blink = CCBlink::create(2, 20);          CCCallFunc* func = CCCallFunc::create( this , callfunc_selector(HeroPlayer::setPlayerUnStrong));          CCSequence* sequence = CCSequence::create(blink,func);          this ->runAction(sequence);                } } void HeroPlayer::setPlayerUnStrong() {      m_isStrong = false ; } void HeroPlayer::onEnter() {      CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate( this , 0, true );      CCSprite::onEnter(); } void HeroPlayer::onExit() {      CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate( this );      CCSprite::onExit(); } bool HeroPlayer::ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) {      this ->setPosition(pTouch->getLocation());      return true ; } void HeroPlayer::ccTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) {      this ->setPosition(pTouch->getLocation()); } void HeroPlayer::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) {      this ->setPosition(pTouch->getLocation()); }

_sta



用lua写popStar

考虑问题( 会有三种情况出现): 先想有几种情况,每种情况有份几种   --- 见折半查找 于豆豆。 如果遇到问题没有现成解决方案时, 就有用了(参考  消除 搜素算法) ---------------------------------------------------------------------------------------------------- owner()huidioao
1:   MatrixStars = {{},{},{},{},{},{},{},{}}   -- 星星矩阵 .  直接  ={}不对 
for i=1, 8, 1 do MatrixStars[i] = {} for j=1,  8,  1 do -- 随机数      local _temp =  math.random(1,5); -- 创建星星矩阵 local star = StarSprite.new(_temp); star:setPosition(cc.p(display.width/2, display.height/2)) self:addChild(star);
MatrixStars[i][j] = "star”;    — (a nil value) 此时键不存在,就无法引用 2:  A  当调用local star = StarSprite.new(_temp); 时,参数会自动传给ctor(var)/function(var)中, B     local imagePath = StarSprite.getImageFile(var), 用冒号为啥不对, 因为此时 无self,  (源码) StarSprite = class("StarSprite", function (var) local imagePath = StarSprite.getImageFile(var) return cc.Sprite:create(imagePath); end);
3:星星类也可以继承Node类。做法(Node是一个小方块, 在小方块上创建一个星星,即内部创建星星) local StarSprite = class("StarSprite", function () return cc.Node:create(); end);
4: coocsbuilder 中的变量不会自动对应, 要binding起来 ---------------------------------------------------------------------------------------------------
#ifndef __popStar__starSprite__

#define __popStar__starSprite__


#include <stdio.h>

#include "cocos2d.h"


USING_NS_CC;


class  Star : public Sprite

{

public:

    static Star*  createStar(int color);

    void init(int color);

    

  

    // 获得星星颜色  死局

    int  getColor() { return  m_color; }

    

    bool isSelect() { return m_select; }

    // 把星星设为已选

    void setSelect(bool select) {   m_select = select ; }

     // 获取坐标索引

    int getIndexX() { return m_indexX; }  // 隐式定义内联函数

    inline int getIndexY() { return m_indexY; }

    

    void setIndexXY(int x, int y) {   m_indexX = x; m_indexY = y; }

    

public:

    static const int STAR_WIDTH  = 80;   //单个 星星宽度

    static const int STAR_HEIGHT = 80;   //单个 星星高度

    

private:

      std::string setColor(int color);

    

private:

    bool m_select;

    int m_color;   //m_colore

    int m_indexX;

    int m_indexY;

    int m_moveDelay;

    

};



#endif /* defined(__popStar__starSprite__) */

//

//  starSprite.cpp

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#include "data.h"

#include "starSprite.h"


Star* Star::createStar(int color)

{

    Star *star = new Star();

    

    if(star && star->initWithFile(star->setColor(color)))

    {

        star->init(color);

        star->autorelease();

        return  star;

    }

    else

    {

        CC_SAFE_DELETE(star);

        star = nullptr;        //

        return  nullptr;

    }

}


void Star::init(int color)

{

    m_select = false;

    m_color = color;


}


std::string Star::setColor(int color)

{

    switch (color)

    {

        case  GREEN:  return "green.png";

        case  BLUE:   return "blue.png";

        case  YELLOW: return "orange.png";

        case  RED:    return "red.png";

        case  PURPLE: return "purple.png";

            

        default:

            CC_ASSERT(0);  // false

    }

}    

—————————————————————————————————————————————

//

//  starArry.h

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#ifndef __popStar__starArry__

#define __popStar__starArry__


#include <stdio.h>

#include <string.h>

#include <deque>

#include <vector>

#include <algorithm>


#include "starSprite.h"

#include "Publics.h"



using namespace std;


// 商店的高度

#define   STOREFEIHT  100

#define   DROPTIME     0.3   // 调整时单个星星下落时间


class StarArry  : public Sprite   // ?? scene()

{

public:

    static StarArry* createMatrix();

    bool init();

    void onTouch(Point& _pos);


    void empty(Ref* obj, Control::EventType);

    void produceBack(Star *);

public:

   

    void initMatrix();

    

    static const int ROW_NUM = 8;

    static const int COL_NUM = 8;

//private:

//public的全局可见,private类内可见  private函数一般是用来给public函数调中A.f1();

    

    void getSelectedList(Star *s) ;  // 获取相同颜色的星星

    void deleteSelectedList();      // 删除数组中同颜色的星星

    void adjustMatrix();           // 消除后,调整二维数组中的内容 即: 调整位置

    void produceStars();           // 消除后产生新的星星

    bool isEnd();                  //判断是否死局

    void clearStarOneByOne();      // 一个接一个的删除星星

    void removeStar(int i,int j);

    int  getLeftStar();

    

    //响应商店函数

    void cleanSameRowAndCol(int _row, int _col);  // 消除同行同列的星星

    void cleanSameColor(int _color);              //  消除相同颜色的星星

    void cleanEightStar(int _i, int _j);                        //  消除八字形

    

    // 通过坐标获取 星星

    Star *getStarByTouchPoint(Point &pos);

    // 通过index获取坐标

    Point getPositionByIndex(int i, int j);

    

private:

    Size  m_size;

    bool  m_overTimer;  // 标志超时

   

    Star* stars[ROW_NUM][COL_NUM];  // 二维数组 来存放星星

    std::vector<Star *> selectedList;   // 用于记录相同颜色的星星

};




#endif /* defined(__popStar__starArry__) */



//

//  starArry.cpp

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#include <time.h>

#include "data.h"

#include "starSprite.h"

#include "starArry.h"

#include "levelShared.h"

#include "jsonRead.h"

#include "starParticle.h"



 StarArry* StarArry::createMatrix()

{

    StarArry *starArry = new StarArry();

  

    if( starArry )

    {

       starArry->autorelease();

       starArry->init();

       return starArry;

    }

    else

    {

        CC_SAFE_DELETE(starArry);

        starArry = nullptr;

        return nullptr;

    }

}


static int oneScore = 0;  // 消除星星得分数

bool StarArry::init()

{

    if( !Sprite::init())

    {

        return false;

    }

    

    m_size = Director::getInstance()->getWinSize();

 

    initMatrix();   //创建星星矩阵

    


    LevelFeature::getInstance()->setScore(0);

    return true;

}

 

void StarArry::initMatrix()

{

    srand(unsigned(time(0)));

    

    int i, j;

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            int _color = rand()%5; // 0~4  随机生成几种颜色

            CCLOG("----: %d", _color);

            Star *s = Star::createStar(_color);

            stars[i][j] = s;

            s->setIndexXY(i, j);   // 为后面 删除 查找用

            s->setPosition(getPositionByIndex(i, j) + Point(0, 100));

           

            // 开始的 运动

            MoveBy *by = MoveBy::create(0.40f,  Point(0, -100));

            s->runAction(by);

            

            addChild(stars[i][j]);

        } // for

    }// for

    

}


// 通过坐标获取 星星

Star * StarArry::getStarByTouchPoint(Point &pos)  // 没问题这个

{   static int a=0;

     CCLOG(" - - --  - touch times: %d ", a++);

    int j = pos.x/Star::STAR_WIDTH; // 列索引

    

    int t = (pos.y - STOREFEIHT)/Star::STAR_HEIGHT;

    int i = ROW_NUM - 1 - t;

    

    // 如果 不存在 或 未点击到星星 返回空

    if(i >=0 && i< ROW_NUM && j>=0 && j< COL_NUM && stars[i][j] != nullptr)

    {

        return stars[i][j];

    }

    else

    {

        return  nullptr;

    }

}


// 通过index获取坐标

Point StarArry::getPositionByIndex(int i, int j)

{

    float _x = j*Star::STAR_WIDTH + Star::STAR_WIDTH/2;

    float _y = (COL_NUM - i)*Star::STAR_HEIGHT - Star::STAR_HEIGHT/2 + STOREFEIHT;

    

    return  Point(_x, _y);

}


void StarArry::onTouch(Point &_pos)

{

    

    Star*_s = getStarByTouchPoint(_pos);

 

    if(_s)

    {

        getSelectedList(_s);

        

        deleteSelectedList();

    }

}


// 搜索相同颜色的 星星

void StarArry::getSelectedList(Star *s)

{

    selectedList.clear();

    

    std::deque<Star *>  _travelList;

    _travelList.push_back(s);

    deque<Star*>::iterator it;

    

    for(  it= _travelList.begin();    it != _travelList.end(); ++it)

   // for(auto &t : _travelList)    //  通过下标来 搜索 上下左右

    {

        Star *_star = *it;   //返回引用值

        Star *_linkStar = nullptr;

        

        int _indexX = _star->getIndexX();

        int _indexY = _star->getIndexY();

      

        //  上

        if(_indexX-1 >=0 && (_linkStar = stars[_indexX-1][_indexY])!= NULL )

        {

            if(_linkStar->isSelect()== false && _linkStar->getColor() == _star->getColor() )

            {

                _travelList.push_back(stars[_indexX-1][_indexY]);

            }

        }

        // 下

        if(_indexX+1 <= ROW_NUM-1 && (_linkStar = stars[_indexX+1][_indexY])!= NULL)

        {

            if(_linkStar->isSelect() == false && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX+1][_indexY]);

            }

        }

        

        //  左   判断是存在

        if(_indexY-1 >=0 && (_linkStar=stars[_indexX][_indexY-1]))

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY-1]);

            }

        }

        // 右

        if(_indexY+1 <= COL_NUM-1 && (_linkStar=stars[_indexX][_indexY+1])!= nullptr )

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY+1]);

              //  _linkStar->setSelect(true); //不用标记;目前只是发现同色 但自身为搜索

            }

        }

        

        if( !_star->isSelect())

        {

            _star->setSelect(true);  // 标记已搜索过

            selectedList.push_back(_star);

        }

        

//        _travelList.pop_front();

//        it =  _travelList.begin(); // 取出第一个

    } // for

    

//    selectedList.clear();

     CCLOG(" -- - getSelectedList  - -- ");

}


// 消除矩阵中 同颜色的星星

void StarArry::deleteSelectedList()

{

//    oneScore = 0;  // 每次清空

    int _score = 0;

    

    if(selectedList.size() <= 2)       // 如果没有搜到

    {

        selectedList.at(0)->setSelect(false);

        if(selectedList.size() == 2)    // 如果2个颜色相同

        {

            selectedList.at(1)->setSelect(false);

        }

        return ;

    }

    

    // 若果存在同颜色的   就消除 同色的星星

    for(auto it = selectedList.begin(); it != selectedList.end(); it++)

    {

        Star* _star = *it;        // 下标删除

        removeStar(_star->getIndexX(),_star->getIndexY());

        

        _score = _score + 20;  //每消除一个的20分

    }

    

    // 放在for外面 优化效率 减少对文件操作    判断:应为存储分的模式不同

    if(UserDefault::getInstance()->getBoolForKey("IsForeverModel", false) == true)

    {

        // 无限模式

        int _scoreForever = UserDefault::getInstance()->getIntegerForKey("foreverScore");

        // 之前消除的得分 + 本次消除得分

        UserDefault::getInstance()->setIntegerForKey("foreverScore", _score+_scoreForever);

    }

    else

    {   // 关卡模式

        LevelFeature::getInstance()->setScore(LevelFeature::getInstance()->getScore() + _score);

    }

    

    selectedList.clear();

    CCLOG(" -- - getSelectedList  - - @ - ");

    

    adjustMatrix();  //如果执行了 删除操作;就调整

    

    produceStars();   // 产生星星

}


 static int  s_count[StarArry::ROW_NUM];

// 调整主要改变 索引

void StarArry::adjustMatrix()

{

    memset(s_count, 0, sizeof(s_count));

    

  

    //*************************************************************

    for(int i = ROW_NUM-1;i>=0;i--)

    {

         for(int j = 0;j <= COL_NUM-1; j++){

            if(stars[i][j] == nullptr)

            {

                int up = i;

                int dis = 0;

                while(stars[up][j] == nullptr)

                {

                    dis++;    // 空的个数

                    up--;

                    if(up<0)

                       {   break;   }

                }

                

                if(s_count[j] == 0 )     // 记录 "该列" 要移动星星个数

                {

                    int pp = s_count[j] = i-dis+1;

                }

          //   int pp = s_count[j] = i-dis+1;    //记录 "该列" 要移动星星个数

                int k=0;

                for(int begin_i = i - dis;  begin_i >= 0;  begin_i--) //循环次数为要移动星星个数

                {

                    if(stars[begin_i][j] == nullptr)  // 为空 不用移动

                        continue;

                

                    //              目标位置                     原始位置

                    Star* s = stars[begin_i + dis][j] = stars[begin_i][j];

                    s->setIndexXY(begin_i + dis,j);   // 不能少  删除查找iyong

//                    s->setIndexXY(<#int x#>, <#int y#>)

               //     s->setDesPosition(getPositionByIndex(begin_i + dis,j));

                    Point _pos = getPositionByIndex(begin_i+dis, j);

                    

                    DelayTime* _time = DelayTime::create(0.05*k); // 延迟时间

                    k++;

                    MoveTo *to = MoveTo::create(DROPTIME, _pos);

                    stars[begin_i][j]->stopAllActions();

                    stars[begin_i][j]->runAction(Sequence::create(_time, to, NULL));

                    

                    stars[begin_i][j]->setOpacity(255);

                    stars[begin_i][j] = nullptr;

                }

            }

            else{

                continue;

            }

        } // for

    }  // for

    

   //    produceStars();

}


// 产生新的星星

void StarArry::produceStars()

{

    srand((unsigned)time(0));

    int i, j;

    

    for(j=0; j<COL_NUM; j++)

    {

        for(i=ROW_NUM-1; i>=0; i--)

        {

            if(stars[i][j] )

            {

                continue;

            }

            

            if(stars[i][j] == nullptr )

            {

                //  首先找出    空的星星个数

                int up = i;

                int dis = 0;

                while(stars[up][j] == nullptr)

                {

                    dis++;    // 空的个数

                    up--;

                    if(up<0)

                    {   break;   }

                }


                //***************

                int k =  s_count[j];  //读取 "该列" 移动星星个数

                while( i>=0 ) // =0  -1

                {

                 int _color = rand()%5;

                    Star *_s = Star::createStar(_color);

           

                    stars[i][j] = _s;

                    _s->setIndexXY(i, j);

                    _s->setPosition(getPositionByIndex(i, j)+Point(0, Star::STAR_HEIGHT*dis));//100

                    

                    DelayTime *_time = DelayTime::create(0.05*k);

                    k++;

                    _s->setOpacity(0);

                    FadeTo *_fadeTo =  FadeTo::create(DROPTIME, 255); //bug

                    MoveTo *_to = MoveTo::create( DROPTIME, getPositionByIndex(i, j));

                    Spawn *_spawn = Spawn::create(_fadeTo, _to, NULL);

           

                    CallFunc *_fun = CallFunc::create([this]()

                    {

                        if(this->isEnd() == true)

                        {

                            UserDefault::getInstance()->setBoolForKey("IsEnd", true);

                            UserDefault::getInstance()->setBoolForKey("DeadLayer", true);

                        }

//                        _s->setOpacity(255);     // 解决bug 出现半透明现象

                     });

                    

                    _s->runAction(Sequence::create( _time, _spawn, _fun, NULL));

                    i--;

                    addChild(_s);  //添加到矩阵中

        

                }

            }  //if

         

        }  // for

    } //for

    

    

}


void StarArry::produceBack(Star *)

{

    

}


void StarArry::empty(cocos2d::Ref *obj, Control::EventType)

{

    

}



void StarArry::cleanSameRowAndCol(int _row, int _col)

{

    int i, j;

    

    // 消除同一行的星星

    for(j=0; j<COL_NUM; j++)

    {

        removeStar(_row,j);

    }

    //adjustMatrix();

    for(i=0; i<ROW_NUM; i++)

    {

        removeStar(i,_col);

    }

    

     adjustMatrix();

     produceStars();

}


// 消除同颜色的星星

void StarArry::cleanSameColor(int _color)

{

    int i, j;

    

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            if(stars[i][j] && stars[i][j]->getColor() == _color)

            {

                removeStar(i,j);

            } // if

            else

                continue;

        }

    }

    

     adjustMatrix();

  //   this->scheduleOnce(schedule_selector(StarArry::intervalProduce), 0.50f);

     produceStars();

}


void StarArry::cleanEightStar(const int i, const int j)

{

    removeStar(i, j);//本身

    removeStar(i-1, j-1);//左上

    removeStar(i, j-1);//左

    removeStar(i, j-2);//左2

    removeStar(i+1, j-1);//左下

    removeStar(i+1, j);//下

    removeStar(i+2, j);//下2

    removeStar(i+1, j+1);//右下

    removeStar(i, j+1);//右

    removeStar(i, j+2);//右2

    removeStar(i-1, j+1);//右上

    removeStar(i-1, j);//上

    removeStar(i-2, j);//上2

    int _i = i, _j = j;

 

//    while(_i>=0 && _j>=0)    // 左上

//    {

//        _i--;

//        _j--;

      removeStar(_i,_j);

//        if(stars[_i][_j])

//                    {

//                        stars[_i][_j]->removeFromParentAndCleanup(true);

//                        stars[_i][_j] = nullptr;

//                    }

//    }

//

//    _i = i, _j = j;

//        CCLOG("touch  index :  i=%d,j=%d", _i, _j);

//    while (_i <ROW_NUM && _j<COL_NUM)   // 右下

//    {

//        

//        _i++;

//        _j++;

//        if(stars[_i][_j])

//                                {

//                                    stars[_i][_j]->removeFromParentAndCleanup(true);

//                                    stars[_i][_j] = nullptr;

//                                }

//    }

//

//    _i = i, _j = j;

//    while ( _i>=0 && _j<COL_NUM)   // 右上

//    {

//        _i--;

//        _j++;

//        if(stars[_i][_j])

//        {

//            stars[_i][_j]->removeFromParentAndCleanup(true);

//            stars[_i][_j] = nullptr;

//        }

//    }

//    

//    _i = i, _j = j;

//    while (_i < ROW_NUM && _j>=0)   // 左下

//    {

//        _i++;

//        _j--;

//        if(stars[_i][_j])

//        {

//            stars[_i][_j]->removeFromParentAndCleanup(true);

//            stars[_i][_j] = nullptr;

//        }

//    }

//    

    

    adjustMatrix();

    produceStars();

}

 


void StarArry::clearStarOneByOne()  // 为啥出来红线

{

    int i,j;

 

    for(i=0; i<ROW_NUM; i++)   //安列来消除 死局星星

    {

        for(j=0; j<COL_NUM; j++)

        {

            removeStar(i,j);

        }

    } // for

    

 

}


// 单独写个函数

void StarArry::removeStar(int i,int j)

{

    if (i >=0 && i < ROW_NUM && j >= 0 && j < COL_NUM && stars[i][j])

    {

        showStarParticleEffect(stars[i][j]->getColor(), stars[i][j]->getPosition(), this);

        

        stars[i][j]->removeFromParentAndCleanup(true);

        stars[i][j] = nullptr;

    }

}


// 判断是否死局

bool StarArry::isEnd()

{

    std::vector<Star *> deadEnd;

    

    int i,j, k;

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

          

            for(k=0; k< deadEnd.size(); k++)

            {

                if(deadEnd.at(k)->isSelect() == true)

                deadEnd.at(k)->setSelect(false);   // 回复标记 false

            }

            

            deadEnd.clear();

    std::deque<Star *>  _travelList;

    _travelList.push_back(stars[i][j]);

    deque<Star*>::iterator it;

    

    for(  it= _travelList.begin();    it != _travelList.end(); ++it)

    {

        Star *_star = *it;   //返回引用值

        Star *_linkStar = nullptr;

        

        int _indexX = _star->getIndexX();

        int _indexY = _star->getIndexY();

        

        //  上

        if(_indexX-1 >=0 && (_linkStar = stars[_indexX-1][_indexY])!= NULL )

        {

            if(_linkStar->isSelect()== false && _linkStar->getColor() == _star->getColor() )

            {

                _travelList.push_back(stars[_indexX-1][_indexY]);

            }

        }

        // 下

        if(_indexX+1 <= ROW_NUM-1 && (_linkStar = stars[_indexX+1][_indexY])!= NULL)

        {

            if(_linkStar->isSelect() == false && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX+1][_indexY]);

            }

        }

        

        //  左   判断是存在

        if(_indexY-1 >=0 && (_linkStar=stars[_indexX][_indexY-1]))

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY-1]);

            }

        }

        // 右

        if(_indexY+1 <= COL_NUM-1 && (_linkStar=stars[_indexX][_indexY+1])!= nullptr )

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY+1]);

            }

        }

        

        if( !_star->isSelect())

        {

            _star->setSelect(true);  // 标记已搜索过

            deadEnd.push_back(_star);

        }

        

        if(deadEnd.size()>=3)

        {

            for(k=0; k< deadEnd.size(); k++)

            {

                if(deadEnd.at(k)->isSelect() == true)

                deadEnd.at(k)->setSelect(false);   // 回复标记 false

            }

            

            return  false;

        }

    } // 最里层 for

            

        }

    }


    // 如果小于3个

    for(k=0; k< deadEnd.size(); k++)

    {

        if(deadEnd.at(k)->isSelect() == true)

        deadEnd.at(k)->setSelect(false);   // 回复标记 false

    }


    return true;

}


int  StarArry::getLeftStar()

{

    int i,j, count = 0;

    

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            if(stars[i][j])

            {

                count++;

            }

            else

            {

                continue;

            } //if

        }

    } // for

   

    return count;

}


/*

 

 stars[i][j] = _s;

 _s->setIndexXY(i, j);

 _s->setPosition(getPositionByIndex(i, j)+Point(0, 100));

 MoveTo *_to = MoveTo::create(0.50f, getPositionByIndex(i, j));

 CallFunc *_fun = CallFunc::create([this]()

 {

 if(this->isEnd() == true)

 {

 UserDefault::getInstance()->setBoolForKey("IsEnd", true);

 UserDefault::getInstance()->setBoolForKey("DeadLayer", true);

 

 }

 });

 

 _s->runAction(Sequence::create(_to, _fun, NULL));

 i--;

 addChild(_s);  //添加到矩阵中


 

 */


#ifndef __popStar__starSprite__

#define __popStar__starSprite__


#include <stdio.h>

#include "cocos2d.h"


USING_NS_CC;


class  Star : public Sprite

{

public:

    static Star*  createStar(int color);

    void init(int color);

    

  

    // 获得星星颜色  死局

    int  getColor() { return  m_color; }

    

    bool isSelect() { return m_select; }

    // 把星星设为已选

    void setSelect(bool select) {   m_select = select ; }

     // 获取坐标索引

    int getIndexX() { return m_indexX; }  // 隐式定义内联函数

    inline int getIndexY() { return m_indexY; }

    

    void setIndexXY(int x, int y) {   m_indexX = x; m_indexY = y; }

    

public:

    static const int STAR_WIDTH  = 80;   //单个 星星宽度

    static const int STAR_HEIGHT = 80;   //单个 星星高度

    

private:

      std::string setColor(int color);

    

private:

    bool m_select;

    int m_color;   //m_colore

    int m_indexX;

    int m_indexY;

    int m_moveDelay;

    

};



#endif /* defined(__popStar__starSprite__) */

//

//  starSprite.cpp

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#include "data.h"

#include "starSprite.h"


Star* Star::createStar(int color)

{

    Star *star = new Star();

    

    if(star && star->initWithFile(star->setColor(color)))

    {

        star->init(color);

        star->autorelease();

        return  star;

    }

    else

    {

        CC_SAFE_DELETE(star);

        star = nullptr;        //

        return  nullptr;

    }

}


void Star::init(int color)

{

    m_select = false;

    m_color = color;


}


std::string Star::setColor(int color)

{

    switch (color)

    {

        case  GREEN:  return "green.png";

        case  BLUE:   return "blue.png";

        case  YELLOW: return "orange.png";

        case  RED:    return "red.png";

        case  PURPLE: return "purple.png";

            

        default:

            CC_ASSERT(0);  // false

    }

}    

—————————————————————————————————————————————

//

//  starArry.h

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#ifndef __popStar__starArry__

#define __popStar__starArry__


#include <stdio.h>

#include <string.h>

#include <deque>

#include <vector>

#include <algorithm>


#include "starSprite.h"

#include "Publics.h"



using namespace std;


// 商店的高度

#define   STOREFEIHT  100

#define   DROPTIME     0.3   // 调整时单个星星下落时间


class StarArry  : public Sprite   // ?? scene()

{

public:

    static StarArry* createMatrix();

    bool init();

    void onTouch(Point& _pos);


    void empty(Ref* obj, Control::EventType);

    void produceBack(Star *);

public:

   

    void initMatrix();

    

    static const int ROW_NUM = 8;

    static const int COL_NUM = 8;

//private:

//public的全局可见,private类内可见  private函数一般是用来给public函数调中A.f1();

    

    void getSelectedList(Star *s) ;  // 获取相同颜色的星星

    void deleteSelectedList();      // 删除数组中同颜色的星星

    void adjustMatrix();           // 消除后,调整二维数组中的内容 即: 调整位置

    void produceStars();           // 消除后产生新的星星

    bool isEnd();                  //判断是否死局

    void clearStarOneByOne();      // 一个接一个的删除星星

    void removeStar(int i,int j);

    int  getLeftStar();

    

    //响应商店函数

    void cleanSameRowAndCol(int _row, int _col);  // 消除同行同列的星星

    void cleanSameColor(int _color);              //  消除相同颜色的星星

    void cleanEightStar(int _i, int _j);                        //  消除八字形

    

    // 通过坐标获取 星星

    Star *getStarByTouchPoint(Point &pos);

    // 通过index获取坐标

    Point getPositionByIndex(int i, int j);

    

private:

    Size  m_size;

    bool  m_overTimer;  // 标志超时

   

    Star* stars[ROW_NUM][COL_NUM];  // 二维数组 来存放星星

    std::vector<Star *> selectedList;   // 用于记录相同颜色的星星

};




#endif /* defined(__popStar__starArry__) */



//

//  starArry.cpp

//  popStar

//

//  Created by 大脚d on 14-12-8.

//

//


#include <time.h>

#include "data.h"

#include "starSprite.h"

#include "starArry.h"

#include "levelShared.h"

#include "jsonRead.h"

#include "starParticle.h"



 StarArry* StarArry::createMatrix()

{

    StarArry *starArry = new StarArry();

  

    if( starArry )

    {

       starArry->autorelease();

       starArry->init();

       return starArry;

    }

    else

    {

        CC_SAFE_DELETE(starArry);

        starArry = nullptr;

        return nullptr;

    }

}


static int oneScore = 0;  // 消除星星得分数

bool StarArry::init()

{

    if( !Sprite::init())

    {

        return false;

    }

    

    m_size = Director::getInstance()->getWinSize();

 

    initMatrix();   //创建星星矩阵

    


    LevelFeature::getInstance()->setScore(0);

    return true;

}

 

void StarArry::initMatrix()

{

    srand(unsigned(time(0)));

    

    int i, j;

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            int _color = rand()%5; // 0~4  随机生成几种颜色

            CCLOG("----: %d", _color);

            Star *s = Star::createStar(_color);

            stars[i][j] = s;

            s->setIndexXY(i, j);   // 为后面 删除 查找用

            s->setPosition(getPositionByIndex(i, j) + Point(0, 100));

           

            // 开始的 运动

            MoveBy *by = MoveBy::create(0.40f,  Point(0, -100));

            s->runAction(by);

            

            addChild(stars[i][j]);

        } // for

    }// for

    

}


// 通过坐标获取 星星

Star * StarArry::getStarByTouchPoint(Point &pos)  // 没问题这个

{   static int a=0;

     CCLOG(" - - --  - touch times: %d ", a++);

    int j = pos.x/Star::STAR_WIDTH; // 列索引

    

    int t = (pos.y - STOREFEIHT)/Star::STAR_HEIGHT;

    int i = ROW_NUM - 1 - t;

    

    // 如果 不存在 或 未点击到星星 返回空

    if(i >=0 && i< ROW_NUM && j>=0 && j< COL_NUM && stars[i][j] != nullptr)

    {

        return stars[i][j];

    }

    else

    {

        return  nullptr;

    }

}


// 通过index获取坐标

Point StarArry::getPositionByIndex(int i, int j)

{

    float _x = j*Star::STAR_WIDTH + Star::STAR_WIDTH/2;

    float _y = (COL_NUM - i)*Star::STAR_HEIGHT - Star::STAR_HEIGHT/2 + STOREFEIHT;

    

    return  Point(_x, _y);

}


void StarArry::onTouch(Point &_pos)

{

    

    Star*_s = getStarByTouchPoint(_pos);

 

    if(_s)

    {

        getSelectedList(_s);

        

        deleteSelectedList();

    }

}


// 搜索相同颜色的 星星

void StarArry::getSelectedList(Star *s)

{

    selectedList.clear();

    

    std::deque<Star *>  _travelList;

    _travelList.push_back(s);

    deque<Star*>::iterator it;

    

    for(  it= _travelList.begin();    it != _travelList.end(); ++it)

   // for(auto &t : _travelList)    //  通过下标来 搜索 上下左右

    {

        Star *_star = *it;   //返回引用值

        Star *_linkStar = nullptr;

        

        int _indexX = _star->getIndexX();

        int _indexY = _star->getIndexY();

      

        //  上

        if(_indexX-1 >=0 && (_linkStar = stars[_indexX-1][_indexY])!= NULL )

        {

            if(_linkStar->isSelect()== false && _linkStar->getColor() == _star->getColor() )

            {

                _travelList.push_back(stars[_indexX-1][_indexY]);

            }

        }

        // 下

        if(_indexX+1 <= ROW_NUM-1 && (_linkStar = stars[_indexX+1][_indexY])!= NULL)

        {

            if(_linkStar->isSelect() == false && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX+1][_indexY]);

            }

        }

        

        //  左   判断是存在

        if(_indexY-1 >=0 && (_linkStar=stars[_indexX][_indexY-1]))

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY-1]);

            }

        }

        // 右

        if(_indexY+1 <= COL_NUM-1 && (_linkStar=stars[_indexX][_indexY+1])!= nullptr )

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY+1]);

              //  _linkStar->setSelect(true); //不用标记;目前只是发现同色 但自身为搜索

            }

        }

        

        if( !_star->isSelect())

        {

            _star->setSelect(true);  // 标记已搜索过

            selectedList.push_back(_star);

        }

        

//        _travelList.pop_front();

//        it =  _travelList.begin(); // 取出第一个

    } // for

    

//    selectedList.clear();

     CCLOG(" -- - getSelectedList  - -- ");

}


// 消除矩阵中 同颜色的星星

void StarArry::deleteSelectedList()

{

//    oneScore = 0;  // 每次清空

    int _score = 0;

    

    if(selectedList.size() <= 2)       // 如果没有搜到

    {

        selectedList.at(0)->setSelect(false);

        if(selectedList.size() == 2)    // 如果2个颜色相同

        {

            selectedList.at(1)->setSelect(false);

        }

        return ;

    }

    

    // 若果存在同颜色的   就消除 同色的星星

    for(auto it = selectedList.begin(); it != selectedList.end(); it++)

    {

        Star* _star = *it;        // 下标删除

        removeStar(_star->getIndexX(),_star->getIndexY());

        

        _score = _score + 20;  //每消除一个的20分

    }

    

    // 放在for外面 优化效率 减少对文件操作    判断:应为存储分的模式不同

    if(UserDefault::getInstance()->getBoolForKey("IsForeverModel", false) == true)

    {

        // 无限模式

        int _scoreForever = UserDefault::getInstance()->getIntegerForKey("foreverScore");

        // 之前消除的得分 + 本次消除得分

        UserDefault::getInstance()->setIntegerForKey("foreverScore", _score+_scoreForever);

    }

    else

    {   // 关卡模式

        LevelFeature::getInstance()->setScore(LevelFeature::getInstance()->getScore() + _score);

    }

    

    selectedList.clear();

    CCLOG(" -- - getSelectedList  - - @ - ");

    

    adjustMatrix();  //如果执行了 删除操作;就调整

    

    produceStars();   // 产生星星

}


 static int  s_count[StarArry::ROW_NUM];

// 调整主要改变 索引

void StarArry::adjustMatrix()

{

    memset(s_count, 0, sizeof(s_count));

    

  

    //*************************************************************

    for(int i = ROW_NUM-1;i>=0;i--)

    {

         for(int j = 0;j <= COL_NUM-1; j++){

            if(stars[i][j] == nullptr)

            {

                int up = i;

                int dis = 0;

                while(stars[up][j] == nullptr)

                {

                    dis++;    // 空的个数

                    up--;

                    if(up<0)

                       {   break;   }

                }

                

                if(s_count[j] == 0 )     // 记录 "该列" 要移动星星个数

                {

                    int pp = s_count[j] = i-dis+1;

                }

          //   int pp = s_count[j] = i-dis+1;    //记录 "该列" 要移动星星个数

                int k=0;

                for(int begin_i = i - dis;  begin_i >= 0;  begin_i--) //循环次数为要移动星星个数

                {

                    if(stars[begin_i][j] == nullptr)  // 为空 不用移动

                        continue;

                

                    //              目标位置                     原始位置

                    Star* s = stars[begin_i + dis][j] = stars[begin_i][j];

                    s->setIndexXY(begin_i + dis,j);   // 不能少  删除查找iyong

//                    s->setIndexXY(<#int x#>, <#int y#>)

               //     s->setDesPosition(getPositionByIndex(begin_i + dis,j));

                    Point _pos = getPositionByIndex(begin_i+dis, j);

                    

                    DelayTime* _time = DelayTime::create(0.05*k); // 延迟时间

                    k++;

                    MoveTo *to = MoveTo::create(DROPTIME, _pos);

                    stars[begin_i][j]->stopAllActions();

                    stars[begin_i][j]->runAction(Sequence::create(_time, to, NULL));

                    

                    stars[begin_i][j]->setOpacity(255);

                    stars[begin_i][j] = nullptr;

                }

            }

            else{

                continue;

            }

        } // for

    }  // for

    

   //    produceStars();

}


// 产生新的星星

void StarArry::produceStars()

{

    srand((unsigned)time(0));

    int i, j;

    

    for(j=0; j<COL_NUM; j++)

    {

        for(i=ROW_NUM-1; i>=0; i--)

        {

            if(stars[i][j] )

            {

                continue;

            }

            

            if(stars[i][j] == nullptr )

            {

                //  首先找出    空的星星个数

                int up = i;

                int dis = 0;

                while(stars[up][j] == nullptr)

                {

                    dis++;    // 空的个数

                    up--;

                    if(up<0)

                    {   break;   }

                }


                //***************

                int k =  s_count[j];  //读取 "该列" 移动星星个数

                while( i>=0 ) // =0  -1

                {

                 int _color = rand()%5;

                    Star *_s = Star::createStar(_color);

           

                    stars[i][j] = _s;

                    _s->setIndexXY(i, j);

                    _s->setPosition(getPositionByIndex(i, j)+Point(0, Star::STAR_HEIGHT*dis));//100

                    

                    DelayTime *_time = DelayTime::create(0.05*k);

                    k++;

                    _s->setOpacity(0);

                    FadeTo *_fadeTo =  FadeTo::create(DROPTIME, 255); //bug

                    MoveTo *_to = MoveTo::create( DROPTIME, getPositionByIndex(i, j));

                    Spawn *_spawn = Spawn::create(_fadeTo, _to, NULL);

           

                    CallFunc *_fun = CallFunc::create([this]()

                    {

                        if(this->isEnd() == true)

                        {

                            UserDefault::getInstance()->setBoolForKey("IsEnd", true);

                            UserDefault::getInstance()->setBoolForKey("DeadLayer", true);

                        }

//                        _s->setOpacity(255);     // 解决bug 出现半透明现象

                     });

                    

                    _s->runAction(Sequence::create( _time, _spawn, _fun, NULL));

                    i--;

                    addChild(_s);  //添加到矩阵中

        

                }

            }  //if

         

        }  // for

    } //for

    

    

}


void StarArry::produceBack(Star *)

{

    

}


void StarArry::empty(cocos2d::Ref *obj, Control::EventType)

{

    

}



void StarArry::cleanSameRowAndCol(int _row, int _col)

{

    int i, j;

    

    // 消除同一行的星星

    for(j=0; j<COL_NUM; j++)

    {

        removeStar(_row,j);

    }

    //adjustMatrix();

    for(i=0; i<ROW_NUM; i++)

    {

        removeStar(i,_col);

    }

    

     adjustMatrix();

     produceStars();

}


// 消除同颜色的星星

void StarArry::cleanSameColor(int _color)

{

    int i, j;

    

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            if(stars[i][j] && stars[i][j]->getColor() == _color)

            {

                removeStar(i,j);

            } // if

            else

                continue;

        }

    }

    

     adjustMatrix();

  //   this->scheduleOnce(schedule_selector(StarArry::intervalProduce), 0.50f);

     produceStars();

}


void StarArry::cleanEightStar(const int i, const int j)

{

    removeStar(i, j);//本身

    removeStar(i-1, j-1);//左上

    removeStar(i, j-1);//左

    removeStar(i, j-2);//左2

    removeStar(i+1, j-1);//左下

    removeStar(i+1, j);//下

    removeStar(i+2, j);//下2

    removeStar(i+1, j+1);//右下

    removeStar(i, j+1);//右

    removeStar(i, j+2);//右2

    removeStar(i-1, j+1);//右上

    removeStar(i-1, j);//上

    removeStar(i-2, j);//上2

    int _i = i, _j = j;

 

//    while(_i>=0 && _j>=0)    // 左上

//    {

//        _i--;

//        _j--;

      removeStar(_i,_j);

//        if(stars[_i][_j])

//                    {

//                        stars[_i][_j]->removeFromParentAndCleanup(true);

//                        stars[_i][_j] = nullptr;

//                    }

//    }

//

//    _i = i, _j = j;

//        CCLOG("touch  index :  i=%d,j=%d", _i, _j);

//    while (_i <ROW_NUM && _j<COL_NUM)   // 右下

//    {

//        

//        _i++;

//        _j++;

//        if(stars[_i][_j])

//                                {

//                                    stars[_i][_j]->removeFromParentAndCleanup(true);

//                                    stars[_i][_j] = nullptr;

//                                }

//    }

//

//    _i = i, _j = j;

//    while ( _i>=0 && _j<COL_NUM)   // 右上

//    {

//        _i--;

//        _j++;

//        if(stars[_i][_j])

//        {

//            stars[_i][_j]->removeFromParentAndCleanup(true);

//            stars[_i][_j] = nullptr;

//        }

//    }

//    

//    _i = i, _j = j;

//    while (_i < ROW_NUM && _j>=0)   // 左下

//    {

//        _i++;

//        _j--;

//        if(stars[_i][_j])

//        {

//            stars[_i][_j]->removeFromParentAndCleanup(true);

//            stars[_i][_j] = nullptr;

//        }

//    }

//    

    

    adjustMatrix();

    produceStars();

}

 


void StarArry::clearStarOneByOne()  // 为啥出来红线

{

    int i,j;

 

    for(i=0; i<ROW_NUM; i++)   //安列来消除 死局星星

    {

        for(j=0; j<COL_NUM; j++)

        {

            removeStar(i,j);

        }

    } // for

    

 

}


// 单独写个函数

void StarArry::removeStar(int i,int j)

{

    if (i >=0 && i < ROW_NUM && j >= 0 && j < COL_NUM && stars[i][j])

    {

        showStarParticleEffect(stars[i][j]->getColor(), stars[i][j]->getPosition(), this);

        

        stars[i][j]->removeFromParentAndCleanup(true);

        stars[i][j] = nullptr;

    }

}


// 判断是否死局

bool StarArry::isEnd()

{

    std::vector<Star *> deadEnd;

    

    int i,j, k;

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

          

            for(k=0; k< deadEnd.size(); k++)

            {

                if(deadEnd.at(k)->isSelect() == true)

                deadEnd.at(k)->setSelect(false);   // 回复标记 false

            }

            

            deadEnd.clear();

    std::deque<Star *>  _travelList;

    _travelList.push_back(stars[i][j]);

    deque<Star*>::iterator it;

    

    for(  it= _travelList.begin();    it != _travelList.end(); ++it)

    {

        Star *_star = *it;   //返回引用值

        Star *_linkStar = nullptr;

        

        int _indexX = _star->getIndexX();

        int _indexY = _star->getIndexY();

        

        //  上

        if(_indexX-1 >=0 && (_linkStar = stars[_indexX-1][_indexY])!= NULL )

        {

            if(_linkStar->isSelect()== false && _linkStar->getColor() == _star->getColor() )

            {

                _travelList.push_back(stars[_indexX-1][_indexY]);

            }

        }

        // 下

        if(_indexX+1 <= ROW_NUM-1 && (_linkStar = stars[_indexX+1][_indexY])!= NULL)

        {

            if(_linkStar->isSelect() == false && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX+1][_indexY]);

            }

        }

        

        //  左   判断是存在

        if(_indexY-1 >=0 && (_linkStar=stars[_indexX][_indexY-1]))

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY-1]);

            }

        }

        // 右

        if(_indexY+1 <= COL_NUM-1 && (_linkStar=stars[_indexX][_indexY+1])!= nullptr )

        {

            if(!_linkStar->isSelect() && _linkStar->getColor() == _star->getColor())

            {

                _travelList.push_back(stars[_indexX][_indexY+1]);

            }

        }

        

        if( !_star->isSelect())

        {

            _star->setSelect(true);  // 标记已搜索过

            deadEnd.push_back(_star);

        }

        

        if(deadEnd.size()>=3)

        {

            for(k=0; k< deadEnd.size(); k++)

            {

                if(deadEnd.at(k)->isSelect() == true)

                deadEnd.at(k)->setSelect(false);   // 回复标记 false

            }

            

            return  false;

        }

    } // 最里层 for

            

        }

    }


    // 如果小于3个

    for(k=0; k< deadEnd.size(); k++)

    {

        if(deadEnd.at(k)->isSelect() == true)

        deadEnd.at(k)->setSelect(false);   // 回复标记 false

    }


    return true;

}


int  StarArry::getLeftStar()

{

    int i,j, count = 0;

    

    for(i=0; i<ROW_NUM; i++)

    {

        for(j=0; j<COL_NUM; j++)

        {

            if(stars[i][j])

            {

                count++;

            }

            else

            {

                continue;

            } //if

        }

    } // for

   

    return count;

}


/*

 

 stars[i][j] = _s;

 _s->setIndexXY(i, j);

 _s->setPosition(getPositionByIndex(i, j)+Point(0, 100));

 MoveTo *_to = MoveTo::create(0.50f, getPositionByIndex(i, j));

 CallFunc *_fun = CallFunc::create([this]()

 {

 if(this->isEnd() == true)

 {

 UserDefault::getInstance()->setBoolForKey("IsEnd", true);

 UserDefault::getInstance()->setBoolForKey("DeadLayer", true);

 

 }

 });

 

 _s->runAction(Sequence::create(_to, _fun, NULL));

 i--;

 addChild(_s);  //添加到矩阵中


 

 */

----------------------------------------------------------------老师Demo

// //  GameStart.cpp //  Chapt16-TestPlaneGame // //  Created by ibokan on 13-11-7. // // #include "GameStart.h" #include "GameMap.h" #include "Bullet.h" #include "SimpleAudioEngine.h" #include "Enemy.h" #include <time.h> using namespace cocos2d; using namespace CocosDenshion; static GameStart* my = NULL; GameStart* GameStart::shared() {      if (my != NULL)      {          return my;      }      else          return NULL; } CCScene* GameStart::scene() {      CCScene* scene = CCScene::create();      GameStart* layer = GameStart::create();      scene->addChild(layer);      return scene; } bool GameStart::init() {      if (!CCLayer::init())      {          return false ;      }            // 设置随机数种子      srand ( time (NULL));            SimpleAudioEngine::sharedEngine()->playBackgroundMusic( "gameMusic.mp3" );            my = this ;            GameMap* map = GameMap::create( "map.png" );      addChild(map);            HeroPlayer* player = HeroPlayer::createPlayer( "player.png" );      addChild(player,20,tag_player);            // 敌人数组      enemies = CCArray::create();      CC_SAFE_RETAIN(enemies);            this ->schedule(schedule_selector(GameStart::autoCreateBullet), 0.3);      this ->schedule(schedule_selector(GameStart::autoCreateEnemy), 1.0f);            return true ; } void GameStart::autoCreateEnemy() {      int count = CCRANDOM_0_1()*10;      for ( int i = 0; i < count; i++)      {          int randomType = rand ()%3;                    const char * name = "enemy_bug.png" ;                    switch (randomType)          {              case 0:              {                  name = "enemy_bug.png" ;              }                  break ;              case 1:              {                  name = "enemy_duck.png" ;              }                  break ;              case 2:              {                  name = "enemy_pig.png" ;              }                  break ;                                default :                  break ;          // switch()                              int type = rand ()%2;          Enemy* enemy = Enemy::createEnemy(name, type);          enemies->addObject(enemy);          addChild(enemy);                } } void GameStart::autoCreateBullet() {      HeroPlayer* player = this ->getHeroPlayer();      Bullet* bullet = Bullet::create(ccpAdd(player->getPosition(), ccp(0, player->getContentSize().height/2)), 180.0, "p_bullet.png" );      addChild(bullet);            SimpleAudioEngine::sharedEngine()->playEffect( "effect_bullet.mp3" ); } HeroPlayer* GameStart::getHeroPlayer() {      return (HeroPlayer*) this ->getChildByTag(tag_player); } void GameStart::gameLost() {       } void GameStart::gameWin() {       } GameStart::~GameStart() {      CC_SAFE_RELEASE_NULL(enemies); }
// //  Bullet.cpp //  Chapt16-TestPlaneGame // //  Created by ibokan on 13-11-7. // // #include "Bullet.h" #include "GameStart.h" #include "Enemy.h" #include "SimpleAudioEngine.h" using namespace cocos2d; using namespace CocosDenshion; Bullet* Bullet::create(cocos2d::CCPoint position, float speed, const char *fileName) {      Bullet* bullet = new Bullet();      if (bullet && bullet->initWithFile(fileName))      {          bullet->autorelease();          bullet->init(position, speed);          return bullet;      }      else      {          CC_SAFE_DELETE(bullet);          return NULL;      } } void Bullet::init(cocos2d::CCPoint position, float speed) {      this ->setPosition(position);      m_speed = speed;      this ->scheduleUpdate();            this ->move(); } void Bullet::move() {      CCSize size = CCDirector::sharedDirector()->getWinSize();      float h = size.height - this ->getPosition().y;      CCMoveBy* move = CCMoveBy::create(h / m_speed, ccp(0, h));      CCCallFuncN* call = CCCallFuncN::create( this , callfuncN_selector(Bullet::removeBullet));      CCSequence* sequence = CCSequence::create(move,call);      this ->runAction(sequence); } void Bullet::removeBullet() {      this ->removeFromParentAndCleanup( true );  关闭定时器 -- 好像是在这调用 ??? } void Bullet::update( float delta) {      CCArray* enemies = GameStart::shared()->enemies;      CCObject* enemy = NULL;      CCARRAY_FOREACH(enemies, enemy)      {          Enemy* ene = (Enemy*)enemy;                    if (ene->boundingBox().intersectsRect( this ->boundingBox()))          {              // 击中了敌人              SimpleAudioEngine::sharedEngine()->playEffect( "effect_boom.mp3" );                            // 添加粒子效果              CCParticleSystemQuad* particle = CCParticleSystemQuad::create( "particle_boom.plist" );              particle->setPosition(ene->getPosition());              particle->setAutoRemoveOnFinish( true );              GameStart::shared()->addChild(particle);                            HeroPlayer* player = GameStart::shared()->getHeroPlayer();              player->addScore(ene->m_scoreValue);              player->addKillCount(1);                            enemies->removeObject(ene);              ene->removeFromParentAndCleanup( true );                        }      } } //  合适调用:该节点从父节点中移除是  -- 退出场景是 void Bullet::onExit() {      this ->CCSprite::onExit();     // 一定要调用父的 -- OR bug      this ->unscheduleUpdate();     //关闭定时器 --- 耗费CPU时间 }
// //  HeroPlayer.cpp //  Chapt16-TestPlaneGame // //  Created by ibokan on 13-11-8. // // #include "HeroPlayer.h" #include "GameStart.h" using namespace cocos2d; using namespace std; HeroPlayer* HeroPlayer::createPlayer( const char *fileName) {      HeroPlayer* player = new HeroPlayer();      if (player && player->initWithFile(fileName))      {          player->autorelease();          player->initPlayer();          return player;      }      else      {          CC_SAFE_DELETE(player);          return NULL;      } } void HeroPlayer::initPlayer() {      CCSize size = CCDirector::sharedDirector()->getWinSize();            this ->setPosition(ccp(size.width/2, this ->getContentSize().height/2+5));      // 初始化基本数据      m_hpMax = 3;      m_hp = 3;      m_score = 0;      m_killCount = 0;      m_isStrong = false ;      isDead = false ;                  // 初始化三滴血      for ( int i = 0; i < 3; i++)      {          CCSprite* spriteHp = CCSprite::create( "icon_hp.png" );          spriteHp->setPosition(ccp(size.width - spriteHp->getContentSize().width*i-20, spriteHp->getContentSize().height/2+5));          switch (i) {              case 0:                  spriteHp->setTag(tag_playerHp1);                  break ;              case 1:                  spriteHp->setTag(tag_playerHp2);                  break ;              case 2:                  spriteHp->setTag(tag_playerHp3);                  break ;                                default :                  break ;          }                    GameStart::shared()->addChild(spriteHp,20);      }            // 得分label      CCLabelTTF* label = CCLabelTTF::create( "分数:" , "Marker Felt" , 25);      label->setColor(ccWHITE);      label->setPosition(ccp(30, size.height-20));      GameStart::shared()->addChild(label, 20);            string scoreStr = ConvertToString(m_score);      CCLabelTTF* labelScore = CCLabelTTF::create(scoreStr.c_str(), "Marker Felt" , 25);      labelScore->setPosition(ccp(110, size.height-20));      labelScore->setColor(ccc3(255,255,0));      GameStart::shared()->addChild(labelScore,20,tag_scoreLabel);            // 杀敌label      CCLabelTTF* labelC = CCLabelTTF::create( "得分:" , "Marker Felt" , 25);      labelC->setPosition(ccp(30, size.height-50));      GameStart::shared()->addChild(labelC,20);            string killStr = ConvertToString(m_killCount);      killStr += "/100" ;      CCLabelTTF* labelKill = CCLabelTTF::create(killStr.c_str(), "Marker Felt" , 25);      labelKill->setPosition(ccp(110, size.height-50));      labelKill->setColor(ccc3(255, 255, 0));      GameStart::shared()->addChild(labelKill,20,tag_killCountLabel);       } void HeroPlayer::addScore( int value) {      m_score += value;      string addScore = ConvertToString(m_score); //    addScore += "/100";      CCLabelTTF* label = (CCLabelTTF*)GameStart::shared()->getChildByTag(tag_scoreLabel);      label->setString(addScore.c_str());       } void HeroPlayer::addKillCount( int value) {      m_killCount += value;      string killCountStr = ConvertToString(m_killCount);      killCountStr += "/100" ;      CCLabelTTF* label = (CCLabelTTF*)GameStart::shared()->getChildByTag(tag_killCountLabel);      label->setString(killCountStr.c_str());            if (m_killCount >= 100)      {          // 最高分本地化存储          /*           * 回去自行研究CCUserDefault           */                    // 游戏胜利          GameStart::shared()->gameWin();      } } void HeroPlayer::downHp() {      if (m_isStrong)      {          return ;      }            m_hp -= 1;      if (m_hp <= 0)      {          isDead = true ;                    // 英雄挂掉后,读取本地存储的最高分,如果分数更高,将当前得分写入本地          //CCUserDefault::sharedUserDefault()->setStringForKey(<#const char *pKey#>, <#const std::string &value#>)          //CCUserDefault::sharedUserDefault()->getStringForKey(<#const char *pKey#>, <#const std::string &defaultValue#>)                    GameStart::shared()->gameLost();                }      else      {          switch (m_hp) {              case 2:                  GameStart::shared()->removeChildByTag(tag_playerHp3);                  break ;              case 1:                  GameStart::shared()->removeChildByTag(tag_playerHp2);                  break ;                                default :                  break ;          }                    // 设置主角无敌          m_isStrong = true ;                    CCBlink* blink = CCBlink::create(2, 20);          CCCallFunc* func = CCCallFunc::create( this , callfunc_selector(HeroPlayer::setPlayerUnStrong));          CCSequence* sequence = CCSequence::create(blink,func);          this ->runAction(sequence);                } } void HeroPlayer::setPlayerUnStrong() {      m_isStrong = false ; } void HeroPlayer::onEnter() {      CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate( this , 0, true );      CCSprite::onEnter(); } void HeroPlayer::onExit() {      CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate( this );      CCSprite::onExit(); } bool HeroPlayer::ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) {      this ->setPosition(pTouch->getLocation());      return true ; } void HeroPlayer::ccTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) {      this ->setPosition(pTouch->getLocation()); } void HeroPlayer::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) {      this ->setPosition(pTouch->getLocation()); }

_sta



本文标签: 用lua写popStar