Gobang program in C language

Note: The environment is GCC

#include <stdio.h>
#include <stdlib.h>


#define ROW 9
#define B -1
#define W 1
#define N 0


int chess_flag = B;
int CHESS[ROW][ROW] = {N};


int play_chess(int row, int col);
void print_chess(void);
int chess_win(int row, int col);


int main(int argc, const char *argv[])
{
int x, y;
int side;
int win_flag;
int over_flag = 0;
print_chess();
do
{
printf("Choose the first side: Black: 1, White: 2\n");
scanf("%d",&side);
if(side == 1)
{
chess_flag = B;
}
else if(side == 2)
{
chess_flag = W;
}


}while(side != 1 && side != 2);


do
{
printf("%s chess set!\n",chess_flag==B?"Black":"White");
printf("Input your chess position!\n");
scanf("%d %d",&x, &y);
x--;
y--;
if(play_chess(x, y) == 0)
{


system("clear");
print_chess();
if(chess_win(x, y)== 1)
{
over_flag = 1;
win_flag = chess_flag;
}
chess_flag = -chess_flag;
}
}while(!over_flag);printf("%s side win!\n",win_flag == B? "Black" : "White");return 0;}void print_chess(void){int i, j;printf("  ");for(i = 0; i < ROW; i++){












printf("%2d",i+1);
}
printf("\n");
for(i = 0; i < ROW; i++)
{
printf("%2d",i+1);
for(j = 0; j < ROW; j++)
{
if(CHESS[i][j] == N)
{
printf("  ");
}
else if(CHESS[i][j] == B)
{
printf(" *");
}
else
{
printf(" $");
}
}
printf("\n");
}
}


int play_chess(int row, int col)
{
if(row > ROW - 1 || row < 0 || col > ROW - 1 || col < 0)
{
printf("Input position error!\n");
return -1;
}
if(CHESS[row][col] != N)
{
printf("The positon has chess!\n");
return 1;
}


CHESS[row][col] = chess_flag;
return 0;
}


int chess_win(int row, int col)
{
int i, j, count;
//row
count = 1;
i = row;
j = col - 1;
while(j >= 0 && CHESS[i][j] == CHESS[row][col])
{
count++;
j--;
}
j = col + 1;
while(j < ROW && CHESS[i][j] == CHESS[row][col])
{
count++;
j++;
}
if( count >= 5)
{
return 1;
}
//colcount = 1;i = row - 1;j = col;while(i >= 0 && CHESS[i][j] == CHESS[row][col]){count++;i--;}









i = row + 1;
while(i < ROW && CHESS[i][j] == CHESS[row][col])
{
count++;
i++;
}
if( count >= 5)
{
return 1;
}
//maincount = 1;i = row - 1;j = col - 1;while(j >= 0 &&  i >= 0 && CHESS[i][j] == CHESS[row][col]){count++;j--;i--;}i = row + 1;j = col + 1;while(j < ROW && i< ROW && CHESS[i][j] == CHESS[row][col]){count++;j++;i++;}if( count >= 5){return 1;}//deputycount = 1;i = row + 1;j = col - 1;



























while(j >= 0 &&  i < ROW && CHESS[i][j] == CHESS[row][col])
{
count++;
i++;
j--;
}
i = row - 1;
j = col + 1;
while(j < ROW && i >= 0 && CHESS[i][j] == CHESS[row][col])
{
count++;
i--;
j++;
}
if( count >= 5)
{
return 1;
}


return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325411451&siteId=291194637