帮我用C语言写一个五子棋游戏,要求:实现人和电脑对弈
时间: 2023-05-23 08:05:52 浏览: 88
游戏,欢乐五子棋,C#实现完整源代码,界面大气美观,跟电脑对战,电脑反应神速,人机对战,赢一局很难,F1可以重新开始对战
A:
以下是一个简单的五子棋游戏示例,满足人与电脑对弈的需求。其中,电脑AI部分使用了简单的随机算法,使得每次电脑下子都是随机的。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 15
#define COLUMN 15
#define PLAYER 1
#define COMPUTER 2
int board[ROW][COLUMN];
void init_board();
void print_board();
int check_win(int player);
void player_move();
void computer_move();
int main() {
init_board();
print_board();
int current_player = PLAYER;
while (1) {
if (current_player == PLAYER) {
player_move();
if (check_win(PLAYER)) {
printf("You win!\n");
break;
}
current_player = COMPUTER;
} else {
computer_move();
print_board();
if (check_win(COMPUTER)) {
printf("Computer win!\n");
break;
}
current_player = PLAYER;
}
}
return 0;
}
void init_board() {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COLUMN; j++) {
board[i][j] = 0;
}
}
}
void print_board() {
printf(" ");
for (int i = 0; i < COLUMN; i++) {
printf("%c ", i + 'a');
}
printf("\n");
for (int i = 0; i < ROW; i++) {
printf("%2d ", i + 1);
for (int j = 0; j < COLUMN; j++) {
switch (board[i][j]) {
case 0:
printf("+ ");
break;
case PLAYER:
printf("O ");
break;
case COMPUTER:
printf("X ");
break;
}
}
printf("%d\n", i + 1);
}
printf(" ");
for (int i = 0; i < COLUMN; i++) {
printf("%c ", i + 'a');
}
printf("\n");
}
int check_win(int player) {
// check rows
for (int i = 0; i < ROW; i++) {
int count = 0;
for (int j = 0; j < COLUMN; j++) {
if (board[i][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return 1;
}
}
}
// check columns
for (int j = 0; j < COLUMN; j++) {
int count = 0;
for (int i = 0; i < ROW; i++) {
if (board[i][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return 1;
}
}
}
// check diagonal (left to right)
for (int i = 0; i <= ROW - 5; i++) {
for (int j = 0; j <= COLUMN - 5; j++) {
int count = 0;
for (int k = 0; k < 5; k++) {
if (board[i+k][j+k] == player) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
}
// check diagonal (right to left)
for (int i = 0; i <= ROW - 5; i++) {
for (int j = 4; j < COLUMN; j++) {
int count = 0;
for (int k = 0; k < 5; k++) {
if (board[i+k][j-k] == player) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
}
return 0;
}
void player_move() {
int row, column;
while (1) {
printf("Your turn (row, column): ");
scanf("%d %d", &row, &column);
if (row < 1 || row > ROW || column < 0 || column >= COLUMN || board[row-1][column] != 0) {
printf("Invalid move, please try again.\n");
} else {
break;
}
}
board[row-1][column] = PLAYER;
}
void computer_move() {
printf("Computer's turn:\n");
srand(time(NULL));
int row, column;
while (1) {
row = rand() % ROW;
column = rand() % COLUMN;
if (board[row][column] == 0) {
break;
}
}
board[row][column] = COMPUTER;
}
```
阅读全文