C++实现井字棋

源码:

 

#include 
#include 
#include 

using namespace std;

enum players{Computer,Human,Draw,None
};

const int iWin[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}};

class qz
{
	public:
		qz();
		void play();
		
	private:
    	int _p;//计数器,用来判断当前的玩家是谁
		int _field[9];//格子状态
		void reset();
		void drawGrid();
		int checkVictory();
		void getHumanMove();
		void getComputerMove();
};

qz::qz(void)
{
	_p = rand()%2;
	
	reset();
}

void qz::play(void)
{
	int res = Draw;//res表结果
	while(true)
	{
		drawGrid();//棋盘
		
		while(true)
		{
			if( _p ) getHumanMove(); // _ p = = 1 则人类玩家先走
			else getComputerMove();
			
			drawGrid();//更新棋盘
            res = checkVictory();//判断输赢
            
            if(res != None) //如果当前棋局状态已定输赢,跳出内循环
				   break;
				   
			++_p %=2;//未定输赢则计数器加一,让对手走
		}
		
		if(res == Human )
		{
			cout<<"CONGRATULATIONS HUMAN --- You won!"<>r;
		
		if(r != "Y" && r != "y")
			 return ;
			 
		++_p %= 2;//如果输入了Y or y ,则计数器加一
		
		reset();//重置棋局
	}
}

void qz::reset(void)
{
	for(int x=0;x<9;x++)
	{
		_field[x]=None;
	}
}

void qz::drawGrid()
{
	system("cls");
	COORD c = {0,2};
	SetConsoleCursorPosition(GetStdHandle( STD_OUTPUT_HANDLE ), c);
	//cout<<"-----------" <>m;
		if( _field[m-1] != None)
			cout<<"Invalid move . Try again!" <

你可能感兴趣的:(C++面向对象)