帮我用c语言写一个五子棋的代码。
时间: 2023-04-02 16:01:27 浏览: 75
好的,我可以为您提供五子棋的 C 语言代码。以下是代码示例:
#include <stdio.h>
#include <stdlib.h>
#define ROW 15
#define COL 15
char board[ROW][COL]; // 棋盘
void init_board() // 初始化棋盘
{
int i, j;
for (i = ; i < ROW; i++) {
for (j = ; j < COL; j++) {
board[i][j] = '+';
}
}
}
void print_board() // 打印棋盘
{
int i, j;
printf(" ");
for (i = ; i < COL; i++) {
printf("%d ", i + 1);
}
printf("\n");
for (i = ; i < ROW; i++) {
printf("%d ", i + 1);
for (j = ; j < COL; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int check_win(int x, int y, char c) // 判断胜负
{
int i, j, count;
// 横向
count = ;
for (i = y - 4; i <= y; i++) {
if (i < || i + 4 >= COL) {
continue;
}
count = ;
for (j = i; j <= i + 4; j++) {
if (board[x][j] == c) {
count++;
}
}
if (count == 5) {
return 1;
}
}
// 纵向
count = ;
for (i = x - 4; i <= x; i++) {
if (i < || i + 4 >= ROW) {
continue;
}
count = ;
for (j = i; j <= i + 4; j++) {
if (board[j][y] == c) {
count++;
}
}
if (count == 5) {
return 1;
}
}
// 左上到右下
count = ;
for (i = x - 4, j = y - 4; i <= x && j <= y; i++, j++) {
if (i < || j < || i + 4 >= ROW || j + 4 >= COL) {
continue;
}
count = ;
for (int k = ; k < 5; k++) {
if (board[i + k][j + k] == c) {
count++;
}
}
if (count == 5) {
return 1;
}
}
// 左下到右上
count = ;
for (i = x + 4, j = y - 4; i >= x && j <= y; i--, j++) {
if (i >= ROW || j < || i - 4 < || j + 4 >= COL) {
continue;
}
count = ;
for (int k = ; k < 5; k++) {
if (board[i - k][j + k] == c) {
count++;
}
}
if (count == 5) {
return 1;
}
}
return ;
}
int main()
{
int x, y, player = 1;
char c;
init_board();
while (1) {
printf("玩家 %d,请输入坐标(x,y): ", player);
scanf("%d,%d", &x, &y);
if (x < 1 || x > ROW || y < 1 || y > COL) {
printf("坐标不合法,请重新输入!\n");
continue;
}
if (board[x - 1][y - 1] != '+') {
printf("该位置已经有棋子,请重新输入!\n");
continue;
}
if (player == 1) {
c = 'X';
player = 2;
} else {
c = 'O';
player = 1;
}
board[x - 1][y - 1] = c;
print_board();
if (check_win(x - 1, y - 1, c)) {
printf("玩家 %d 获胜!\n", player == 1 ? 2 : 1);
break;
}
}
return ;
}
阅读全文