可以称得上史上最简单的五子棋版本了。
可以使用curses库来改进页面和下棋方式。
并且对于输入的坐标没有进行鉴别,如果输入的坐标超过棋盘大小,就会段错误退出。
我改进了一点,但是还是没有完全避免这个问题。
/*
*Gobang.c
*/
#include<stdio.h>
#include<stdlib.h> #define N 15
int chessboard[N+][N+] = {}; int whoseTurn = ; void initGame();
void printChessboard();
void playChess();
int judge(int x, int y); int main()
{
initGame();
while()
{
whoseTurn++;
playChess();
}
return ;
} void initGame()
{
char c;
printf("Input Y to enter the game: ");
c = getchar();
if (c != 'y' && c != 'Y')
{
exit();
}
system("clear");
printChessboard();
} void printChessboard()
{
int i,j;
for (i = ; i <= N; i++)
{
for (j = ; j <= N; j++)
{
if ( == i)
{
printf("%3d", j);
}
else if( == j)
{
printf("%3d", i);
}
else if ( == chessboard[i][j])
{
printf(" X");
}
else if ( == chessboard[i][j])
{
printf(" O");
}
else
{
printf(" *");
}
} printf("\n");
}
}
void playChess()
{
int i, j, winner;
if ( == whoseTurn % )
{
printf("Turn to player 1, please input the position: ");
scanf("%d %d", &i, &j);
while(chessboard[i][j] != || i > N || i < || j > N || j < )
{
printf("your position is taken, choose another: ");
scanf("%d %d", &i, &j);
} chessboard[i][j] = ;
}
else
{
printf("Turn to player 2, please input the position: ");
scanf("%d %d", &i, &j);
while(chessboard[i][j] != || i > N || i < || j > N || j < )
{
printf("your position is taken, choose another: ");
scanf("%d %d", &i, &j);
} chessboard[i][j] = ;
} system("clear"); printChessboard();
if (judge(i, j))
{
if ( == whoseTurn % )
{
printf("player1 win\n");
exit();
}
else
{
printf("player2 win\n");
exit();
}
}
} int judge(int x, int y)
{
int i, j, k;
int t = - whoseTurn % ;
const int step[][] = {{-, }, {, -}, {, }, {, }};
for (i = ; i < ; i++)
{
const int d[] = {-, };
int count = ;
for (j = ; j < ; ++j)
{
for (k = ; k <= ; k++)
{
int row = x + k*d[j]*step[i][];
int col = y + k*d[j]*step[i][];
if (row > && row <= N && col >= && col <= N &&
chessboard[x][y] == chessboard[row][col])
{
count++;
}
else
{
break;
}
}
}
if (count >= )
{
return ;
}
} return ;
}