import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Puzzle extends JFrame implements KeyListener
{
static int[][] a={{11,0,7,3},{15,6,9,8},{2,10,13,1},{4,12,5,14}};
int i,j, row=3,col=3;
JTextField[][] tf=new JTextField[4][4];
Puzzle()
{
setTitle("puzzle");
setLayout(new GridLayout(4,4));
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
tf[i][j]=new JTextField("");
tf[i][j].setText(""+a[i][j]);
tf[i][j].setHorizontalAlignment(JTextField.CENTER);
tf[i][j].setFont(new Font("Georgia",Font.BOLD,26));
tf[i][j].setBackground(Color.black);
tf[i][j].setForeground(Color.white);
tf[i][j].setEditable(false);
add(tf[i][j]);
tf[i][j].addKeyListener(this);
if(Integer.parseInt(tf[i][j].getText())==0)
{
tf[i][j].setEditable(true);
tf[i][j].setText("");
row=i;col=j;
}
}
}
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setSize(200,250);
setLocation(300,300);
}
public void keyPressed(KeyEvent ke)
{
int key=ke.getKeyCode();
if(key==KeyEvent.VK_UP)
{
if(row==0)
{
}
else
{
String temp=tf[row-1][col].getText();
tf[row-1][col].setText("");
tf[row-1][col].setEditable(true);
tf[row][col].setText(temp);
tf[row][col].setEditable(false);
row=row-1;
}
check();
}
if(key==KeyEvent.VK_DOWN)
{
if(row==3)
{
}
else
{
String temp=tf[row+1][col].getText();
tf[row+1][col].setText("");
tf[row+1][col].setEditable(true);
tf[row][col].setText(temp);
tf[row][col].setEditable(false);
row=row+1;
}
check();
}
if(key==KeyEvent.VK_LEFT)
{
if(col==0)
{
}
else
{
String temp=tf[row][col-1].getText();
tf[row][col-1].setText("");
tf[row][col-1].setEditable(true);
tf[row][col].setText(temp);
tf[row][col].setEditable(false);
col=col-1;
}
check();
}
if(key==KeyEvent.VK_RIGHT)
{
if(col==3)
{
}
else
{
String temp=tf[row][col+1].getText();
tf[row][col+1].setText("");
tf[row][col+1].setEditable(true);
tf[row][col].setText(temp);
tf[row][col].setEditable(false);
col=col+1;
}
check();
}
}
public void check()
{
try
{
int n=1;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
int m=Integer.parseInt(tf[i][j].getText());
if(m==n)
{
if(n==15)
{
JOptionPane.showMessageDialog(this," Congratulations ! Puzzle is done. You won.","Message",JOptionPane.PLAIN_MESSAGE);
int choice=JOptionPane.showConfirmDialog(this,"Do you want to restart ?","Question Message",JOptionPane.YES_NO_OPTION);
if(choice==0)
{
setVisible(false);
new Puzzle().setVisible(true);
}
else
{
setVisible(false);
}
}
n++;
}
}
}
}
catch(Exception e)
{}
}
public void keyReleased(KeyEvent ke)
{}
public void keyTyped(KeyEvent ke)
{}
public static void main(String args[])
{
new Puzzle();
}
}
Download
0 comments:
Post a Comment