c语言实现五子棋代码
时间: 2024-03-02 14:45:54 浏览: 131
以下是一个简单的C语言实现五子棋的代码示例:
```c
#include <stdio.h>
#define SIZE 15
char board[SIZE][SIZE]; // 棋盘
void initBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = ' ';
}
}
}
void printBoard() {
printf(" ");
for (int i = 0; i < SIZE; i++) {
printf("%2d", i);
}
printf("\n");
for (int i = 0; i < SIZE; i++) {
printf("%2d", i);
for (int j = 0; j < SIZE; j++) {
printf(" %c", board[i][j]);
}
printf("\n");
}
}
int checkWin(int row, int col, char player) {
int count = 0;
int i, j;
// 横向检查
for (i = col - 4; i <= col; i++) {
if (i >= 0 && i + 4 < SIZE) {
count = 0;
for (j = i; j <= i + 4; j++) {
if (board[row][j] == player) {
count++;
}
}
if (count == 5) {
return 1;
}
}
}
// 纵向检查
for (i = row - 4; i <= row; i++) {
if (i >= 0 && i + 4 < SIZE) {
count = 0;
for (j = i; j <= i + 4; j++) {
if (board[j][col] == player) {
count++;
}
}
if (count == 5) {
return 1;
}
}
}
// 左上到右下斜向检查
for (i = row - 4, j = col - 4; i <= row && j <= col; i++, j++) {
if (i >= 0 && i + 4 < SIZE && j >= 0 && j + 4 < SIZE) {
count = 0;
for (int k = 0; k < 5; k++) {
if (board[i + k][j + k] == player) {
count++;
}
}
if (count == 5) {
return 1;
}
}
}
// 左下到右上斜向检查
for (i = row + 4, j = col - 4; i >= row && j <= col; i--, j++) {
if (i >= 0 && i - 4 < SIZE && j >= 0 && j + 4 < SIZE) {
count = 0;
for (int k = 0; k < 5; k++) {
if (board[i - k][j + k] == player) {
count++;
}
}
if (count == 5) {
return 1;
}
}
}
return 0;
}
int main() {
int row, col;
char player = 'X';
initBoard();
while (1) {
printBoard();
printf("Player %c's turn. Enter row and column: ", player);
scanf("%d %d", &row, &col);
if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) {
printf("Invalid input. Please try again.\n");
continue;
}
if (board[row][col] != ' ') {
printf("This position is already occupied. Please try again.\n");
continue;
}
board[row][col] = player;
if (checkWin(row, col, player)) {
printf("Player %c wins!\n", player);
break;
}
player = (player == 'X') ? 'O' : 'X';
}
return 0;
}
```
阅读全文