用C语言编写判断五子棋输赢的程序
时间: 2024-02-09 12:10:02 浏览: 223
C语言课程设计五子棋
好的,以下是用C语言编写判断五子棋输赢的程序:
```c
#include <stdio.h>
#define SIZE 15 // 棋盘大小
int board[SIZE][SIZE]; // 棋盘
int player = 1; // 当前下棋者
int is_win(int row, int col) {
int i;
int count = 1; // 连续棋子数量
// 判断横向
for (i = col - 1; i >= 0 && board[row][i] == player; i--) {
count++;
}
for (i = col + 1; i < SIZE && board[row][i] == player; i++) {
count++;
}
if (count >= 5) {
return 1;
}
// 判断纵向
count = 1;
for (i = row - 1; i >= 0 && board[i][col] == player; i--) {
count++;
}
for (i = row + 1; i < SIZE && board[i][col] == player; i++) {
count++;
}
if (count >= 5) {
return 1;
}
// 判断左上到右下斜线
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 < SIZE && j < SIZE && board[i][j] == player; i++, j++) {
count++;
}
if (count >= 5) {
return 1;
}
// 判断左下到右上斜线
count = 1;
for (i = row + 1, j = col - 1; i < SIZE && j >= 0 && board[i][j] == player; i++, j--) {
count++;
}
for (i = row - 1, j = col + 1; i >= 0 && j < SIZE && board[i][j] == player; i--, j++) {
count++;
}
if (count >= 5) {
return 1;
}
return 0;
}
int main() {
int row, col;
// 初始化棋盘
for (row = 0; row < SIZE; row++) {
for (col = 0; col < SIZE; col++) {
board[row][col] = 0;
}
}
// 开始下棋
while (1) {
printf("Player %d's turn.\n", player);
printf("Enter row and column: ");
scanf("%d %d", &row, &col);
// 判断位置是否合法
if (row < 0 || row >= SIZE || col < 0 || col >= SIZE || board[row][col] != 0) {
printf("Invalid move. Try again.\n");
continue;
}
// 下棋
board[row][col] = player;
// 判断是否获胜
if (is_win(row, col)) {
printf("Player %d wins!\n", player);
break;
}
// 切换下棋者
player = (player == 1) ? 2 : 1;
}
return 0;
}
```
这个程序实现了一个简单的五子棋游戏,并且可以判断输赢。不过需要注意的是,这个程序并没有考虑禁手规则或其他特殊规则。
阅读全文