感谢支持,欢迎评论
后续更新单人版。
尽情期待《c++蒟蒻五子棋2.0单人版》
#include <iostream>
#include <limits>
using namespace std;
const int BOARD_SIZE = 15;
char board[BOARD_SIZE][BOARD_SIZE];
// 初始化棋盘
void initBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = '-';
}
}
}
// 显示棋盘
void displayBoard() {
system("cls");
// 打印列号
cout << " ";
for (int j = 0; j < BOARD_SIZE; j++) {
printf("%2d ", j + 1);
}
cout << "\n";
// 打印棋盘内容
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%2d ", i + 1);
for (int j = 0; j < BOARD_SIZE; j++) {
cout << " " << board[i][j] << " ";
}
cout << "\n";
}
}
// 检查胜利条件
bool checkWin(int x, int y) {
char current = board[x][y];
int count;
// 检查水平方向
count = 1;
for (int j = y - 1; j >= 0 && board[x][j] == current; j--) count++;
for (int j = y + 1; j < BOARD_SIZE && board[x][j] == current; j++) count++;
if (count >= 5) return true;
// 检查垂直方向
count = 1;
for (int i = x - 1; i >= 0 && board[i][y] == current; i--) count++;
for (int i = x + 1; i < BOARD_SIZE && board[i][y] == current; i++) count++;
if (count >= 5) return true;
// 检查主对角线
count = 1;
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i][j] == current; i--, j--) count++;
for (int i = x + 1, j = y + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == current; i++, j++) count++;
if (count >= 5) return true;
// 检查副对角线
count = 1;
for (int i = x - 1, j = y + 1; i >= 0 && j < BOARD_SIZE && board[i][j] == current; i--, j++) count++;
for (int i = x + 1, j = y - 1; i < BOARD_SIZE && j >= 0 && board[i][j] == current; i++, j--) count++;
return count >= 5;
}
// 检查平局
bool checkDraw() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == '-') return false;
}
}
return true;
}
int main() {
initBoard();
char currentPlayer = 'X';
bool gameOver = false;
while (!gameOver) {
displayBoard();
int row, col;
bool valid = false;
while (!valid) {
cout << "玩家 " << currentPlayer << ",请输入行列号(1-15):";
if (!(cin >> row >> col)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "输入格式错误,请重新输入!\n";
continue;
}
if (row < 1 || row > BOARD_SIZE || col < 1 || col > BOARD_SIZE) {
cout << "输入超出范围,请重新输入!\n";
continue;
}
row--;
col--;
if (board[row][col] != '-') {
cout << "该位置已有棋子,请重新输入!\n";
} else {
valid = true;
}
}
board[row][col] = currentPlayer;
if (checkWin(row, col)) {
displayBoard();
cout << "恭喜玩家 " << currentPlayer << " 获胜!\n";
gameOver = true;
} else if (checkDraw()) {
displayBoard();
cout << "游戏结束,平局!\n";
gameOver = true;
} else {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}
return 0;
}