#include <iostream>
#include <vector>
using namespace std;
const int BOARD_SIZE = 15;
enum class Player {
EMPTY,
BLACK,
WHITE
};
class Game {
private:
vector<vector<Player>> board;
Player currentPlayer;
public:
Game() : board(BOARD_SIZE, vector<Player>(BOARD_SIZE, Player::EMPTY)), currentPlayer(Player::BLACK) {}
void play() {
bool gameOver = false;
int row, col;
while (!gameOver) {
printBoard();
cout << "Player " << static_cast<int>(currentPlayer) << "'s turn. Enter row and column (0-14): ";
cin >> row >> col;
if (isValidMove(row, col)) {
board[row][col] = currentPlayer;
if (isWinningMove(row, col)) {
gameOver = true;
cout << "Player " << static_cast<int>(currentPlayer) << " wins!" << endl;
} else {
switchPlayer();
}
} else {
cout << "Invalid move. Try again." << endl;
}
}
}
private:
void printBoard() {
for (int row = 0; row < BOARD_SIZE; ++row) {
for (int col = 0; col < BOARD_SIZE; ++col) {
switch (board[row][col]) {
case Player::EMPTY:
cout << ".";
break;
case Player::BLACK:
cout << "X";
break;
case Player::WHITE:
cout << "O";
break;
}
cout << " ";
}
cout << endl;
}
}
bool isValidMove(int row, int col) {
return (row >= 0 && row < BOARD_SIZE) && (col >= 0 && col < BOARD_SIZE) && (board[row][col] == Player::EMPTY);
}
bool isWinningMove(int row, int col) {
Player player = currentPlayer;
// 检查行
int count = 1;
int i = col - 1;
while (i >= 0 && board[row][i] == player) {
count++;
i--;
}
i = col + 1;
while (i < BOARD_SIZE && board[row][i] == player) {
count++;
i++;
}
if (count >= 5) {
return true;
}
// 检查列
count = 1;
i = row - 1;
while (i >= 0 && board[i][col] == player) {
count++;
i--;
}
i = row + 1;
while (i < BOARD_SIZE && board[i][col] == player) {
count++;
i++;
}
if (count >= 5) {
return true;
}
// 检查主对角线
count = 1;
int j = col - 1;
i = row - 1;
while (i >= 0 && j >= 0 && board[i][j] == player) {
count++;
i--;
j--;
}
j = col + 1;
i = row + 1;
while (i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == player) {
count++;
i++;
j++;
}
if (count >= 5) {
return true;
}
// 检查副对角线
count = 1;
j = col - 1;
i = row + 1;
while (i < BOARD_SIZE && j >= 0 && board[i][j] == player) {
count++;
i++;
j--;
}
j = col + 1;
i = row - 1;
while (i >= 0 && j < BOARD_SIZE && board[i][j] == player) {
count++;
i--;
j++;
}
if (count >= 5) {
return true;
}
return false;
}
void switchPlayer() {
currentPlayer = (currentPlayer == Player::BLACK) ? Player::WHITE : Player::BLACK;
}
};
int main() {
Game game;
game.play();
return 0;
}
AI-c++小游戏-五子棋
于 2024-10-10 23:10:01 首次发布