C++控制台实现简单人机对弈井字棋
本文实例为大家分享了c++实现简单人机对弈井字棋的具体代码,供大家参考,具体内容如下
main.cpp
#include"TicTacToe.h"
int main()
{
Game game;
game.getWinner();
return 0;
}
TicTacToe.h
#pragma once
#include<iOStream>
using namespace std;
#include<array>
#include<ctime>
class Game
{
public:
Game();
void print();
char getCurrentPlayer();
void getWinner();
bool isDone(int row,int col);
void makeMove();
void computer_move(int row, int col);
protected:
array <array< char, 3 >, 3 > board;
int row;
int col;
};
TicTacToe.cpp
#include"TicTacToe.h"
Game::Game()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
board[i][j] = '-';
}
}
this->col = 3;
this->row = 3;
}
void Game::print()
{
cout << "\t1\t2\t3\n";
for (int i = 0; i < 3; i++)
{
cout << i + 1;
for (int j = 0; j < 3; j++)
{
cout << "\t";
cout << board[i][j];
}
cout << endl;
}
}
char Game::getCurrentPlayer()
{
int i = 0;
for (; i < 3; i++)//判断第i行是否全都相同
{
if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != '-')
return board[i][0];//将第i行的内容返回
}
for (i = 0; i < 3; i++)//判断第i列是否全都相同
{
if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != '-')
return board[0][i];//将第i列的内容返回
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != '-')//判断捺对角线(\)的内容是否全都相同
return board[0][0];
else if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != '-')//判断撇对角线(/)的内容是否全都相同
return board[0][2];
else if (isDone(row,col))//判断是否是平局,如果是平局返回‘q'
return 'q';
else //判断是否还未产生游戏结果,如果还未产生游戏结果返回‘-'
return '-';
}
void Game::getWinner()
{
char a;
do
{
print(); //屏幕上打印一个棋盘
makeMove(); //打印出棋盘之后,玩家开始下棋
a = getCurrentPlayer(); //玩家下完棋后,开始判断游戏结果
if (a != '-') // ‘-':没人赢
{
break; //如果已经分出胜负,跳出循环
}
computer_move(row,col); //如果没有分出胜负,电脑下棋
a = getCurrentPlayer(); //下完之后判断游戏结果
} while (a == '-');
if (a == 'X') //判断玩家是否获胜:‘x'代表玩家获胜
printf("Congratulations,you win!\n");
else if (a == 'O') //判断玩家是否获胜:‘o'代表电脑获胜
printf("It's too bad,you lose!\n");
else //判断是否是平局
printf("Draw!\n");
}
bool Game::isDone(int row,int col)
{
//判断数组当中每一个元素是否有'-',如果有'-',说明没有满,返回0;否则返回1
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
if (board[i][j] == '-') //判断是否有'-'
return 0; //有'-'返回0
}
return 1; //没有'-'返回1
}
void Game::makeMove()
{
int x, y;//先定义两个变量,以便接收玩家下棋的坐标
do
{
printf("Please input your coordinate:(x,y)!");//提示玩家下棋
scanf("%d%d", &x, &y); //接收玩家所下的位置
if (x >= 1 && x <= 3 && y >= 1 && y <= 3) //判断玩家输入坐标是否有误
if (board[x - 1][y - 1] == '-') //判断玩家输入的位置是否已经被占
{
board[x - 1][y - 1] = 'X'; //将玩家输入的位置用‘x'占用
break;
}
else//玩家输入位置被占,提示玩家重新输入位置
printf("Error!This place was be used!\n");
else//玩家输入坐标有误,直接提示玩家error
printf("Error!");
} while (1);
}
void Game::computer_move(int row,int col)
{
srand((unsigned long)time(NULL));//利用函数生成随机数
do
{
int x = rand() % row;//控制随机数小于3并把结果赋给横坐标
int y = rand() % col;//控制随机数小于3并把结果赋给纵坐标
if (board[x][y] == '-')//判断电脑选择的位置是否被占
{
board[x][y] = 'O';//将电脑下棋的位置用‘O'占用
break;
}
} while (1);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
相关文章