C语言实现简单五子棋

#include
#include
#include
#include
#define P_INPUT "P1 is 'x' P2 is 'o'.\nPlease player:%d input coordinate XX(B4 or F2 or I1): "
#define T_RYAGN "Input coordinate error!\nPlease try again:"
#define M 15
#define N 15
char chessboard[M][N];
int per = 1; //player
void display_cb(void); //display chessboard
void seek_victor(int XX, int YY, char CH); //find winner
int main(void)
{
char yy;
int y, x;
memset(chessboard, '+', sizeof(chessboard)); //init chessboard
display_cb();
printf(P_INPUT, per);
while (1) {
fflush(stdout);
scanf("%c%d", &yy, &x); //get coordinate
scanf("%*[^\n]"); //empty buffer
scanf("%*c"); //empty buffer
printf("\n");
y = yy - 'A';
x--;
if (x < 0 || x > 14 || y < 0 || y > 14 ||
(chessboard[x][y] == 'x') || (chessboard [x][y] == 'o')) {
write(STDOUT_FILENO, T_RYAGN, strlen(T_RYAGN));
continue;
}
if (per == 1) {
chessboard[x][y] = 'x';
seek_victor(x, y, 'x');
} else {
chessboard[x][y] = 'o';
seek_victor(x, y, 'o');
}
printf(P_INPUT, per);
}
return 0;
}
void display_cb(void)
{
int i, j;
printf(" A B C D E F G H I J K L M N O\n");
for (i = 0; i < 15; i++) {
printf("%2d ", i + 1);
for (j = 0; j < 15; j++) {
if (j == 14) {
printf("%c\n", chessboard[i][j]);
break;
}
printf("%c-", chessboard[i][j]);
}
}
printf("\n");
}
void seek_victor(int x, int y, char c)
{
int xx, yy, i;
int count;
// '一' find
count = 1;
for (i = 1, xx = x - 1, yy = y;
i < 5 && xx >= 0 && count < 5; i++) {
if (chessboard[xx][yy] == c)
count++;
else
break;
xx--;
}
for (i = 1, xx = x + 1, yy = y;
i < 5 && xx < 15 && count < 5; i++) {
if (chessboard[xx][yy] == c)
count++;
else
break;
xx++;
}
if (count >= 5)
goto victor;
// '|' find
count = 1;
for (i = 1, xx = x, yy = y - 1;
i < 5 && yy >= 0 && count < 5; i++) {
if (chessboard[xx][yy] == c)
count++;
else
break;
yy--;
}
for (i = 1, xx = x, yy = y + 1;
i < 5 && yy < 15 && count < 5; i++) {
if (chessboard[xx][yy] == c)
count++;
else
break;
yy++;
}
if (count >= 5)
goto victor;
// '\' find
count = 1;
for (i = 1, xx = x - 1, yy = y - 1;
i < 5 && yy >= 0 && xx >= 0 && count < 5; i++) {
if (chessboard[xx][yy] == c)
count++;
else
break;
yy--;
xx--;
}
for (i = 1, xx = x + 1, yy = y + 1;
i < 5 && yy < 15 && xx < 15 && count < 5; i++) {
if (chessboard[xx][yy] == c)
count++;
else
break;
yy++;
xx++;
}
if (count >= 5)
goto victor;
// '/' find
count = 1;
for (i = 1, xx = x + 1, yy = y - 1;
i < 5 && yy >= 0 && xx < 15 && count < 5; i++) {
if (chessboard[xx][yy] == c)
count++;
else
break;
yy--;
xx++;
}
for (i = 1, xx = x - 1, yy = y + 1;
i < 5 && yy < 15 && xx >= 0 && count < 5; i++) {
if (chessboard[xx][yy] == c)
count++;
else
break;
yy++;
xx--;
}
if (count >= 5)
got

o victor;
switch (c) {
case 'x':
per++;
break;
case 'o':
per--;
break;
}
display_cb();
return;
victor:
display_cb();
printf("Player%d is winer!\n", per);
exit(0);
}

相关文档
最新文档