c++五子棋人机大战代码实现
时间: 2023-08-03 15:17:44 浏览: 64
以下是一个简单的C++五子棋人机大战代码实现,使用了基本的alpha-beta剪枝算法来提高电脑的下棋效率。
```
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 15;
const int INF = 0x3f3f3f3f;
int map[MAXN][MAXN], ansx, ansy, depth = 5, Max = -INF, Min = INF;
// 判断棋子是否在边界内
bool check(int x, int y) {
if(x < 1 || x > 15 || y < 1 || y > 15)
return false;
return true;
}
// 评估函数,计算当前局面得分
int evaluate() {
int sum = 0;
for(int i = 1; i <= 15; i++) {
for(int j = 1; j <= 15; j++) {
if(map[i][j] == 1) {
int cnt = 1;
while(check(i, j + cnt) && map[i][j + cnt] == 1) cnt++;
if(check(i, j + cnt) && map[i][j + cnt] == 0) sum += cnt;
cnt = 1;
while(check(i + cnt, j) && map[i + cnt][j] == 1) cnt++;
if(check(i + cnt, j) && map[i + cnt][j] == 0) sum += cnt;
cnt = 1;
while(check(i + cnt, j + cnt) && map[i + cnt][j + cnt] == 1) cnt++;
if(check(i + cnt, j + cnt) && map[i + cnt][j + cnt] == 0) sum += cnt;
cnt = 1;
while(check(i - cnt, j + cnt) && map[i - cnt][j + cnt] == 1) cnt++;
if(check(i - cnt, j + cnt) && map[i - cnt][j + cnt] == 0) sum += cnt;
}
if(map[i][j] == 2) {
int cnt = 1;
while(check(i, j + cnt) && map[i][j + cnt] == 2) cnt++;
if(check(i, j + cnt) && map[i][j + cnt] == 0) sum -= cnt;
cnt = 1;
while(check(i + cnt, j) && map[i + cnt][j] == 2) cnt++;
if(check(i + cnt, j) && map[i + cnt][j] == 0) sum -= cnt;
cnt = 1;
while(check(i + cnt, j + cnt) && map[i + cnt][j + cnt] == 2) cnt++;
if(check(i + cnt, j + cnt) && map[i + cnt][j + cnt] == 0) sum -= cnt;
cnt = 1;
while(check(i - cnt, j + cnt) && map[i - cnt][j + cnt] == 2) cnt++;
if(check(i - cnt, j + cnt) && map[i - cnt][j + cnt] == 0) sum -= cnt;
}
}
}
return sum;
}
// alpha-beta剪枝算法
int dfs(int depth, int alpha, int beta) {
if(depth == 0)
return evaluate();
for(int i = 1; i <= 15; i++) {
for(int j = 1; j <= 15; j++) {
if(map[i][j] == 0) {
map[i][j] = 1;
int tmp = evaluate();
if(tmp > Max) {
Max = tmp;
ansx = i;
ansy = j;
}
alpha = max(alpha, dfs(depth - 1, alpha, beta));
map[i][j] = 0;
if(alpha >= beta)
return alpha;
}
}
}
return alpha;
}
int main() {
memset(map, 0, sizeof(map));
int x, y;
cout << "请输入您的先后手:(1 为先手,2 为后手)" << endl;
int player;
cin >> player;
if(player == 1) {
cout << "请输入您的落子坐标:" << endl;
cin >> x >> y;
map[x][y] = 2;
}
while(true) {
// 电脑落子
dfs(depth, -INF, INF);
map[ansx][ansy] = 1;
cout << "电脑落子坐标:" << ansx << " " << ansy << endl;
// 判断是否胜利
int res = evaluate();
if(res >= 10000) {
cout << "电脑胜利!" << endl;
break;
}
// 玩家落子
cout << "请输入您的落子坐标:" << endl;
cin >> x >> y;
map[x][y] = 2;
// 判断是否胜利
res = evaluate();
if(res <= -10000) {
cout << "玩家胜利!" << endl;
break;
}
}
return 0;
}
```
注意:本代码仅为基础实现,还有很多可以进行优化的地方,例如加入禁手判断等。