五子棋人人对战C++代码实现
时间: 2023-08-24 17:09:53 浏览: 84
以下是一个简单的五子棋人人对战的 C++ 代码实现,仅供参考:
```c++
#include <iostream>
using namespace std;
const int ROWS = 15;
const int COLS = 15;
char board[ROWS][COLS]; // 棋盘
void init_board() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = '+';
}
}
}
void print_board() {
cout << " ";
for (int i = 0; i < COLS; i++) {
cout << i+1 << " ";
}
cout << endl;
for (int i = 0; i < ROWS; i++) {
cout << i+1 << " ";
for (int j = 0; j < COLS; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
bool is_valid_move(int row, int col) {
if (row < 0 || row >= ROWS || col < 0 || col >= COLS) {
return false;
}
if (board[row][col] != '+') {
return false;
}
return true;
}
bool is_win(int row, int col) {
char player = board[row][col];
int count = 0;
// 横向
for (int i = col-4; i <= col+4; i++) {
if (i < 0 || i >= COLS) {
continue;
}
if (board[row][i] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
// 竖向
count = 0;
for (int i = row-4; i <= row+4; i++) {
if (i < 0 || i >= ROWS) {
continue;
}
if (board[i][col] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
// 斜向1
count = 0;
for (int i = -4; i <= 4; i++) {
int r = row + i;
int c = col + i;
if (r < 0 || r >= ROWS || c < 0 || c >= COLS) {
continue;
}
if (board[r][c] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
// 斜向2
count = 0;
for (int i = -4; i <= 4; i++) {
int r = row + i;
int c = col - i;
if (r < 0 || r >= ROWS || c < 0 || c >= COLS) {
continue;
}
if (board[r][c] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
return false;
}
int main() {
init_board();
print_board();
int row, col;
char player = 'O';
while (true) {
cout << "Player " << player << ", enter row and column: ";
cin >> row >> col;
row--; // 从0开始计数
col--;
if (!is_valid_move(row, col)) {
cout << "Invalid move, try again." << endl;
continue;
}
board[row][col] = player;
print_board();
if (is_win(row, col)) {
cout << "Player " << player << " wins!" << endl;
break;
}
// 切换玩家
if (player == 'O') {
player = 'X';
} else {
player = 'O';
}
}
return 0;
}
```
这个代码实现了以下功能:
- 初始化棋盘
- 打印棋盘
- 判断落子是否合法
- 判断是否获胜
- 交替落子
你可以根据自己的需要进行修改和扩展。
阅读全文