#include <iostream>
#include <iomanip>
// 定义棋盘大小
const int BOARD_SIZE = 3;
// 打印棋盘
void printBoard(char board[][BOARD_SIZE]) {
std::cout << " 0 1 2\n";
for (int i = 0; i < BOARD_SIZE; ++i) {
std::cout << i << " ";
for (int j = 0; j < BOARD_SIZE; ++j) {
std::cout << board[i][j] << " ";
}
std::cout << "\n";
}
}
// 检查是否有玩家获胜
bool checkWin(char board[][BOARD_SIZE], char player) {
// 检查行
for (int i = 0; i < BOARD_SIZE; ++i) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
return true;
}
}
// 检查列
for (int j = 0; j < BOARD_SIZE; ++j) {
if (board[0][j] == player && board[1][j] == player && board[2][j] == player) {
return true;
}
}
// 检查对角线
if (board[0][0] == player && board[1][1] == player && board[2][2] == player) {
return true;
}
if (board[0][2] == player && board[1][1] == player && board[2][0] == player) {
return true;
}
return false;
}
// 检查棋盘是否已满(平局)
bool isBoardFull(char board[][BOARD_SIZE]) {
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() {
char board[BOARD_SIZE][BOARD_SIZE];
// 初始化棋盘
for (int i = 0; i < BOARD_SIZE; ++i) {
for (int j = 0; j < BOARD_SIZE; ++j) {
board[i][j] =' ';
}
}
char currentPlayer = 'X';
bool gameOver = false;
std::cout << "井字棋游戏开始!\n";
printBoard(board);
while (!gameOver) {
int row, col;
std::cout << "玩家 " << currentPlayer << ",请输入你的下棋位置(行 列):";
std::cin >> row >> col;
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE || board[row][col]!=' ') {
std::cout << "无效的位置,请重新输入!\n";
continue;
}
board[row][col] = currentPlayer;
if (checkWin(board, currentPlayer)) {
std::cout << "玩家 " << currentPlayer << " 获胜!\n";
gameOver = true;
} else if (isBoardFull(board)) {
std::cout << "平局!\n";
gameOver = true;
} else {
currentPlayer = (currentPlayer == 'X')? 'O' : 'X';
}
printBoard(board);
}
return 0;
}