You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
1.0 KiB

#include<stdlib.h>
#include<time.h>
int h[9]={1,2,3,4,5,6,7,8,0};
int di4[4][2]={{-1,0},{1,0},{0,-1},{0,1}};//上下左右
int main()
{
int i;
for(i=0;i<5;i++)randn();
fresh();
do
{
move();
}while(1);
return 0;
}
int randn()
{
int i,r,c,r1,c1,ok=0;
srand((unsigned)time(0));
for (i=0;i<9;i++)
if(h[i]==0) break;
r=i/3;c=i%3;
do
{
i=rand()%4;
r1=r+di4[i][0];
c1=c+di4[i][1];
if(r1>=0&&r1<3&&c1>=0&&c1<3)
{
ok=1;
h[r*3+c]=h[r1*3+c1];
h[r1*3+c1]=0;
}
}while(ok==0);
return 1;
}
int moveok(int n)
{
int i,r,c,r1,c1,ok=0;
for (i=0;i<9;i++)
if(h[i]==0) break;
r=i/3;c=i%3;
for(i=0;i<4;i++)
{
r1=r+di4[i][0];
c1=c+di4[i][1];
if(r1>=0&&r1<3&&c1>=0&&c1<3&&(n==h[r1*3+c1]))
{
ok=1;
h[r*3+c]=n;
h[r1*3+c1]=0;
}
}
return ok;
}
int move()
{
int n;
printf("输入要移动的数字:");
do
{
scanf("%d",&n);
}while(moveok(n)==0);
fresh();
}
int fresh()
{//显示当前状态
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%2d",h[i*3+j]);
printf("\n");
}
return 1;
}