本文主要是介绍2048 游戏中滑块上下左右滑动相加的逻辑实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. 添加一个数组我们需要借助数组,来实现这个逻辑功能。在HelloWorldScene.h中添加一个数组声明:
//创建一个卡片二位数组
CardSprite* cardArr[4][4];
2. 把数字添加到数组中
还记得我们在创建卡片函数createCardSprite函数中得到的卡片card吗?现在,我们就把这个卡片加入到数组中:
//把卡片加入到数组中
cardArr[i][j] = card;
3. 添加具体的逻辑
(1)向左滑动函数的逻辑代码:
bool HelloWorld::doLeft(){
bool isdo = 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--;
isdo = 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);
isdo = true;
}
break;
}
}
}
}
return isdo;
}
如果右边的数等于左边的数,那么左边的数乘以2,然后把右边的数设置为0,也就变为了空。
另外三个方向滑动的逻辑代码,也类似。
(2)向右滑动函数的逻辑代码:
bool HelloWorld::doRight(){
bool isdo = 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++;
isdo = 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);
isdo = true;
}
break;
}
}
}
}
return isdo;
}
(3)向下滑动函数的逻辑代码:
bool HelloWorld::doDown(){
bool isdo = 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--;
isdo = 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);
isdo = true;
}
break;
}
}
}
}
return isdo;
}
(4)向上滑动函数的逻辑代码:
bool HelloWorld::doUp(){
bool isdo = 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++;
isdo = 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);
isdo = true;
}
break;
}
}
}
}
return isdo;
}
这篇关于2048 游戏中滑块上下左右滑动相加的逻辑实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!