1. 声明该函数

我们在HelloWorldScene.h中声明该函数

?
1
2
//判断游戏是否还能继续
void doCheckGameOver();
2. 具体实现该函数

我们在HelloWorldScene.cpp中具体实现这个函数

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
//判断游戏是否还能继续
void HelloWorld::doCheckGameOver(){
     bool isGameOver =  true ;
     
     for  (int y = 0; y < 4; y++) {
         for  (int x = 0; x < 4; x++) {
             if  (cardArr[x][y]->getNumber() == 0||
                 (x>0&&(cardArr[x][y]->getNumber() == cardArr[x-1][y]->getNumber()))||
                 (x<3&&(cardArr[x][y]->getNumber() == cardArr[x+1][y]->getNumber()))||
                 (y>0&&(cardArr[x][y]->getNumber() == cardArr[x][y-1]->getNumber()))||
                 (y<3&&(cardArr[x][y]->getNumber() == cardArr[x][y+1]->getNumber()))) {
                 isGameOver =  false ;
             }
         }
     }
     
     if  (isGameOver) {
         //游戏结束,重新开始游戏
         log( "游戏结束" );
         Director::getInstance()->replaceScene(TransitionFade::create(1, HelloWorld::createScene()));
     }
}

利用五个条件判断游戏是否还能够继续:(1)还有空卡片 (2)还可以向右滑 (3)还可以向左滑 (4)还可以向上滑 (5)还可以向下滑。

只要以上条件满足一个,游戏就可以再继续。否则,游戏就不能够再继续了,会重新回到开始的界面。

3. 在上下左右每一步滑动后,都添加该函数

在上下左右每一步滑动之后,我们都需要判断该游戏是否还能再继续,所以要在滑动之后添加该函数,例如:

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
         if (endX+5>0)
         {
             //向左
             doLeft();
             //判断游戏是否还能继续
             doCheckGameOver();
         }
         else
         {
             //向右
             doRight();
             //判断游戏是否还能继续
             doCheckGameOver();
         }