五子棋C++人人对战代码
时间: 2023-09-02 20:15:54 浏览: 156
以下是一个简单的五子棋C++人人对战代码,使用了字符数组来表示棋盘:
```c++
#include <iostream>
#include <cstring>
using namespace std;
const int BOARD_SIZE = 15; // 棋盘大小
char board[BOARD_SIZE][BOARD_SIZE]; // 棋盘
void printBoard() { // 打印棋盘
cout << " ";
for (int i = 0; i < BOARD_SIZE; i++) {
cout << " " << i + 1;
}
cout << endl;
for (int i = 0; i < BOARD_SIZE; i++) {
cout << i + 1 << " ";
for (int j = 0; j < BOARD_SIZE; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
bool checkWin(int row, int col, char player) { // 判断胜负
int count = 0;
for (int i = row; i >= 0; i--) { // 竖直向上
if (board[i][col] == player) {
count++;
} else {
break;
}
}
for (int i = row + 1; i < BOARD_SIZE; i++) { // 竖直向下
if (board[i][col] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
count = 0;
for (int j = col; j >= 0; j--) { // 水平向左
if (board[row][j] == player) {
count++;
} else {
break;
}
}
for (int j = col + 1; j < BOARD_SIZE; j++) { // 水平向右
if (board[row][j] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
count = 0;
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { // 左上到右下
if (board[i][j] == player) {
count++;
} else {
break;
}
}
for (int i = row + 1, j = col + 1; i < BOARD_SIZE && j < BOARD_SIZE; i++, j++) { // 左上到右下
if (board[i][j] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
count = 0;
for (int i = row, j = col; i >= 0 && j < BOARD_SIZE; i--, j++) { // 右上到左下
if (board[i][j] == player) {
count++;
} else {
break;
}
}
for (int i = row + 1, j = col - 1; i < BOARD_SIZE && j >= 0; i++, j--) { // 右上到左下
if (board[i][j] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
return false;
}
int main() {
memset(board, '.', sizeof(board)); // 初始化棋盘
printBoard();
char player1 = 'X'; // 玩家1
char player2 = 'O'; // 玩家2
char currentPlayer = player1; // 当前玩家
int row, col;
while (true) {
cout << "请 " << currentPlayer << " 下棋(输入行号和列号,以空格分隔):" << endl;
cin >> row >> col;
row--;
col--;
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
cout << "输入错误,请重新输入!" << endl;
continue;
}
if (board[row][col] != '.') {
cout << "该位置已有棋子,请重新输入!" << endl;
continue;
}
board[row][col] = currentPlayer;
printBoard();
if (checkWin(row, col, currentPlayer)) {
cout << currentPlayer << " 获胜!" << endl;
break;
}
if (currentPlayer == player1) {
currentPlayer = player2;
} else {
currentPlayer = player1;
}
}
return 0;
}
```
该代码实现了基本的下棋、打印棋盘和判断胜负功能,可以作为五子棋C++人人对战的参考。
阅读全文