博弈树搜索算法五子棋代码
时间: 2024-04-30 07:15:31 浏览: 137
博弈树搜索算法是一种用于解决博弈问题的算法,其中五子棋是一个常见的应用场景。下面是一个基于博弈树搜索算法的五子棋代码示例:
```cpp
#include <iostream>
#include <vector>
const int BOARD_SIZE = 15;
const int WIN_COUNT = 5;
enum class Player {
NONE,
BLACK,
WHITE
};
struct Move {
int row;
int col;
};
class Game {
public:
Game() : currentPlayer(Player::BLACK) {
board.resize(BOARD_SIZE, std::vector<Player>(BOARD_SIZE, Player::NONE));
}
void makeMove(const Move& move) {
board[move.row][move.col] = currentPlayer;
currentPlayer = (currentPlayer == Player::BLACK) ? Player::WHITE : Player::BLACK;
}
bool isGameOver() const {
return checkWin() || isBoardFull();
}
Player getWinner() const {
return winner;
}
private:
std::vector<std::vector<Player>> board;
Player currentPlayer;
Player winner;
bool checkWin() {
// 检查行
for (int row = 0; row < BOARD_SIZE; row++) {
for (int col = 0; col <= BOARD_SIZE - WIN_COUNT; col++) {
if (board[row][col] != Player::NONE) {
bool win = true;
for (int i = 1; i < WIN_COUNT; i++) {
if (board[row][col + i] != board[row][col]) {
win = false;
break;
}
}
if (win) {
winner = board[row][col];
return true;
}
}
}
}
// 检查列
for (int col = 0; col < BOARD_SIZE; col++) {
for (int row = 0; row <= BOARD_SIZE - WIN_COUNT; row++) {
if (board[row][col] != Player::NONE) {
bool win = true;
for (int i = 1; i < WIN_COUNT; i++) {
if (board[row + i][col] != board[row][col]) {
win = false;
break;
}
}
if (win) {
winner = board[row][col];
return true;
}
}
}
}
// 检查对角线
for (int row = 0; row <= BOARD_SIZE - WIN_COUNT; row++) {
for (int col = 0; col <= BOARD_SIZE - WIN_COUNT; col++) {
if (board[row][col] != Player::NONE) {
bool win = true;
for (int i = 1; i < WIN_COUNT; i++) {
if (board[row + i][col + i] != board[row][col]) {
win = false;
break;
}
}
if (win) {
winner = board[row][col];
return true;
}
}
}
}
// 检查反对角线
for (int row = WIN_COUNT - 1; row < BOARD_SIZE; row++) {
for (int col = 0; col <= BOARD_SIZE - WIN_COUNT; col++) {
if (board[row][col] != Player::NONE) {
bool win = true;
for (int i = 1; i < WIN_COUNT; i++) {
if (board[row - i][col + i] != board[row][col]) {
win = false;
break;
}
}
if (win) {
winner = board[row][col];
return true;
}
}
}
}
return false;
}
bool isBoardFull() const {
for (int row = 0; row < BOARD_SIZE; row++) {
for (int col = 0; col < BOARD_SIZE; col++) {
if (board[row][col] == Player::NONE) {
return false;
}
}
}
return true;
}
};
int main() {
Game game;
// 玩家输入示例
while (!game.isGameOver()) {
int row, col;
std::cout << "请输入下棋位置的行和列(以空格分隔):";
std::cin >> row >> col;
Move move{row, col};
game.makeMove(move);
}
// 游戏结束后输出结果
Player winner = game.getWinner();
if (winner == Player::BLACK) {
std::cout << "黑方获胜!" << std::endl;
} else if (winner == Player::WHITE) {
std::cout << "白方获胜!" << std::endl;
} else {
std::cout << "平局!" << std::endl;
}
return 0;
}
```
这段代码实现了一个简单的五子棋游戏,使用了博弈树搜索算法来判断胜负。玩家通过输入行和列来下棋,游戏会判断是否有一方获胜或者平局,并输出结果。
阅读全文