写一个c++的五子棋代码
时间: 2024-03-17 19:46:35 浏览: 60
C++ 五子棋代码
以下是一个基本的C++五子棋代码:
```c++
#include <iostream>
using namespace std;
const int ROW = 15;
const int COL = 15;
char board[ROW][COL]; // 棋盘
void initBoard() // 初始化棋盘
{
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
board[i][j] = '+';
}
}
}
void drawBoard() // 画出棋盘
{
cout << " ";
for (int i = 0; i < COL; i++) {
cout << i << " ";
}
cout << endl;
for (int i = 0; i < ROW; i++) {
cout << i << " ";
for (int j = 0; j < COL; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
bool isWin(char player) // 判断是否胜利
{
// 判断行
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL - 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 < ROW - 4; i++) {
for (int j = 0; j < COL; 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 < ROW - 4; i++) {
for (int j = 0; j < COL - 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 < ROW; i++) {
for (int j = 0; j < COL - 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;
}
int main()
{
initBoard();
drawBoard();
char player = 'X'; // 先手为X
int row, col;
while (true) {
cout << "请输入下棋的位置,用空格分隔,例如:3 4" << endl;
cin >> row >> col;
if (row >= 0 && row < ROW && col >= 0 && col < COL && board[row][col] == '+') {
board[row][col] = player;
drawBoard();
if (isWin(player)) {
cout << "恭喜" << player << "获胜!" << endl;
break;
}
player = (player == 'X') ? 'O' : 'X'; // 交换先手
} else {
cout << "输入无效,请重新输入!" << endl;
}
}
return 0;
}
```
这个代码实现了五子棋的基本功能,包括初始化棋盘、画出棋盘、下棋、判断胜利等等。当然,这只是一个基本的实现,还有很多可以改进的地方,比如加入人机对战、增加界面等等。
阅读全文