写一段五子棋AI的C++代码
时间: 2024-05-30 10:14:51 浏览: 90
C++实现五子棋游戏(带AI)
4星 · 用户满意度95%
五子棋AI的C代码可以这样写:#include <stdio.h>int board[9][9]; // 棋盘// 初始化棋盘
void init_board() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
board[i][j] = 0;
}
}
}// 下棋
void put_chess(int row, int col, int player) {
board[row][col] = player;
}// 检查胜负
int check_winner(int player) {
// 检查横向
for (int i = 0; i < 9; i++) {
int count = 0;
for (int j = 0; j < 9; j++) {
if (board[i][j] == player) {
count++;
}
if (count == 5) {
return 1;
}
}
}
// 检查纵向
for (int j = 0; j < 9; j++) {
int count = 0;
for (int i = 0; i < 9; i++) {
if (board[i][j] == player) {
count++;
}
if (count == 5) {
return 1;
}
}
}
// 检查对角线
for (int i = 0; i < 9; i++) {
int count = 0;
for (int j = 0; j < 9; j++) {
if (board[i][j] == player) {
count++;
}
if (count == 5) {
return 1;
}
}
}
// 检查反对角线
for (int i = 0; i < 9; i++) {
int count = 0;
for (int j = 8; j >= 0; j--) {
if (board[i][j] == player) {
count++;
}
if (count == 5) {
return 1;
}
}
}
return 0;
}int main() {
// 初始化棋盘
init_board();
// 游戏循环
while (1) {
// 玩家1下棋
int row, col;
printf("玩家1请落子:");
scanf("%d %d", &row, &col);
put_chess(row, col, 1);
// 检查胜负
if (check_winner(1)) {
printf("玩家1赢了!\n");
break;
}
// 玩家2下棋
printf("玩家2请落子:");
scanf("%d %d", &row, &col);
put_chess(row, col, 2);
// 检查胜负
if (check_winner(2)) {
printf("玩家2赢了!\n");
break;
}
}
return 0;
}
阅读全文