悔棋需要用到备忘录模式。大致思路是:我们先创建一个Step结构体,这个结构体记录着两个棋子的id(一个是移动棋子,一个是被杀棋子)、移动前行列,移动后行列。然后创建一个Step链表存放所有Step,在调用移动棋子函数moveStone时把当前棋子状态放进_steps中,当玩家点击菜单按钮的悔棋按钮时调用悔棋按钮的回调函数执行悔棋操作。在完成这一篇内容后,下一篇我们就开始写人工智能,写完AI类,简单的cocos2dx-3.14的中国象棋也就基本算完成了。
这里把LayerGameMain需要添加的成员变量和成员函数都列出来
//定义一个结构体记录每一步信息
struct Step
{
int moveid;//移动棋子的id
int killid;//被杀棋子的id
int rowFrom;//移动前的行
int colFrom;//移动前的列
int rowTo;//移动后的行
int colTo;//移动后的列
};
//悔棋相关
list _steps;//存放整局棋谱
void recordStep(int moveid, int killid, int rowFrom, int colFrom, int rowTo, int colTo);//记录悔棋相关参数
void addCtrlMenu();//添加悔棋等菜单
void regretItemCallback(Ref *obj);//悔棋菜单回调函数
void regret1Step();//悔棋1步执行函数
这里就不大篇幅地解释了,要看懂也很容易,先从moveStone找到addCtrlMenu函数然后查看一下addCtrlMenu函数基本就能看懂。这里直接上所有代码。
LayerGameMain.h
#ifndef __LAYERGAMEMAIN_H__
#define __LAYERGAMEMAIN_H__
#include "cocos2d.h"
#include "Plate.h"
#include "Stone.h"
#include
#include
using namespace std;
/*
cocos2d-x3.14.1版本将大部分类的前缀CC去掉了,不过有部分还是兼容,如果用旧的命名创建对应的类会有警告提示/错误提示
*/
USING_NS_CC;
//定义一个结构体记录每一步信息
struct Step
{
int moveid;//移动棋子的id
int killid;//被杀棋子的id
int rowFrom;//移动前的行
int colFrom;//移动前的列
int rowTo;//移动后的行
int colTo;//移动后的列
};
class LayerGameMain : public Layer
{
public:
static Scene* createScene();
virtual bool init();
CREATE_FUNC(LayerGameMain);
//添加棋盘和棋子
void addPlate();//用于在LayerGameMain上添加棋盘层/精灵
void addStones();//用于在LayerGameMain上添加棋子层/精灵
//触摸事件回调函数
bool touchBeganCallBack(Touch *pTouch, Event *pEvent);
void touchEndedCallBack(Touch *pTouch, Event *pEvent);
//选中棋子相关
Sprite *selectBox;//选中款精灵
static int _selectedId;//标记当前选中的棋子id,没有点中为-1
bool Screen2Plate(Point &point, int &row, int &col);//循环棋盘上所有点,通过Plate2Screen获取到棋子中心点,用引用输出中心点
Point Plate2Screen(int row, int col);//获取棋子中心点返回到世界坐标给Screen2Plate
void selectStone(Touch *pTouch);//选中棋子,将选中框精灵移动到选中的棋子上
//获取棋子相关
__Array *arrStone;//用于存放棋子
Stone* getStoneFromArrById(int id);//通过棋子id从arrStone获取对应棋子
int getStoneIdFromRowCol(int row, int col);//通过行列获取棋子id
//棋子移动相关
static bool _redTurn;
void moveStone(Touch *pTouch);
int getStoneCount(int row1, int col1, int row2, int col2);
bool canMove(int moveid, int row, int col, int killid);//筛选移动规则
//moveid为当前想要移动棋子的id,killid移动的目的点(-1为没有棋子),row和col为目的点的行列
//炮、兵、将、车移动规则都有点相似
bool canMoveChe(int moveid, int row, int col);//车移动规则
bool canMovePao(int moveid, int row, int col, int killid);//炮移动规则
bool canMoveBing(int moveid, int row, int col);//兵移动规则
bool canMoveJiang(int moveid, int row, int col, int killid);//将移动规则
bool canMoveMa(int moveid, int row, int col);//马移动规则
bool canMoveXiang(int moveid, int row, int col);//象移动规则
bool canMoveShi(int moveid, int row, int col);//士移动规则
bool isSameColor(int clickedId);//判断选中棋子颜色是否相同
//悔棋相关
list _steps;//存放整局棋谱
void recordStep(int moveid, int killid, int rowFrom, int colFrom, int rowTo, int colTo);//记录悔棋相关参数
void addCtrlMenu();//添加悔棋等菜单
void regretItemCallback(Ref *obj);//悔棋菜单回调函数
void regret1Step();//悔棋1步执行函数
};
#endif // !__LAYERGAMEMAIN_H__
LayerGameMain.cpp
#include "LayerGameMain.h"
using namespace std;
int LayerGameMain::_selectedId = -1;
bool LayerGameMain::_redTurn = true;
Scene* LayerGameMain::createScene()
{
auto ret = Scene::create();
auto layer = LayerGameMain::create();
ret->addChild(layer);
return ret;
}
bool LayerGameMain::init()
{
if (!Layer::init())
{
return false;
}
arrStone = __Array::create();
arrStone->retain();//计数器+1,否则会被回收
_steps.clear();//初始化steps链表
selectBox = Sprite::create("selected.png");
selectBox->setVisible(false);
selectBox->setLocalZOrder(1000);//设置显示优先级
this->addChild(selectBox);
this->addPlate();
this->addStones();
addCtrlMenu();
//cocos2d-x3.14.1触摸事件,创建监听
EventDispatcher* eventDispatcher = Director::getInstance()->getEventDispatcher();
auto listener = EventListenerTouchOneByOne::create();
listener->setEnabled(true);
listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(LayerGameMain::touchBeganCallBack, this);
listener->onTouchEnded = CC_CALLBACK_2(LayerGameMain::touchEndedCallBack, this);
eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
void LayerGameMain::addPlate()
{
Plate *plate = Plate::create();
this->addChild(plate);
}
void LayerGameMain::addStones()
{
int i = 0;
Stone *stone;
for (i = 0; i < 32; i++)
{
stone = Stone::create(i);
arrStone->addObject(stone);//将棋子添加进数组
this->addChild(stone);
}
}
Stone* LayerGameMain::getStoneFromArrById(int stoneId)
{
Stone *ret;
ret = nullptr;
if (stoneId > 0)
{
ret = (Stone *)arrStone->getObjectAtIndex(stoneId);
}
return ret;
}
bool LayerGameMain::touchBeganCallBack(Touch *pTouch, Event *pEvent)
{
return true;
}
void LayerGameMain::touchEndedCallBack(Touch *pTouch, Event *pEvent)
{
if (_selectedId == -1)
{
selectStone(pTouch);
}
else
{
moveStone(pTouch);
}
}
bool LayerGameMain::Screen2Plate(Point &point, int &row, int &col)
{
int distance = Stone::_d/2 * Stone::_d/2;//以半径作为距离
for (row = 0; row <= 9; row++)
{
for (col = 0; col <= 8; col++)
{
Point ptCenter = Plate2Screen(row, col);
if (distance > ptCenter.getDistanceSq(point))//获取点距的平方并比较,如果小于半径平方则为能选中中心点上的棋子
{
return true;
}
}
}
return false;
}
Point LayerGameMain::Plate2Screen(int row, int col)//该函数与Stone的getPositionFromPlate类似
{
Point ret = Point(Stone::_offx + col*Stone::_d, Stone::_offy + row*Stone::_d);
return ret;
}
int LayerGameMain::getStoneIdFromRowCol(int row, int col)
{
int ret = -1;
Ref *obj;
CCARRAY_FOREACH(arrStone,obj)
{
Stone *stone = (Stone *)obj;
if (stone->_row == row && stone->_col == col && !stone->_isdead)//已死去的棋子不能选中
{
ret = stone->_id;
return ret;
}
}
return ret;
}
void LayerGameMain::selectStone(Touch *pTouch)
{
Point point = pTouch->getLocation();
int row, col;
if (!Screen2Plate(point, row, col))//点中范围不在棋盘上直接返回
{
selectBox->setVisible(false);
return;
}
int clickedId = getStoneIdFromRowCol(row, col);
if (clickedId < 0)//没选中棋子直接返回
{
selectBox->setVisible(false);
return;
}
Stone *clickedStone = getStoneFromArrById(clickedId);
if (clickedStone->_red != _redTurn)//如果没有轮到,不能选中、移动
{
return;
}
selectBox->setPosition(Plate2Screen(row, col));
selectBox->setVisible(true);
_selectedId = clickedId;//记录下棋子id
}
void LayerGameMain::moveStone(Touch *pTouch)
{
Point ptClicked = pTouch->getLocation();
int row, col;
if (!Screen2Plate(ptClicked, row, col))//获取触点的行列,如果触点不在棋盘上直接返回
{
return;
}
int clickedId = getStoneIdFromRowCol(row, col);//获取触点上的棋子id,没有棋子为-1
//如果点中相同颜色的棋子,选中框转移到最后选中的棋子上
if (clickedId != -1 && isSameColor(clickedId))
{
Stone *clickedStone = getStoneFromArrById(clickedId);
selectBox->setPosition(Plate2Screen(clickedStone->_row, clickedStone->_col));
_selectedId = clickedId;
return;
}
if (!canMove(_selectedId, row, col, clickedId))
{
return;
}
Stone *selectedStone = getStoneFromArrById(_selectedId);
//悔棋相关,移动前记录各项信息
recordStep(_selectedId, clickedId, selectedStone->_row, selectedStone->_col, row, col);
//移动相关
Point pt = Plate2Screen(row, col);
MoveTo *to = MoveTo::create(0.3, pt);
selectedStone->runAction(to);
selectedStone->_row = row;
selectedStone->_col = col;
if (clickedId != -1)
{
Stone *clickedStone = getStoneFromArrById(clickedId);
clickedStone->setVisible(false);
clickedStone->_isdead = true;
}
//移动完毕初始化选中框和选中id
selectBox->setVisible(false);
_selectedId = -1;//移动完成后初始化为-1
_redTurn = !_redTurn;
}
int LayerGameMain::getStoneCount(int row1, int col1, int row2, int col2)
{
int ret = 0;//记录棋子的个数
if (row1 != row2 && col1 != col2) return -1;//行列都不同,没有直线
if (row1 == row2 && col1 == col2) return -1;//行列都相同,两点相同,不需要移动
if (row1 == row2)//列相同
{
int mincol = col1 < col2 ? col1 : col2;//获取两点间较小的行
int maxcol = col1 > col2 ? col1 : col2;//获取两点间较大的行
for (int col = mincol+1; col < maxcol; col++)//遍历两点间所有点
{
if (getStoneIdFromRowCol(row1, col) > 0)//如果存在棋子,ret棋子计数器+1
{
++ret;
}
}
}
else if(col1 == col2)
{
int minrow = row1 < row2 ? row1 : row2;//获取两点间较小的列
int maxrow = row1 > row2 ? row1 : row2;//获取两点间较大的列
for (int row = minrow + 1; row < maxrow; row++)//遍历两点间所有点
{
if (getStoneIdFromRowCol(row, col1) > 0)//如果存在棋子,ret棋子计数器+1
{
++ret;
}
}
}
return ret;
}
bool LayerGameMain::canMove(int moveid, int row, int col, int killid)
{
Stone *stone = getStoneFromArrById(moveid);
switch (stone->_type)
{
case Stone::CHE:
return canMoveChe(moveid, row, col);
break;
case Stone::JIANG:
return canMoveJiang(moveid, row, col, killid);
break;
case Stone::BING:
return canMoveBing(moveid, row, col);
break;
case Stone::PAO:
return canMovePao(moveid, row, col, killid);
break;
case Stone::MA:
return canMoveMa(moveid, row, col);
break;
case Stone::XIANG:
return canMoveXiang(moveid, row, col);
break;
case Stone::SHI:
return canMoveShi(moveid, row, col);
break;
default:
break;
}
return false;
}
bool LayerGameMain::canMoveChe(int moveid, int row, int col)
{
//车只有在两点间不存在棋子时才能走
Stone *che = getStoneFromArrById(moveid);
return getStoneCount(che->_row, che->_col, row, col) == 0;
}
bool LayerGameMain::canMovePao(int moveid, int row, int col, int killid)
{
//炮可以行走只有两种情况:1.两点间没有棋子。2.两点间存在一个棋子,并且目的点也存在棋子。
Stone *pao = getStoneFromArrById(moveid);
if (killid == -1)
{
return getStoneCount(pao->_row, pao->_col, row, col) == 0;
}
return getStoneCount(pao->_row, pao->_col, row, col) == 1;
}
bool LayerGameMain::canMoveBing(int moveid, int row, int col)
{
//兵行走规则:1.只能走一格。2.不能回退。3.过河前只能直走
Stone *bing = getStoneFromArrById(moveid);
int dRow = abs(bing->_row - row);
int dCol = abs(bing->_col - col);
int d = dRow * 10 + dCol;//此处类似标记效果,10等价于(1,0),1代表可移动,第一位说明可以左右移动一格,第二位说明可以上下移动一格
if (d != 1 && d != 10)
{
return false;
}
if (bing->_red)
{
//兵不能回退
if (row < bing->_row)
{
return false;
}
//兵过河前不能左右移动
if (bing->_row <= 4 && bing->_row == row)
{
return false;
}
}
else
{
if (row > bing->_row)
{
return false;
}
if (bing->_row >= 5 && bing->_row == row)
{
return false;
}
}
return true;
}
bool LayerGameMain::canMoveJiang(int moveid, int row, int col, int killid)
{
//将规则:1.一次只能移动一格。2.不能出九宫格。3.将帅照面时可以直接对杀。
Stone *jiang = getStoneFromArrById(moveid);
//将照面杀
if (killid != -1)
{
Stone *kill = getStoneFromArrById(killid);
if (kill->_type == Stone::JIANG)
{
return canMoveChe(moveid, row, col);//复用车的移动方法,减少代码量
}
}
int dRow = abs(jiang->_row - row);
int dCol = abs(jiang->_col - col);
int d = dRow * 10 + dCol;//此处类似标记效果,10等价于(1,0),1代表可移动,第一位说明可以左右移动一格,第二位说明可以上下移动一格
if (d != 1 && d != 10)
{
return false;
}
//将不能左右出九宫
if (col < 3 || col > 5)
{
return false;
}
//将不能上下出九宫
if (jiang->_red)
{
if (row > 2 || row <0)
{
return false;
}
}
else
{
if (row < 7 || row >9)
{
return false;
}
}
return true;
}
bool LayerGameMain::canMoveMa(int moveid, int row, int col)
{
//马规则:1.马走日。2.卡住马脚不能移动。
Stone *ma = getStoneFromArrById(moveid);
int dRow = abs(ma->_row - row);
int dCol = abs(ma->_col - col);
int d = dRow * 10 + dCol;
//12为横日,21为竖日,类似于(1,2)(2,1)做法
if (d == 12 || d == 21)
{
int cRow, cCol;
if (d == 12)
{
//蹩脚点
cCol = (col + ma->_col) / 2;
cRow = ma->_row;
}
else
{
cCol = ma->_col;
cRow = (ma->_row + row) / 2;
}
//获取蹩脚点后判断蹩脚点是否有棋子
if (getStoneIdFromRowCol(cRow, cCol) == -1)
{
return true;
}
}
return false;
}
bool LayerGameMain::canMoveXiang(int moveid, int row, int col)
{
//象规则:1.象走田。2.被卡象眼不能移动。3.象不能过河
Stone *xiang = getStoneFromArrById(moveid);
int dRow = abs(xiang->_row - row);
int dCol = abs(xiang->_col - col);
int d = dRow * 10 + dCol;
if (d != 22)
{
return false;
}
int cRow, cCol;
cRow = (row + xiang->_row) / 2;
cCol = (col + xiang->_col) / 2;
if (getStoneIdFromRowCol(cRow, cCol) != -1)//卡主香烟不能移动
{
return false;
}
if (xiang->_red)
{
if (row > 4) return false;
}
else
{
if (row < 5) return false;
}
return true;
}
bool LayerGameMain::canMoveShi(int moveid, int row, int col)
{
//士规则:1.一次斜着走一格。2.不能出九宫格
Stone *shi = getStoneFromArrById(moveid);
int dRow = abs(shi->_row - row);
int dCol = abs(shi->_col - col);
int d = dRow * 10 + dCol;
//只能斜线走
if (d != 11)
{
return false;
}
//不能两侧走出九宫
if (col<3 || col>5)
{
return false;
}
//不能上下走出九宫
if (shi->_red)
{
if (row>2 || row<0)
{
return false;
}
}
else
{
if (row<7 || row>9)
{
return false;
}
}
return true;
}
bool LayerGameMain::isSameColor(int clickedId)
{
Stone *clickedStone = getStoneFromArrById(clickedId);
Stone *selectedStone = getStoneFromArrById(_selectedId);
return selectedStone->_red == clickedStone->_red;
}
void LayerGameMain::recordStep(int moveid, int killid, int rowFrom, int colFrom, int rowTo, int colTo)
{
Step *step = new Step();
step->moveid = moveid;
step->killid = killid;
step->rowFrom = rowFrom;
step->colFrom = colFrom;
step->rowTo = rowTo;
step->colTo = colTo;
_steps.push_back(step);
}
void LayerGameMain::addCtrlMenu()
{
MenuItemImage *regretItem = MenuItemImage::create("regret.png",
"regretselected.png",
this,
menu_selector(LayerGameMain::regretItemCallback));
Menu *menu = Menu::create();
menu->addChild(regretItem);
this->addChild(menu);
menu->setPosition(Point(400, 160));
}
void LayerGameMain::regretItemCallback(Ref *obj)
{
if (_steps.size() <= 1)//只走了一步不能悔棋
{
return;
}
for (int i = 0; i < 2; i++)//悔棋两步
{
regret1Step();
}
return;
}
void LayerGameMain::regret1Step()
{
Step *step = *_steps.rbegin();
Stone *stone = getStoneFromArrById(step->moveid);
stone->_row = step->rowFrom;
stone->_col = step->colFrom;
stone->setPosition(Plate2Screen(stone->_row, stone->_col));
if (step->killid != -1)//如果目标点有棋子,将棋子回归为原来状态
{
stone = getStoneFromArrById(step->killid);
stone->_isdead = false;
stone->setVisible(true);
}
_redTurn = !_redTurn;//执棋权归还给对方
delete step;
_steps.pop_back();
//防止选中棋子情况下悔棋
selectBox->setVisible(false);
_selectedId = -1;
return;
}