C++实现五子棋小游戏

Posted Wecccccccc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++实现五子棋小游戏相关的知识,希望对你有一定的参考价值。

代码如下:

#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;

}

以上是关于C++实现五子棋小游戏的主要内容,如果未能解决你的问题,请参考以下文章

五子棋游戏(简单易懂,入门都能学)

C++入门级(超级基础)练手小项目----简单五子棋

C++ 中五子棋游戏的计算机播放器 [关闭]

用C++基础语句写一个五子棋游戏

《游戏学习》java实现连珠五子棋完整代码

《游戏学习》java实现连珠五子棋完整代码