ssdut c++的大作业,在控制台的界面实现人人对弈,比较适合初学,自己设计了一些简单算法,两百多行完成。
以下正文:
完成中国象棋游戏,实现如下功能:
1.实现人与人之间象棋的对弈。
2.每次走子之前都会判断是否符合规则,若不符合规则就要重新走子。
3.程序随时判断是否有一方取得胜利,该局结束。
类的设计:
1.chess:棋子类,有int型私有变量id存储棋子的编号。作为基类派生出其他具体的棋子类。有判断棋子走法是否符合规则的judge_move()纯虚函数。
代码:
class chess{
private:
int id;//等级
public:
chess(int i):id(i){}
int get(){return id;}
virtual bool judge_move(chessboard &cb,int startx,int starty,int aimx,int aimy)=0;
virtual ~chess(){};//虚析构
};
2.具体的棋子类:包括soldier类、horse类、rook类、guard类、cannon类、elephant类、general类分别代表兵(卒)、馬(马)、車(车)、士(仕)、炮(砲)、相(象)、帅(将)的类,由chess类作为基类派生。每个派生类都对judge_move()函数进行重写。
以马为例:
class horse : public chess{//马的实现
public:
horse(int i) : chess((i==0?-2:2)){}
bool judge_move(chessboard &cb,int startx,int starty,int aimx,int aimy){
int tempx=aimx-startx,tempy=aimy-starty;
int sid=cb.getid(startx, starty),aid=cb.getid(aimx, aimy);
if(sid*aid<=0&&(tempx*tempx+tempy*tempy==5)&&!cb.get(startx+tempx/2,starty+tempy/2))
return true;
return false;
}
};
3.chessboard类:棋盘类,私有成员包括10*9的指向chess类的指针数组,用以存储各个棋子对象的地址,并通过指针调用实现多态。
代码:
class chessboard{
private:
chess *c[10][9];//用指针调用各个棋子,实现多态
char chessword[15][4]={"帅","相","炮","士","車","馬","兵","","卒","马","车","仕","砲","象","将"};//名字
public:
chessboard(){memset(c, NULL, sizeof(c));};//把指针初始化为零指针
void init();
chess* get(int x,int y){return c[x][y];}
int getid(int x,int y){ if(c[x][y]!=NULL) return c[x][y]->get();return 0;}
void show();
void play();
bool move(int startx,int starty,int aimx,int aimy);
~chessboard();//析构函数
static bool end;//判断结束
static int player;
};
算法描述:
红方棋子:中文分别为"兵","馬","車","士","炮","相","帅"。
id的编号分别为-1、-2、-3、-4、-5、-6、-7。