用c语言写一个五子棋人机对战程序
时间: 2023-09-18 18:13:56 浏览: 135
程序设计:基于AI的五子棋游戏软件,包含双人对战和人机对战。由C++及QT框架完成.zip
好的,下面是一个简单的五子棋人机对战程序的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 15
#define COL 15
char board[ROW][COL] = {' '}; // 棋盘
char human = 'X'; // 玩家执子
char computer = 'O'; // AI执子
// 打印棋盘
void print_board() {
printf(" ");
for (int i = 0; i < COL; i++) {
printf("%2d", i + 1);
}
printf("\n");
for (int i = 0; i < ROW; i++) {
printf("%2d", i + 1);
for (int j = 0; j < COL; j++) {
printf("%2c", board[i][j]);
}
printf("\n");
}
}
// 判断是否胜利
int is_win(char c) {
// 判断行
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL - 4; j++) {
if (board[i][j] == c && board[i][j + 1] == c && board[i][j + 2] == c && board[i][j + 3] == c && board[i][j + 4] == c) {
return 1;
}
}
}
// 判断列
for (int i = 0; i < ROW - 4; i++) {
for (int j = 0; j < COL; j++) {
if (board[i][j] == c && board[i + 1][j] == c && board[i + 2][j] == c && board[i + 3][j] == c && board[i + 4][j] == c) {
return 1;
}
}
}
// 判断正斜线
for (int i = 0; i < ROW - 4; i++) {
for (int j = 0; j < COL - 4; j++) {
if (board[i][j] == c && board[i + 1][j + 1] == c && board[i + 2][j + 2] == c && board[i + 3][j + 3] == c && board[i + 4][j + 4] == c) {
return 1;
}
}
}
// 判断反斜线
for (int i = 0; i < ROW - 4; i++) {
for (int j = 4; j < COL; j++) {
if (board[i][j] == c && board[i + 1][j - 1] == c && board[i + 2][j - 2] == c && board[i + 3][j - 3] == c && board[i + 4][j - 4] == c) {
return 1;
}
}
}
return 0;
}
// AI下棋
void computer_move() {
int x, y;
srand((unsigned int) time(NULL));
do {
x = rand() % ROW;
y = rand() % COL;
} while (board[x][y] != ' ');
board[x][y] = computer;
printf("AI下了(%d, %d)\n", x + 1, y + 1);
}
// 玩家下棋
void human_move() {
int x, y;
printf("请输入你的落子位置(x y): ");
scanf("%d %d", &x, &y);
while (x < 1 || x > ROW || y < 1 || y > COL || board[x - 1][y - 1] != ' ') {
printf("无效位置,请重新输入(x y): ");
scanf("%d %d", &x, &y);
}
board[x - 1][y - 1] = human;
}
int main() {
printf("欢迎来到五子棋人机对战游戏!\n");
printf("玩家执子:X, AI执子:O\n");
print_board();
while (1) {
human_move();
print_board();
if (is_win(human)) {
printf("你赢了!\n");
break;
}
computer_move();
print_board();
if (is_win(computer)) {
printf("AI赢了!\n");
break;
}
}
return 0;
}
```
这个程序实现了一个简单的五子棋人机对战,玩家执黑子,AI执白子。玩家通过输入坐标来下棋,AI则随机选择一个空位下棋。程序使用了一个双重循环来判断是否胜利,分别判断行、列、正斜线和反斜线。如果有五个相同的棋子相连,则判断为胜利。
阅读全文