请用c++写一个五子棋程序
时间: 2023-04-09 22:01:40 浏览: 72
我可以回答这个问题。以下是一个简单的五子棋程序的 C 代码示例:
#include <stdio.h>
#include <stdlib.h>
#define BOARD_SIZE 15
#define EMPTY 0
#define BLACK 1
#define WHITE 2
int board[BOARD_SIZE][BOARD_SIZE];
void init_board() {
int i, j;
for (i = 0; i < BOARD_SIZE; i++) {
for (j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY;
}
}
}
void print_board() {
int i, j;
printf(" ");
for (i = 0; i < BOARD_SIZE; i++) {
printf("%c ", 'A' + i);
}
printf("\n");
for (i = 0; i < BOARD_SIZE; i++) {
printf("%2d", i + 1);
for (j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY) {
printf(" .");
} else if (board[i][j] == BLACK) {
printf(" X");
} else if (board[i][j] == WHITE) {
printf(" O");
}
}
printf("\n");
}
}
int is_valid_move(int row, int col) {
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
return 0;
}
if (board[row][col] != EMPTY) {
return 0;
}
return 1;
}
int is_game_over(int row, int col, int player) {
int i, j, k;
int count;
// check horizontal
count = 1;
for (i = col - 1; i >= 0 && board[row][i] == player; i--) {
count++;
}
for (i = col + 1; i < BOARD_SIZE && board[row][i] == player; i++) {
count++;
}
if (count >= 5) {
return 1;
}
// check vertical
count = 1;
for (i = row - 1; i >= 0 && board[i][col] == player; i--) {
count++;
}
for (i = row + 1; i < BOARD_SIZE && board[i][col] == player; i++) {
count++;
}
if (count >= 5) {
return 1;
}
// check diagonal
count = 1;
for (i = row - 1, j = col - 1; i >= 0 && j >= 0 && board[i][j] == player; i--, j--) {
count++;
}
for (i = row + 1, j = col + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == player; i++, j++) {
count++;
}
if (count >= 5) {
return 1;
}
// check anti-diagonal
count = 1;
for (i = row - 1, j = col + 1; i >= 0 && j < BOARD_SIZE && board[i][j] == player; i--, j++) {
count++;
}
for (i = row + 1, j = col - 1; i < BOARD_SIZE && j >= 0 && board[i][j] == player; i++, j--) {
count++;
}
if (count >= 5) {
return 1;
}
// check draw
for (i = 0; i < BOARD_SIZE; i++) {
for (j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY) {
return 0;
}
}
}
return 2;
}
void make_move(int row, int col, int player) {
board[row][col] = player;
}
int main() {
int row, col;
int player = BLACK;
int game_over = 0;
init_board();
while (!game_over) {
print_board();
printf("Player %d's turn:\n", player);
printf("Enter row (1-%d): ", BOARD_SIZE);
scanf("%d", &row);
row--;
printf("Enter column (A-%c): ", 'A' + BOARD_SIZE - 1);
scanf(" %c", &col);
col = col - 'A';
if (!is_valid_move(row, col)) {
printf("Invalid move!\n");
continue;
}
make_move(row, col, player);
game_over = is_game_over(row, col, player);
if (game_over == 1) {
printf("Player %d wins!\n", player);
} else if (game_over == 2) {
printf("Draw!\n");
}
player = 3 - player;
}
print_board();
return 0;
}
阅读全文