五子棋判断获胜算法
只需要用一个结构体去分别记录每个棋子的位置,然后再用一个变量去记录当前下子的个数,然后用一个循环,每次去试当前子的上左下右斜边是不是都有两个子,如果成立,直接跳出循环。
五子棋代码:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
struct h
{
int y;//y表示是第几列
int x;//x表示第几行
};
struct pos cor[2501];
int main()
{
int sum1;
char w;
w='@';
int i,m;
char a[50][50]={"###############################################",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"###############################################",
};
int h;
m=0;
int x1,y1;
int sum;
int p,q;
sum=0,sum1=0;
h=0;
for(i=0;i<20;i++)
puts(a[i]);
while(1)
{
if(w=='@')
{
printf("@方");
printf("请输入行号与列号");
scanf("%d%d",&p,&q);
if(a[p][q]!='#'&&a[p][q]!='%'&&a[p][q]!='@')
{
cor[h].x=p;
cor[h].y=q;
a[p][q]='@';
sum1++;
}
for(h=0;h<sum1;h++)
{
x1=cor[h].x;
y1=cor[h].y;
if(a[x1-1][y1]=='@'&&a[x1-2][y1]=='@'&&a[x1+2][y1]=='@'&&a[x1+1][y1]=='@')
{
m++;
}
if(a[x1][y1+1]=='@'&&a[x1][y1+2]=='@'&&a[x1][y1-1]=='@'&&a[x1][y1-2]=='@')
{
m++;
}
if(a[x1-1][y1-1]=='@'&&a[x1-2][y1-2]=='@'&&a[x1+1][y1+1]=='@'&&a[x1+2][y1+2]=='@')
{
m++;
}
}
if(m!=0)
break;
}
system("cls");
for(i=0; i<20; i++)
puts(a[i]);
if(w='*')
{
printf("*方");
printf("请输入行号与列号");
scanf("%d%d",&p,&q);
if(a[p][q]!='#'&&a[p][q]!='@'&&a[p][q]!='*')
{
cor[h].x=p;
cor[h].y=q;
a[p][q]='*';
sum++;
}
for(h=0;h<sum;h++)
{
x1=cor[h].x;
y1=cor[h].y;
if(a[x1-1][y1]=='*'&&a[x1-2][y1]=='*'&&a[x1+2][y1]=='*'&&a[x1+1][y1]=='*')
{
m++;
}
if(a[x1][y1+1]=='*'&&a[x1][y1+2]=='*'&&a[x1][y1-1]=='*'&&a[x1][y1-2]=='*')
{
m++;
}
if(a[x1-1][y1-1]=='*'&&a[x1-2][y1-2]=='*'&&a[x1+1][y1+1]=='*'&&a[x1+2][y1+2]=='*')
{
m++;
}
}
if(m!=0)
break;
}
if(w=='@')
w='*';
else w='@';
system("cls");
for(i=0; i<20; i++)
puts(a[i]);
}
system("cls");
if(w=='@')
printf("@方赢!");
else printf("*方赢!");
//printf("you win!");
system("pause");
return 0;
}