请用c++给我写一个五子棋游戏的程序
时间: 2023-11-27 14:03:44 浏览: 75
好的,以下是一个简单的五子棋游戏程序示例,希望对你有帮助:
```c++
#include <iostream>
using namespace std;
const int SIZE = 15; // 棋盘大小
const int BLACK = 1; // 黑子
const int WHITE = 2; // 白子
int board[SIZE][SIZE] = {0}; // 棋盘,0表示空,1表示黑子,2表示白子
// 初始化棋盘
void initBoard()
{
for(int i = 0; i < SIZE; i++)
{
for(int j = 0; j < SIZE; j++)
{
board[i][j] = 0;
}
}
}
// 绘制棋盘
void drawBoard()
{
cout << " ";
for(int i = 0; i < SIZE; i++)
{
cout << i << " ";
}
cout << endl;
for(int i = 0; i < SIZE; i++)
{
cout << i << " ";
for(int j = 0; j < SIZE; j++)
{
if(board[i][j] == BLACK)
{
cout << "● ";
}
else if(board[i][j] == WHITE)
{
cout << "○ ";
}
else
{
cout << "+ ";
}
}
cout << endl;
}
}
// 判断是否有人获胜
bool checkWin(int player)
{
// 横向判断
for(int i = 0; i < SIZE; i++)
{
for(int j = 0; j < SIZE - 4; j++)
{
if(board[i][j] == player && board[i][j + 1] == player && board[i][j + 2] == player && board[i][j + 3] == player && board[i][j + 4] == player)
{
return true;
}
}
}
// 纵向判断
for(int i = 0; i < SIZE - 4; i++)
{
for(int j = 0; j < SIZE; j++)
{
if(board[i][j] == player && board[i + 1][j] == player && board[i + 2][j] == player && board[i + 3][j] == player && board[i + 4][j] == player)
{
return true;
}
}
}
// 左上到右下斜向判断
for(int i = 0; i < SIZE - 4; i++)
{
for(int j = 0; j < SIZE - 4; j++)
{
if(board[i][j] == player && board[i + 1][j + 1] == player && board[i + 2][j + 2] == player && board[i + 3][j + 3] == player && board[i + 4][j + 4] == player)
{
return true;
}
}
}
// 右上到左下斜向判断
for(int i = 4; i < SIZE; i++)
{
for(int j = 0; j < SIZE - 4; j++)
{
if(board[i][j] == player && board[i - 1][j + 1] == player && board[i - 2][j + 2] == player && board[i - 3][j + 3] == player && board[i - 4][j + 4] == player)
{
return true;
}
}
}
return false;
}
// 判断是否平局
bool checkTie()
{
for(int i = 0; i < SIZE; i++)
{
for(int j = 0; j < SIZE; j++)
{
if(board[i][j] == 0)
{
return false;
}
}
}
return true;
}
int main()
{
int player = BLACK; // 当前玩家,默认黑子先行
initBoard(); // 初始化棋盘
while(true)
{
drawBoard(); // 绘制棋盘
int x, y;
cout << "请 " << (player == BLACK ? "黑" : "白") << " 子下棋(输入x,y坐标,以空格分隔):" << endl;
cin >> x >> y;
if(x < 0 || x >= SIZE || y < 0 || y >= SIZE || board[x][y] != 0)
{
cout << "输入无效,请重新输入!" << endl;
continue;
}
board[x][y] = player; // 下棋
if(checkWin(player)) // 判断是否获胜
{
cout << (player == BLACK ? "黑" : "白") << "子获胜!" << endl;
break;
}
if(checkTie()) // 判断是否平局
{
cout << "平局!" << endl;
break;
}
player = (player == BLACK ? WHITE : BLACK); // 切换玩家
}
return 0;
}
```
这个程序只是一个简单的示例,可能还有一些不足之处,希望能够帮到你。
阅读全文