用c语言写一个五子棋程序
时间: 2023-10-01 22:06:40 浏览: 99
用c语言编写的五子棋程序
好的,下面是一个简单的五子棋程序的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define BOARD_SIZE 15
#define EMPTY 0
#define BLACK 1
#define WHITE 2
int board[BOARD_SIZE][BOARD_SIZE];
void init_board() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY;
}
}
}
void print_board() {
printf(" ");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%d ", i);
}
printf("\n");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%d ", i);
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY) {
printf("+ ");
} else if (board[i][j] == BLACK) {
printf("X ");
} else {
printf("O ");
}
}
printf("\n");
}
}
bool is_valid_move(int row, int col) {
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
return false;
}
if (board[row][col] != EMPTY) {
return false;
}
return true;
}
bool is_win(int player) {
int count = 0;
// 横向
for (int i = 0; i < BOARD_SIZE; i++) {
count = 0;
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
}
// 纵向
for (int j = 0; j < BOARD_SIZE; j++) {
count = 0;
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
}
// 左上到右下
for (int k = 0; k <= BOARD_SIZE - 5; k++) {
for (int i = k, j = 0; i < BOARD_SIZE && j < BOARD_SIZE; i++, j++) {
count = 0;
for (int x = i, y = j; x < BOARD_SIZE && y < BOARD_SIZE; x++, y++) {
if (board[x][y] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
}
}
// 右上到左下
for (int k = 4; k < BOARD_SIZE; k++) {
for (int i = k, j = 0; i >= 0 && j < BOARD_SIZE; i--, j++) {
count = 0;
for (int x = i, y = j; x >= 0 && y < BOARD_SIZE; x--, y++) {
if (board[x][y] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
}
}
return false;
}
void play_game() {
int player = BLACK;
int row, col;
while (true) {
printf("Player %d's turn.\n", player);
printf("Enter row and column: ");
scanf("%d %d", &row, &col);
if (is_valid_move(row, col)) {
board[row][col] = player;
print_board();
if (is_win(player)) {
printf("Player %d wins!\n", player);
break;
}
player = (player == BLACK) ? WHITE : BLACK;
} else {
printf("Invalid move. Try again.\n");
}
}
}
int main() {
init_board();
print_board();
play_game();
return 0;
}
```
这个程序使用二维数组来表示棋盘,0表示空,1表示黑子,2表示白子。程序提供了初始化棋盘,打印棋盘,判断是否为有效落子,判断棋局是否结束,以及进行游戏的主函数。
注意,这个程序只是一个简单的五子棋程序,没有考虑很多特殊情况,比如长连和禁手等规则。如果想要实现更完整的五子棋程序,还需要在这个基础上进行更多的开发和测试。
阅读全文