arnab.d287
Still A Student!!!
I wanted to create a game like the 15puzzle
15puzzle
I used the blank space as 0(zero) for the game
but it is not running as it should be.. Can anyone tell whats wrong?
15puzzle
Code:
import java.io.*;
class puzzle
{
int a[][]={{8,2,7,4},{1,11,0,10},{15,3,12,5},{14,6,13,9}};
int n; int r=0; int c=0;
public void main()throws IOException
{
display();
do
{
input();
swapping(a, r, c);
checkForCompletion();
display();
}while(true);
}
public void input()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number to move");
System.out.println("Enter 0 to exit");
n=Integer.parseInt(br.readLine());
int flag=0;
int c=0,r=0;
for (int i=0;i<4;i++)
for(int j=0;j<4;j++)
{
if(n==a[i][j])
{
r=i;
c=j;
flag=1;
break;
}
}
if(n<1&&n>15)
System.out.println("Invalid Input");
else if (flag!=1)
System.out.println("Invalid Input");
else if(n==0)
System.exit(0);
}
public void swapping(int a[][], int r, int c)
{
int fl=0;
for (int i=0;i<4;i++)
for(int j=0;j<4;j++)
{
if(r!=3||a[r+1][c]==0)
{
a[r+1][c]=n;fl=1;
a[r][c]=0;
}
else if(r!=0||a[r-1][c]==0)
{
a[r-1][c]=n;fl=1;
a[r][c]=0;
}
else if(r!=0||a[r][c-1]==0)
{
a[r][c-1]=n;fl=1;
a[r][c]=0;
}
else if(r!=3||a[r][c+1]==0)
{
a[r][c+1]=n;fl=1;
a[r][c]=0;
}
}
if(fl!=1)
System.out.println("Cannot be moved");
}
public void checkForCompletion()
{
int c=1;int fl=0;
for (int i=0;i<4;i++)
for(int j=0;j<4;j++)
{
if(i!=4&&j!=4)
{
if(a[i][j]!=c++)
fl=1;
}
}
if (fl==0)
{
System.out.println("Completed");
System.exit(0);
}
}
public void display()
{
for (int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
but it is not running as it should be.. Can anyone tell whats wrong?