Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import java.awt.event.*;
- import java.util.*;
- import javax.swing.*;
- public class Puzzle implements WindowListener,ActionListener
- {
- JFrame mf;
- JPanel p1,p2;
- JButton jb[],rb;
- JTextField cc;
- JLabel lcc;
- int eb;
- int ccnt;
- void initbl()
- {
- for (int i=0;i<9;i++)
- jb[i].setText("0");
- jb[8].setText("");
- }
- Puzzle()
- {
- eb=8;
- mf=new JFrame("NLabs' Puzzle");
- p1=new JPanel();
- p2=new JPanel();
- jb=new JButton[9];
- rb=new JButton("Randomize");
- for (int i=0;i<9;i++)
- jb[i]=new JButton("0");
- jb[8].setText("");
- cc=new JTextField(5);
- lcc=new JLabel("Click Count: ");
- p1.setLayout(new GridLayout(3, 3));
- for (int i=0;i<9;i++)
- p1.add(jb[i]);
- p2.add(lcc);
- p2.add(cc);
- p2.add(rb);
- (mf.getContentPane()).setLayout(new GridLayout(2, 1));
- (mf.getContentPane()).add(p1);
- (mf.getContentPane()).add(p2);
- mf.setSize(200, 200);
- mf.setVisible(true);
- mf.addWindowListener(this);
- mf.setResizable(false);
- rnd();
- rb.addActionListener(this);
- for (int i=0;i<9;i++)
- jb[i].addActionListener(this);
- ccnt=0;
- dccnt();
- }
- void dccnt()
- {
- cc.setText(Integer.toString(ccnt));
- }
- void rnd()
- {
- Random r=new Random();
- for (int i=0;i<8;)
- {
- int j=r.nextInt(9);
- if (jb[j].getText().equals("0"))
- {
- jb[j].setText(Integer.toString(i+1));
- i++;
- }
- }
- }
- public static void main(String a[])
- {
- new Puzzle();
- }
- public void windowOpened(WindowEvent we)
- {
- }
- public void windowClosing(WindowEvent we)
- {
- System.exit(0);
- }
- public void windowClosed(WindowEvent we)
- {
- }
- public void windowIconified(WindowEvent we)
- {
- }
- public void windowDeiconified(WindowEvent we)
- {
- }
- public void windowActivated(WindowEvent we)
- {
- }
- public void windowDeactivated(WindowEvent we)
- {
- }
- void chek()
- {
- boolean go=false;
- for (int i=0;i<8;i++)
- {
- if (jb[i].getText().equals(Integer.toString(i+1)))
- {
- go=true;
- }
- else
- {
- go=false;
- break;
- }
- }
- if (go)
- {
- JOptionPane jp=new JOptionPane();
- jp.showMessageDialog(mf,"You have completed the puzzle in "+ ccnt +" counts.");
- ccnt=0;
- initbl();
- rnd();
- dccnt();
- }
- }
- public void actionPerformed(ActionEvent ae)
- {
- if (ae.getSource()==rb)
- {
- ccnt=0;
- initbl();
- rnd();
- dccnt();
- return;
- }
- for (int i=0;i<9;i++)
- {
- if (ae.getSource()==jb[i])
- {
- ccnt++;
- dccnt();
- if (eb!=i)
- {
- jb[eb].setText(jb[i].getText());
- eb=i;
- jb[eb].setText("");
- chek();
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement