五子棋c语言代码 人机
时间: 2023-12-12 14:35:40 浏览: 77
以下是一个简单的五子棋C语言代码,实现了人机对战的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 15
#define COL 15
#define PLAYER 1
#define COMPUTER 2
void init_board(int board[ROW][COL]) {
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
board[i][j] = 0;
}
}
}
void print_board(int board[ROW][COL]) {
int i, j;
printf(" ");
for (i = 0; i < COL; i++) {
printf("%d ", i);
}
printf("\n");
for (i = 0; i < ROW; i++) {
printf("%d ", i);
for (j = 0; j < COL; j++) {
if (board[i][j] == 0) {
printf("+ ");
} else if (board[i][j] == PLAYER) {
printf("O ");
} else if (board[i][j] == COMPUTER) {
printf("X ");
}
}
printf("\n");
}
}
int is_win(int board[ROW][COL], int player) {
int i, j, k;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
if (board[i][j] == player) {
for (k = 1; k < 5; k++) {
if (i + k < ROW && board[i + k][j] == player &&
i + k - 4 >= 0 && board[i + k - 1][j] == player &&
board[i + k - 2][j] == player && board[i + k - 3][j] == player) {
return 1;
}
if (j + k < COL && board[i][j + k] == player &&
j + k - 4 >= 0 && board[i][j + k - 1] == player &&
board[i][j + k - 2] == player && board[i][j + k - 3] == player) {
return 1;
}
if (i + k < ROW && j + k < COL && board[i + k][j + k] == player &&
i + k - 4 >= 0 && j + k - 4 >= 0 && board[i + k - 1][j + k - 1] == player &&
board[i + k - 2][j + k - 2] == player && board[i + k - 3][j + k - 3] == player) {
return 1;
}
if (i + k < ROW && j - k >= 0 && board[i + k][j - k] == player &&
i + k - 4 >= 0 && j - k + 4 < COL && board[i + k - 1][j - k + 1] == player &&
board[i + k - 2][j - k + 2] == player && board[i + k - 3][j - k + 3] == player) {
return 1;
}
}
}
}
}
return 0;
}
void player_move(int board[ROW][COL]) {
int x, y;
printf("请输入您的落子位置(x y): ");
scanf("%d %d", &x, &y);
while (board[x][y] != 0) {
printf("该位置已有棋子,请重新输入(x y): ");
scanf("%d %d", &x, &y);
}
board[x][y] = PLAYER;
}
void computer_move(int board[ROW][COL]) {
int x, y;
srand(time(NULL));
do {
x = rand() % ROW;
y = rand() % COL;
} while (board[x][y] != 0);
board[x][y] = COMPUTER;
printf("电脑落子位置: (%d %d)\n", x, y);
}
void game() {
int board[ROW][COL];
int player = PLAYER;
init_board(board);
print_board(board);
while (1) {
if (player == PLAYER) {
player_move(board);
} else {
computer_move(board);
}
print_board(board);
if (is_win(board, player)) {
printf("%s获胜!\n", player == PLAYER ? "玩家" : "电脑");
break;
}
player = player == PLAYER ? COMPUTER : PLAYER;
}
}
int main() {
game();
return 0;
}
```
阅读全文