代码如下:
#include <iostream>
using namespace std;class GoBangDesk
{
public:GoBangDesk() :state('@'), flagWin(false), flagOver(false), flagDraw(false){for (int i = 0; i < 20; i++)for (int j = 0; j < 20; j++)goBangDesk[i][j] = '#';}void printDesk(){cout << " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15" << endl;for (int i = 1; i <= 15; i++){cout << " ---------------------------------------------" << endl;cout << i<<"\t";for (int j = 1; j <= 15; j++){cout << "|" << goBangDesk[i][j]<<"|";}cout << endl;}cout<< " ---------------------------------------------" << endl;}void clearDesk(){system("cls");}void gameProcess(){int tmpx;int tmpy;cout << "当前要落的子为:" << state << endl;cout << "请输入坐标,进行落子操作:" << endl;cin >> tmpx >> tmpy;if (tmpx < 1 || tmpx > 15 || tmpy < 1 || tmpy >15){cout << "输入有误,请重新输入" << endl;system("pause");return;}if (goBangDesk[tmpx][tmpy]!='@' && tmpx >= 1 && tmpx <= 15 && tmpy >= 1 && tmpy <=15){idx = tmpx;idy = tmpy;goBangDesk[idx][idy] = state;lastState = state;if (state == '@') state = 'O';else state = '@';checkWin();}else{cout << "输入有误,请重新输入" << endl;system("pause");}}void gameStart(){while (true){printDesk();gameProcess();if (flagOver) break;if (flagDraw){cout << "平局" << endl;break;}clearDesk();}}void checkWin(){for (int i = 0; i < 8; i++){checkWinDfs(idx, idy, i, 1);if (flagWin){cout << lastState << "方赢得比赛" << endl;flagOver = true;break;}}}void checkDesk() {bool flag = false;for (int i = 1; i <= 15; i++){for (int j = 1; j <= 15; j++){if (goBangDesk[i][j] == '@'){flag = true;flagDraw = true;if (flag) break;}}if (flag) break;}}private:void checkWinDfs(int x, int y, int k, int step){if (step == 5){flagWin = true;}char tmpState = goBangDesk[x][y];int xx = x + dx[k];int yy = y + dy[k];if (goBangDesk[xx][yy] != tmpState && goBangDesk[xx][yy] != '@' || step > 5) return;checkWinDfs(xx, yy, k, step + 1);}private:static const int N = 20;char goBangDesk[N][N];int idx;int idy;char state;//当前是哪个子(状态)char lastState;//上一次是哪个子(状态)int dx[8] = { 0,0,1,-1,1,1,-1,-1 };int dy[8] = { 1,-1,0,0,1,-1,1,-1 };bool flagWin;//判断胜利bool flagOver;//判断结束bool flagDraw;//判断棋盘满了,平局
};int main()
{GoBangDesk d;d.gameStart();return 0;}