用c语言写一个五子棋
时间: 2023-11-18 19:03:01 浏览: 75
一个用C语言编写的五子棋
5星 · 资源好评率100%
以下是一个简单的五子棋游戏的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define ROW 15
#define COL 15
void display_board(char board[][COL]);
int check_win(char board[][COL], int row, int col, char ch);
int main()
{
char board[ROW][COL] = {0};
char player = 'X';
int row, col;
printf("Welcome to Five in a Row game!\n");
while (1) {
display_board(board);
printf("\nPlayer %c's turn, enter row and column: ", player);
scanf("%d%d", &row, &col);
if (row < 1 || row > ROW || col < 1 || col > COL) {
printf("Invalid input, please try again.\n");
continue;
}
if (board[row-1][col-1] != 0) {
printf("This position is already occupied, please try again.\n");
continue;
}
board[row-1][col-1] = player;
if (check_win(board, row-1, col-1, player)) {
display_board(board);
printf("\nPlayer %c wins!\n", player);
break;
}
if (player == 'X')
player = 'O';
else
player = 'X';
}
return 0;
}
void display_board(char board[][COL])
{
int i, j;
printf(" ");
for (i = 1; i <= COL; i++)
printf("%2d ", i);
printf("\n");
for (i = 0; i < ROW; i++) {
printf("%2d ", i+1);
for (j = 0; j < COL; j++) {
if (board[i][j] == 0)
printf("| ");
else
printf("|%2c", board[i][j]);
}
printf("|\n");
}
}
int check_win(char board[][COL], int row, int col, char ch)
{
int i, j, count;
// check row
count = 0;
for (i = col-4; i <= col+4; i++) {
if (i < 0 || i >= COL)
continue;
if (board[row][i] == ch)
count++;
else
count = 0;
if (count == 5)
return 1;
}
// check column
count = 0;
for (i = row-4; i <= row+4; i++) {
if (i < 0 || i >= ROW)
continue;
if (board[i][col] == ch)
count++;
else
count = 0;
if (count == 5)
return 1;
}
// check diagonal
count = 0;
for (i = row-4, j = col-4; i <= row+4 && j <= col+4; i++, j++) {
if (i < 0 || i >= ROW || j < 0 || j >= COL)
continue;
if (board[i][j] == ch)
count++;
else
count = 0;
if (count == 5)
return 1;
}
// check another diagonal
count = 0;
for (i = row-4, j = col+4; i <= row+4 && j >= col-4; i++, j--) {
if (i < 0 || i >= ROW || j < 0 || j >= COL)
continue;
if (board[i][j] == ch)
count++;
else
count = 0;
if (count == 5)
return 1;
}
return 0;
}
```
这个程序提供了一个简单的五子棋游戏界面,并且可以检测出胜利者。你可以在此基础上进行修改,添加更多的功能或者改进游戏体验。
阅读全文