闲暇之余自己写的一个C++三子棋小游戏,分享给大家!
#include <iostream>
#define Chess char *
using namespace std;
void DrawBoard(Chess chess)
{
cout << "-------------" << endl;
cout << "| " << chess[0] << " | " << chess[1] << " | " << chess[2] << " |" << endl;
cout << "|-----------|" << endl;
cout << "| " << chess[3] << " | " << chess[4] << " | " << chess[5] << " |" << endl;
cout << "|-----------|" << endl;
cout << "| " << chess[6] << " | " << chess[7] << " | " << chess[8] << " |" << endl;
cout << "-------------" << endl;
}
bool IsWin(Chess chess, char letter)
{
return (chess[0] == letter && chess[1] == letter && chess[2] == letter) ||
(chess[3] == letter && chess[4] == letter && chess[5] == letter) ||
(chess[6] == letter && chess[7] == letter && chess[8] == letter) ||
(chess[6] == letter && chess[3] == letter && chess[0] == letter) ||
(chess[7] == letter && chess[4] == letter && chess[1] == letter) ||
(chess[8] == letter && chess[5] == letter && chess[2] == letter) ||
(chess[6] == letter && chess[4] == letter && chess[2] == letter) ||
(chess[8] == letter && chess[4] == letter && chess[0] == letter);
}
bool IsFull(Chess chess, int index)
{
return chess[index] != ' ';
}
bool IsFullAll(Chess chess)
{
return (IsFull(chess, 0) && IsFull(chess, 1) && IsFull(chess, 2) &&
IsFull(chess, 3) && IsFull(chess, 4) && IsFull(chess, 5) &&
IsFull(chess, 6) && IsFull(chess, 7) && IsFull(chess, 8));
}
int AI(Chess chess)
{
for (int i = 0; i <= 8; i++)
{
if (!IsFull(chess, i))
{
chess[i] = 'O';
if (IsWin(chess, 'O'))
return i;
chess[i] = 'X';
if (IsWin(chess, 'X'))
return i;
chess[i] = ' ';
}
}
for (int i = 0; i <= 8; i++)
{
if (!IsFull(chess, i))
{
return i;
}
}
return -1;
}
int PlayerInput(Chess chess)
{
int input;
do
{
cout << "please input a number" << endl;
cin >> input;
} while (IsFull(chess, input - 1) && !input <= 9 && !input >= 1);
return input;
}
int main(void)
{
char chessBoard[] = { ' ', ' ', ' ',
' ', ' ', ' ',
' ', ' ', ' '};
char chessInputBoard[] = { '1', '2', '3',
'4', '5', '6',
'7', '8', '9'};
int input;
cout << "Game begin" << endl;
cout << "You go first" << endl;
for (;;)
{
DrawBoard(chessInputBoard);
int in = PlayerInput(chessBoard);
chessBoard[in - 1] = 'X';
chessInputBoard[in - 1] = 'X';
DrawBoard(chessBoard);
if (IsFullAll(chessBoard))
{
cout << "The game is full" << endl;
break;
}
if (IsWin(chessBoard, 'X'))
{
cout << "You win!" << endl;
break;
}
cout << "The computer go" << endl;
int ai = AI(chessBoard);
chessBoard[ai] = 'O';
chessInputBoard[ai] = 'O';
DrawBoard(chessBoard);
if (IsFullAll(chessBoard))
{
cout << "The game is full" << endl;
break;
}
if (IsWin(chessBoard, 'O'))
{
cout << "Computer win!" << endl;
break;
}
cout << "It's your turn" << endl;
}
cout<<"The game is over"<<endl;
cout<<"Thank you for your play"<<endl;
return 0;
}