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