C++ 井字棋

Posted

tags:

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

#include <iostream>
#include <string>

using namespace std;

const int MAX_MOVES=9;

void printBoard(int board[3][3]);

void getNextMove(int board[3][3]);

//isAvailable();

//makeMove();

//playerHasWon();

int main()
int i;
int n;
int board[3][3]=
7,8,9,
4,5,6,
1,2,3
;

printBoard(board);

for(i=0;i<MAX_MOVES;i++)
getNextMove(board);
n++;


if(n=MAX_MOVES)
cout<<"gameover";

system("PAUSE");
return 0;


void printBoard(int board[3][3])
cout<<board[0][0]<<" | "<<board[0][1]<<" | "<<board[0][2]<<endl;
cout<<"--+---+--"<<endl;
cout<<board[1][0]<<" | "<<board[1][1]<<" | "<<board[1][2]<<endl;
cout<<"--+---+--"<<endl;
cout<<board[2][0]<<" | "<<board[2][1]<<" | "<<board[2][2]<<endl;


void getNextMove(int board[3][3])
int i,j,s,t,m;
cout<<"Make your move: ";
cin>>m;

for(i=0;i<3;i++)
for(j=0;j<3;j++)
if(board[i][j]==m)
s=i;
t=j;


board[s][t]=x;
printBoard(board);


两个玩家玩, 不是对电脑, 上面是自己写的,请帮忙修改!
//isAvailable();

//makeMove();

//playerHasWon();
这是还没写的子程序..
有问题可以加我Q, 谢谢高手门!!

参考技术A 好了 所有要求都有了

#include <iostream>
#include <string>

using namespace std;

const int MAX_MOVES=9;

void printBoard(char board[3][3]);

void getNextMove(char board[3][3]);

void win(char board[3][3]);

void whowin(char key);
int foot = 0;

int main()

int i;
int n = 0;
char board[3][3]= '7','8','9', '4','5','6', '1','2','3' ;

printBoard(board);

for(i=0;i<MAX_MOVES;i++)

getNextMove(board);
win(board);
n++;


if(n=MAX_MOVES)
cout<<"gameover";

system("PAUSE");
return 0;

void win(char a[3][3])

int i, j, k;
char key;
if((a[0][0] == a[1][1] && a[1][1] == a[2][2] && a[2][2] == a[0][0]) || (a[2][0] == a[1][1] && a[1][1] == a[0][2] && a[2][0] == a[0][2]))

key = a[0][0];
whowin(key);

else

for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
if(a[i][j] == 15 || a[i][j] == 'X')

key = a[i][j];
for(k = 0; k < 3; k++)

if(a[i][k] != key)
break;

if(k == 3)
whowin(key);
for(k = 0; k < 3; k++)

if(a[k][j] != key)
break;

if(k == 3)
whowin(key);



void whowin(char key)

if(key == 15)
cout << "P1 Win!" << endl;
else
cout << "P2 Win!" << endl;
exit(0);

void printBoard(char board[3][3])

cout<<board[0][0]<<" | "<<board[0][1]<<" | "<<board[0][2]<<endl;
cout<<"--+---+--"<<endl;
cout<<board[1][0]<<" | "<<board[1][1]<<" | "<<board[1][2]<<endl;
cout<<"--+---+--"<<endl;
cout<<board[2][0]<<" | "<<board[2][1]<<" | "<<board[2][2]<<endl;


void getNextMove(char board[3][3])

int i,j,s,t;
char m;
while(1)

s = -1;
t = -1;
cout<<"Make your move: ";
cin>>m;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
if(board[i][j]==m)

s=i;
t=j;

if(s == -1 && t == -1)
cout << "that point already has a pawn!" << endl;
else
break;

if(foot % 2 == 0)
board[s][t] = 15;
else
board[s][t] = 'X';
foot++;
system("cls");
printBoard(board);
本回答被提问者和网友采纳
参考技术B 我有MFC版。
#include <afxwin.h>

typedef int Int32;

class CMyApp : public CWinApp

public:
virtual BOOL InitInstance();
;

class CMainWindow : public CFrameWnd

public:
CMainWindow();

private:
enumEX = 1, OH;

virtual void PostNcDestroy();

afx_msg void OnPaint();
afx_msg void OnLButtonDown(UINT, CPoint);
//afx_msg void OnLButtonDblClk(UINT, CPoint);
afx_msg void OnRButtonDown(UINT, CPoint);

CRect GetRcSquares(const Int32 &) const;
Int32 GetRectID(const CPoint &) const;
void DrawBoard(CDC *) const;
void DrawX(CDC *, const Int32 &) const;
void DrawO(CDC *, const Int32 &) const;
void ResetGame();
void CheckForGameOver();
Int32 IsWinner() const;
BOOL IsDraw() const;

Int32 m_nGameGrid[9];
Int32 m_nNextChar;

DECLARE_MESSAGE_MAP()
;

#include "TicTac.h"

CMyApp myApp;

BOOL CMyApp::InitInstance()

m_pMainWnd = new CMainWindow;
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE;


BEGIN_MESSAGE_MAP(CMainWindow, CFrameWnd)
ON_WM_PAINT()
ON_WM_LBUTTONDOWN()
//ON_WM_LBUTTONDBLCLK()
ON_WM_RBUTTONDOWN()
END_MESSAGE_MAP()

CRect CMainWindow::GetRcSquares(const Int32 &i) const

return CRect( (i % 3) * 112 + 16, (i / 3) * 112 + 16, (i % 3 + 1) * 112, (i / 3 + 1) * 112);


CMainWindow::CMainWindow()
:m_nNextChar(EX)

::ZeroMemory(m_nGameGrid, 9 * sizeof(Int32) );

CString strWndClass = AfxRegisterWndClass(
CS_DBLCLKS,
AfxGetApp()->LoadStandardCursor(IDC_ARROW),
(HBRUSH)(COLOR_3DFACE + 1),
AfxGetApp()->LoadStandardIcon(IDI_WINLOGO)
);

CreateEx(0, strWndClass, _T("Tic-Tac-Toe"),
WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL);

CRect rect(0, 0, 352, 352);
CalcWindowRect(&rect);
SetWindowPos(NULL, 0, 0, rect.Width(), rect.Height(),
SWP_NOZORDER | SWP_NOMOVE | SWP_NOREDRAW);


void CMainWindow::PostNcDestroy()

delete this;


void CMainWindow::OnPaint()

CPaintDC dc(this);
DrawBoard(&dc);


void CMainWindow::OnLButtonDown(const UINT nFlags, const CPoint point)

if(m_nNextChar != EX)
return;

if( (GetRectID(point) == -1) || (m_nGameGrid[GetRectID(point) ] != 0) )
return;

m_nGameGrid[GetRectID(point) ] = EX;
m_nNextChar = OH;

CClientDC dc(this);
DrawX(&dc, GetRectID(point) );
CheckForGameOver();


void CMainWindow::OnRButtonDown(const UINT nFlags, const CPoint point)

if(m_nNextChar != OH)
return;

if( (GetRectID(point) == -1) || (m_nGameGrid[GetRectID(point) ] != 0) )
return;

m_nGameGrid[GetRectID(point) ] = OH;
m_nNextChar = EX;

CClientDC dc(this);
DrawO(&dc, GetRectID(point) );
CheckForGameOver();


//void CMainWindow::OnLButtonDblClk(const UINT nFlags, const CPoint point)
//
// CClientDC dc(this);
// if(dc.GetPixel(point) == RGB(0, 0, 0) )
// ResetGame();
//

Int32 CMainWindow::GetRectID(const CPoint &point) const

for(Int32 i = 0; i < 9; ++i)

if(GetRcSquares(i).PtInRect(point) )
return i;

return -1;


void CMainWindow::DrawBoard(CDC *const pDC) const

CPen pen(PS_SOLID, 16, RGB(0, 0, 0) );
CPen *pOldPen = pDC->SelectObject(&pen);

pDC->MoveTo(120, 16);
pDC->LineTo(120, 336);

pDC->MoveTo(232, 16);
pDC->LineTo(232, 336);

pDC->MoveTo( 16, 120);
pDC->LineTo(336, 120);

pDC->MoveTo( 16, 232);
pDC->LineTo(336, 232);

pDC->SelectObject(pOldPen);


void CMainWindow::DrawX(CDC *const pDC, const Int32 &nPos) const

CPen pen(PS_SOLID, 16, RGB(255, 0, 0) );
CPen *pOldPen = pDC->SelectObject(&pen);

CRect rect = GetRcSquares(nPos);
rect.DeflateRect(16, 16);
pDC->MoveTo(rect.left, rect.top);
pDC->LineTo(rect.right, rect.bottom);
pDC->MoveTo(rect.left, rect.bottom);
pDC->LineTo(rect.right, rect.top);

pDC->SelectObject(pOldPen);


void CMainWindow::DrawO(CDC *const pDC, const Int32 &nPos) const

CPen pen(PS_SOLID, 16, RGB(0, 0, 255) );
CPen *pOldPen = pDC->SelectObject(&pen);
pDC->SelectStockObject(NULL_BRUSH);

CRect rect = GetRcSquares(nPos);
rect.DeflateRect(16, 16);
pDC->Ellipse(rect);

pDC->SelectObject(pOldPen);


void CMainWindow::CheckForGameOver()

if(IsWinner() )

MessageBox((IsWinner() == EX) ? _T("X wins!") : _T("O wins!"),
_T("Game Over"), MB_ICONEXCLAMATION | MB_OK);
ResetGame();

else if(IsDraw() )

MessageBox(_T("It's a draw!"), _T("Game Over"), MB_ICONEXCLAMATION | MB_OK);
ResetGame();



Int32 CMainWindow::IsWinner() const

static const Int32 nPattern[8][3] =
0, 1, 2,
3, 4, 5,
6, 7, 8,
0, 3, 6,
1, 4, 7,
2, 5, 8,
0, 4, 8,
2, 4, 6
;

for(Int32 i = 0; i < 8; ++i)

if( (m_nGameGrid[nPattern[i][0] ] == EX) &&
(m_nGameGrid[nPattern[i][1] ] == EX) &&
(m_nGameGrid[nPattern[i][2] ] == EX) )
return EX;

if( (m_nGameGrid[nPattern[i][0] ] == OH) &&
(m_nGameGrid[nPattern[i][1] ] == OH) &&
(m_nGameGrid[nPattern[i][2] ] == OH) )
return OH;

return 0;


BOOL CMainWindow::IsDraw() const

for(Int32 i = 0; i < 9; ++i)

if(m_nGameGrid[i] == 0)
return FALSE;

return TRUE;


void CMainWindow::ResetGame()

m_nNextChar = EX;
::ZeroMemory(m_nGameGrid, 9 * sizeof(Int32) );
Invalidate();

参考资料:MFC Window程序设计 Jeff Prosise

C++实现井字棋小游戏(写得不好,留作纪念!!!)

回宿舍路上,同学问起我能不能用C++写个五子棋游戏,我说应该挺简单的,但是我不会写,然后他说不用写五子棋,就写井字棋吧!!!我说试试吧!!!
(不过说实话,写得不是很好,留作纪念吧!!!)

代码如下:

#include <iostream>
using namespace std;
const int N = 5;
bool vis[N][N] = { false };
bool tttSon[N][N] = { false };
char tttDesk[N][N];
int dx[] = { 1,-1,1,-1,0,0,1,-1 };
int dy[] = { 0,0, 1,-1,1,-1,-1,1 };
bool isEnd = false;

void printError()
{
	cout << "无效输入,按任意键后,重新输入" << endl;
}

void initDesk()
{
	for (int i = 1; i <= 3; i++)
		for (int j = 1; j <= 3; j++)
			tttDesk[i][j] = '@';
}

void printInterface(char son)
{
	int flagX = 0, flagY = 0;
	for (int i = 1; i <= 3; i++)
	{
		for (int j = 1; j <= 3; j++)
		{
			cout << vis[i][j] << " ";
			if (vis[i][j])
			{
				flagX = i;
				flagY = j;
			}
		}
		cout << endl;
	}
	cout << "当前要落的子为:" << son << endl;
	cout << "当前光标的位置在第" << flagX << "行," << "第" << flagY << "列" << endl;
	cout << "-------------------------------------" << endl;

	for (int i = 1; i <= 3; i++)
	{
		for (int j = 1; j <= 3; j++)
		{
			cout << tttDesk[i][j] << " ";
		}
		cout << endl;
	}
}

void checkPos(int &sonX,int &sonY)
{
	for (int i  =1;i<=3;i++)
		for (int j = 1; j <= 3; j++)
		{
			if (!tttSon[i][j])
			{
				sonX = i;
				sonY = j;
				vis[sonX][sonY] = true;
				return;
			}
		}
}




bool checkWinOfDfs(int x, int y,int step,char me,int k)
{
	if (step == 3) return true;
	int xx = x + dx[k];
	int yy = y + dy[k];
	if (xx < 1 || xx > 3 || yy < 1 || yy > 3 || tttDesk[xx][yy] != me || tttDesk[xx][yy]=='@') return false;
	/*cout << xx << " " << yy << endl;*/
	checkWinOfDfs(xx, yy, step + 1, me, k);

}


void operatorDesk(int &sonX,int &sonY,char &son)
{
	char sonIng;
	bool flag = false;
	initDesk();
	int cnt = 0;
	while (true)
	{
		bool winFlag = false;
		if (cnt > 4 && tttDesk[sonX][sonY]!='@')
		{
			/*cout << sonX << " " << sonY << endl;*/
			for (int k = 0; k < 8; k++)
			{
				if (checkWinOfDfs(sonX, sonY, 1, tttDesk[sonX][sonY], k))
				{
					winFlag = true;
				}
				if (winFlag)
				{
					if (tttDesk[sonX][sonY]=='O')
					cout << "Winer is O" << endl;
					else cout << "Winer is X" << endl;
					isEnd = true;
					return;
				}
			}
			int cnt1 = 0;
			for (int i = 1;i<=3;i++)
				for (int j = 1; j <= 3; j++)
				{
					if (tttSon[i][j]) cnt1++;
				}
			if (cnt1 == 9) return;
		}
		if (!flag)
		checkPos(sonX,sonY);
		printInterface(son);
		cout << "请输入指令" << endl;
		cin >> sonIng;
		if (sonIng == 'w' || sonIng == 'W')
		{
			if (sonX - 1 < 1 )
			{
				printError();
				system("pause");
				system("cls");
				continue;
			}
			flag = true;
			vis[sonX][sonY] = false;
			sonX -= 1;
			vis[sonX][sonY] = true;
			system("cls");
		}
		else if (sonIng == 's' ||sonIng == 'S')
		{
			if (sonX + 1 > 3 )
			{
				printError();
				system("pause");
				system("cls");
				continue;
			}
			flag = true;
			vis[sonX][sonY] = false;
			sonX += 1;
			vis[sonX][sonY] = true;
			system("cls");
		}
		else if (sonIng == 'a'|| sonIng == 'A')
		{
			if (sonY - 1 < 1 )
			{
				printError();
				system("pause");
				system("cls");
				continue;
			}
			flag = true;
			vis[sonX][sonY] = false;
			sonY -= 1;
			vis[sonX][sonY] = true;
			system("cls");
		}
		else if (sonIng == 'd' || sonIng=='D')
		{
			if (sonY + 1 > 3 )
			{
				printError();
				system("pause");
				system("cls");
				continue;
			}
			flag = true;
			vis[sonX][sonY] = false;
			sonY += 1;
			vis[sonX][sonY] = true;
			system("cls");
		}
		else if (sonIng == 'g' || sonIng == 'G')
		{
			if (tttSon[sonX][sonY])
			{
				printError();
				system("pause");
				system("cls");
				continue;
			}
			cnt++;
			tttSon[sonX][sonY] = true;
			vis[sonX][sonY] = false;
			flag = false;
			tttDesk[sonX][sonY] = son;
			if (son == 'O') son = 'X';
			else son = 'O';
			system("cls");
		}
		else
		{
			printError();
			system("pause");
			system("cls");
			continue;
		}
	}
}

void PrintGame()
{
	cout << "----------------------" << endl;
	cout << "----简略井字棋游戏----" << endl;
	cout << "----------------------" << endl;
	cout << "------游戏说明--------" << endl;
	cout << "---按下G键开始游戏----" << endl;
	cout << "--通过W键控制光标上移-" << endl;
	cout << "-通过S键控制光标下移--" << endl;
	cout << "--通过A键控制光标左移-" << endl;
	cout << "--通过D键控制光标右移-" << endl;
	cout << "------通过G键落子-----" << endl;
	cout << "----------------------" << endl;
	cout << "----------------------" << endl;
}

int main()
{
	char son = 'O';
	int  sonX = 1, sonY = 1;
	while (true)
	{
		char gameStart;
		PrintGame();
		cin >> gameStart;
		if (gameStart == 'G' || gameStart == 'g')
		{
			system("cls");
			break;
		}
		else
		{
			cout << "输入错误!!!,请重新输入" << endl;
			system("pause");
			system("cls");
		}
	}

	operatorDesk(sonX, sonY,son);
	if (!isEnd)
	{
		cout << "平局!!!" << endl;
	}
	return 0 ;
}

以上是关于C++ 井字棋的主要内容,如果未能解决你的问题,请参考以下文章

C++游戏game | 井字棋游戏坤坤版(配资源+视频)赋源码,双人对战

基于C++的井字棋小游戏(使用数组搭建)

(教你简单地C语言黑框框三子棋(井字棋)

井字棋算法

C语言实战小游戏:井字棋(三子棋)大战!文内含有源码

三子棋(井字棋)如何用C语言实现