【来写个2048吧】—— 移动算法与随机数字生成
//左滑动 bool GameScene:: doLeft () { //判断有没有发生移动 bool isMove = false ; for ( int y = 0 ; y < 4; y++) { for ( int x = 0 ; x < 4; x++) { for ( int x1 = x +1 ; x1 < 4; x1++) { if ( cardArr [x1 ][ y]-> getNumber () > 0 ) { if ( cardArr [x ][ y]-> getNumber () <= 0 ) { cardArr [x ][ y]-> setNumber (cardArr [ x1][ y ]->getNumber ()); cardArr [x1 ][ y]-> setNumber (0 ); x --; isMove = true; } else if ( cardArr[ x ][y ]-> getNumber() == cardArr [ x1][ y ]->getNumber ()) { cardArr [ x][ y ]->setNumber ( cardArr[ x ][y ]-> getNumber() * 2 ); cardArr [x1 ][ y]-> setNumber (0 ); isMove = true; } break ; } } } } return isMove ; }
//右滑动 bool GameScene::doRight() { //判断有没有发生移动 bool isMove = false; for (int y = 0; y < 4; y++) { for (int x = 3; x >= 0; x--) { for (int x1 = x-1; x1>=0; x1--) { if (cardArr[x1][y]->getNumber() > 0) { if (cardArr[x][y]->getNumber() <= 0) { cardArr[x][y]->setNumber(cardArr[x1][y]->getNumber()); cardArr[x1][y]->setNumber(0); x++; isMove = true; } else if(cardArr[x][y]->getNumber() == cardArr[x1][y]->getNumber()) { cardArr[x][y]->setNumber(cardArr[x][y]->getNumber() * 2); cardArr[x1][y]->setNumber(0); isMove = true; } break; } } } } return isMove; }
向上滑动
//上滑动 bool GameScene::doUp() { //判断有没有发生移动 bool isMove = false; for (int x = 0; x < 4; x++) { for (int y = 3; y >= 0; y--) { for (int y1 = y-1; y1>=0; y1--) { if (cardArr[x][y1]->getNumber() > 0) { if (cardArr[x][y]->getNumber() <= 0) { cardArr[x][y]->setNumber(cardArr[x][y1]->getNumber()); cardArr[x][y1]->setNumber(0); y++; isMove = true; } else if(cardArr[x][y]->getNumber() == cardArr[x][y1]->getNumber()) { cardArr[x][y]->setNumber(cardArr[x][y]->getNumber() * 2); cardArr[x][y1]->setNumber(0); isMove = true; } break; } } } } return isMove; }
//下滑动 bool GameScene::doDown() { //判断有没有发生移动 bool isMove = false; for (int x = 0; x < 4; x++) { for (int y = 0; y <4; y++) { for (int y1 = y+1; y1<4; y1++) { if (cardArr[x][y1]->getNumber() > 0) { if (cardArr[x][y]->getNumber() <= 0) { cardArr[x][y]->setNumber(cardArr[x][y1]->getNumber()); cardArr[x][y1]->setNumber(0); y--; isMove = true; } else if(cardArr[x][y]->getNumber() == cardArr[x][y1]->getNumber()) { cardArr[x][y]->setNumber(cardArr[x][y]->getNumber() * 2); cardArr[x][y1]->setNumber(0); isMove = true; } break; } } } } return isMove; }
//创建生成随机卡片 void GameScene:: createCardNumber () { int i = CCRANDOM_0_1 () * 4 ; //生成0~3随机数 int j = CCRANDOM_0_1 () * 4 ; //判断是否已经存在 if ( cardArr [i ][ j]-> getNumber () > 0 ) { createCardNumber (); } else { //2和4的生成率为9:1 cardArr [i ][ j]-> setNumber (CCRANDOM_0_1 ()* 10 < 1 ? 4 : 2); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。