用c++做个五子棋,人机对战
时间: 2023-09-03 09:06:52 浏览: 72
好的,以下是一个简单的五子棋人机对战的 C++ 代码,供您参考:
```c++
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int ROW = 15;
const int COL = 15;
char board[ROW][COL]; // 棋盘
char player = 'X'; // 玩家棋子
char computer = 'O'; // 电脑棋子
// 初始化棋盘
void InitBoard()
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
board[i][j] = '+';
}
}
}
// 显示棋盘
void DisplayBoard()
{
cout << " ";
for (int i = 0; i < COL; i++)
{
cout << " " << i + 1;
}
cout << endl;
for (int i = 0; i < ROW; i++)
{
cout << i + 1 << " ";
for (int j = 0; j < COL; j++)
{
cout << board[i][j] << " ";
}
cout << endl;
}
}
// 玩家下棋
void PlayerMove()
{
int x, y;
cout << "请输入你要下棋的位置(行 列):";
cin >> x >> y;
while (x < 1 || x > ROW || y < 1 || y > COL || board[x - 1][y - 1] != '+')
{
cout << "输入有误,请重新输入:";
cin >> x >> y;
}
board[x - 1][y - 1] = player;
}
// 电脑下棋
void ComputerMove()
{
int x, y;
srand((unsigned)time(NULL));
do
{
x = rand() % ROW;
y = rand() % COL;
} while (board[x][y] != '+');
board[x][y] = computer;
}
// 判断游戏是否结束
bool IsGameOver()
{
// 横向判断
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL - 4; j++)
{
if (board[i][j] != '+' && board[i][j] == board[i][j + 1] && board[i][j] == board[i][j + 2] && board[i][j] == board[i][j + 3] && board[i][j] == board[i][j + 4])
{
return true;
}
}
}
// 纵向判断
for (int i = 0; i < ROW - 4; i++)
{
for (int j = 0; j < COL; j++)
{
if (board[i][j] != '+' && board[i][j] == board[i + 1][j] && board[i][j] == board[i + 2][j] && board[i][j] == board[i + 3][j] && board[i][j] == board[i + 4][j])
{
return true;
}
}
}
// 左上到右下斜向判断
for (int i = 0; i < ROW - 4; i++)
{
for (int j = 0; j < COL - 4; j++)
{
if (board[i][j] != '+' && board[i][j] == board[i + 1][j + 1] && board[i][j] == board[i + 2][j + 2] && board[i][j] == board[i + 3][j + 3] && board[i][j] == board[i + 4][j + 4])
{
return true;
}
}
}
// 右上到左下斜向判断
for (int i = 0; i < ROW - 4; i++)
{
for (int j = 4; j < COL; j++)
{
if (board[i][j] != '+' && board[i][j] == board[i + 1][j - 1] && board[i][j] == board[i + 2][j - 2] && board[i][j] == board[i + 3][j - 3] && board[i][j] == board[i + 4][j - 4])
{
return true;
}
}
}
// 棋盘已满,平局
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
if (board[i][j] == '+')
{
return false;
}
}
}
return true;
}
int main()
{
InitBoard(); // 初始化棋盘
while (!IsGameOver())
{
DisplayBoard(); // 显示棋盘
PlayerMove(); // 玩家下棋
if (IsGameOver())
{
break;
}
ComputerMove(); // 电脑下棋
}
DisplayBoard(); // 显示最终棋盘
if (IsGameOver())
{
cout << "游戏结束!";
if (player == board[0][0])
{
cout << "玩家胜利!";
}
else if (computer == board[0][0])
{
cout << "电脑胜利!";
}
else
{
cout << "平局!";
}
}
return 0;
}
```
以上是一个简单的五子棋人机对战的 C++ 代码,其中包括棋盘的初始化、显示、玩家和电脑下棋、游戏是否结束的判断等功能。您可以根据需要进行修改和扩展。
阅读全文