Developing Tile Puzzle Game in Java Java by Rajesh Kumar Sahanee - July 31, 2017September 11, 20170 Post Views: 9,484 Greetings! Friends, Today I am going to explain how to Develop Game in Java. The game which I am going to develop is a Tile Puzzle Game. In this game development we are going to use below classes :- java.awt.Image java.awt.image.BufferedImage javax.swing.ImageIcon Here Image class is used to hold image resource while BufferedImage and ImageIcon are used to split image to multiple images. In this game there is a default image which is loaded automatically but you can load your own image also at runtime using load button in the user interface. In this game I am going to create three classes first one is Game.java where all game logic coded ie. loading image, starting game, stopping game, etc. second one is Help.java which is used to show solved puzzle for hint and last one is Timer.java which is used to store time. So here is the code Game.java Game.java Java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package zatackcoder; import java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * * @author Rajesh Kumar Sahanee */ public class Game extends javax.swing.JFrame implements ActionListener{ /** * Creates new form Game */ public Game() { initComponents(); gamePanelJP.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { controlPanel = new javax.swing.JPanel(); startStopJB = new javax.swing.JButton(); playPauseJB = new javax.swing.JButton(); shuffleJB = new javax.swing.JButton(); loadJB = new javax.swing.JButton(); gamePanelJP = new javax.swing.JPanel(); timerPanel = new javax.swing.JPanel(); closeJL = new javax.swing.JLabel(); timeJL = new javax.swing.JTextField(); helpJL = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(204, 204, 255)); setIconImage(new ImageIcon(getClass().getResource("/img/logo.png")).getImage()); setLocationByPlatform(true); setUndecorated(true); getContentPane().setLayout(new java.awt.BorderLayout()); controlPanel.setBackground(new java.awt.Color(204, 204, 255)); controlPanel.setFocusable(false); controlPanel.setOpaque(false); controlPanel.setPreferredSize(new java.awt.Dimension(300, 40)); controlPanel.setLayout(new java.awt.GridLayout(1, 3)); startStopJB.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N startStopJB.setForeground(new java.awt.Color(0, 153, 153)); startStopJB.setText("START"); startStopJB.setToolTipText("Start or Stop"); startStopJB.setBorder(null); startStopJB.setBorderPainted(false); startStopJB.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); startStopJB.setFocusable(false); startStopJB.setMaximumSize(new java.awt.Dimension(85, 31)); startStopJB.setMinimumSize(new java.awt.Dimension(85, 31)); startStopJB.setPreferredSize(new java.awt.Dimension(85, 31)); startStopJB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startStopJBActionPerformed(evt); } }); controlPanel.add(startStopJB); playPauseJB.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N playPauseJB.setForeground(new java.awt.Color(0, 153, 153)); playPauseJB.setText("PLAY"); playPauseJB.setToolTipText("Play or Pause"); playPauseJB.setBorder(null); playPauseJB.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); playPauseJB.setFocusable(false); playPauseJB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { playPauseJBActionPerformed(evt); } }); controlPanel.add(playPauseJB); shuffleJB.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N shuffleJB.setForeground(new java.awt.Color(0, 153, 153)); shuffleJB.setText("SHUFFLE"); shuffleJB.setToolTipText("Shuffle Tiles"); shuffleJB.setBorder(null); shuffleJB.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); shuffleJB.setFocusable(false); shuffleJB.setOpaque(false); shuffleJB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { shuffleJBActionPerformed(evt); } }); controlPanel.add(shuffleJB); loadJB.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N loadJB.setForeground(new java.awt.Color(0, 153, 153)); loadJB.setText("LOAD"); loadJB.setToolTipText("Load Image"); loadJB.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); loadJB.setFocusable(false); loadJB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadJBActionPerformed(evt); } }); controlPanel.add(loadJB); getContentPane().add(controlPanel, java.awt.BorderLayout.SOUTH); gamePanelJP.setBackground(new java.awt.Color(204, 204, 255)); gamePanelJP.setFocusable(false); gamePanelJP.setMaximumSize(new java.awt.Dimension(240, 200)); gamePanelJP.setMinimumSize(new java.awt.Dimension(240, 200)); gamePanelJP.setPreferredSize(new java.awt.Dimension(240, 200)); gamePanelJP.setRequestFocusEnabled(false); gamePanelJP.setLayout(new java.awt.GridLayout(4, 4)); getContentPane().add(gamePanelJP, java.awt.BorderLayout.CENTER); timerPanel.setBackground(new java.awt.Color(204, 204, 255)); timerPanel.setFocusCycleRoot(true); timerPanel.setPreferredSize(new java.awt.Dimension(300, 25)); timerPanel.setLayout(new java.awt.BorderLayout()); closeJL.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N closeJL.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); closeJL.setText("X"); closeJL.setToolTipText("Close"); closeJL.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); closeJL.setFocusable(false); closeJL.setMaximumSize(new java.awt.Dimension(10, 10)); closeJL.setMinimumSize(new java.awt.Dimension(20, 20)); closeJL.setPreferredSize(new java.awt.Dimension(25, 25)); closeJL.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { closeJLMouseClicked(evt); } }); timerPanel.add(closeJL, java.awt.BorderLayout.EAST); timeJL.setEditable(false); timeJL.setBackground(new java.awt.Color(0, 102, 102)); timeJL.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N timeJL.setForeground(new java.awt.Color(255, 255, 255)); timeJL.setHorizontalAlignment(javax.swing.JTextField.CENTER); timeJL.setText("0:0"); timeJL.setToolTipText(""); timeJL.setBorder(null); timeJL.setCursor(new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR)); timeJL.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { timeJLMouseDragged(evt); } }); timeJL.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { timeJLKeyPressed(evt); } }); timerPanel.add(timeJL, java.awt.BorderLayout.CENTER); helpJL.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N helpJL.setForeground(new java.awt.Color(0, 153, 153)); helpJL.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); helpJL.setText("?"); helpJL.setToolTipText("Left Click to see Image and Right Click to Hide Controls"); helpJL.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); helpJL.setFocusable(false); helpJL.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); helpJL.setPreferredSize(new java.awt.Dimension(25, 25)); helpJL.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { helpJLMouseClicked(evt); } }); timerPanel.add(helpJL, java.awt.BorderLayout.LINE_START); getContentPane().add(timerPanel, java.awt.BorderLayout.PAGE_START); pack(); }// </editor-fold> private void initGame(){ buttons=new JButton[15]; img=new ImageIcon(getClass().getResource("/img/C15.jpg")).getImage(); icon=splitImage(img); for(int i=0;i<buttons.length;i++){ buttons[i]=new JButton(); buttons[i].setFocusable(false); buttons[i].setSize(60, 50); buttons[i].addActionListener(this); buttons[i].setIcon(icon[i]); gamePanelJP.add(buttons[i]); } swapB=new JButton(); swapB.setIcon(new ImageIcon(getClass().getResource("/img/blank.png"))); gamePanelJP.add(swapB); gamePanelJP.setVisible(true); gamePanelJP.updateUI(); } private void changeImage() { gamePanelJP.removeAll(); for (int i = 0; i < buttons.length; i++) { buttons[i].setIcon(icon[i]); gamePanelJP.add(buttons[i]); } swapB = new JButton(); swapB.setIcon(new ImageIcon(getClass().getResource("/img/blank.png"))); gamePanelJP.add(swapB); gamePanelJP.updateUI(); } private void shuffleJBActionPerformed(java.awt.event.ActionEvent evt) { shuffle(); } private void closeJLMouseClicked(java.awt.event.MouseEvent evt) { if(evt.getButton()==MouseEvent.BUTTON1){ this.dispose(); System.exit(1); } } private void timeJLKeyPressed(java.awt.event.KeyEvent evt) { if(evt.getKeyCode()==KeyEvent.VK_LEFT){ this.setLocation(this.getLocation().x-10, this.getLocation().y); } if(evt.getKeyCode()==KeyEvent.VK_RIGHT){ this.setLocation(this.getLocation().x+10, this.getLocation().y); } if(evt.getKeyCode()==KeyEvent.VK_UP){ this.setLocation(this.getLocation().x, this.getLocation().y-10); } if(evt.getKeyCode()==KeyEvent.VK_DOWN){ this.setLocation(this.getLocation().x, this.getLocation().y+10); } } private void loadJBActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser filechooser=new JFileChooser(); int response=filechooser.showOpenDialog(startStopJB); if(response==JFileChooser.APPROVE_OPTION){ img=new ImageIcon(filechooser.getSelectedFile().toString()).getImage(); icon=splitImage(img); changeImage(); } } private void startStopJBActionPerformed(java.awt.event.ActionEvent evt) { if(startStopJB.getText().equals("START")){ timer=new Timer(timeJL); timer.start(); playPauseJB.setText("PAUSE"); startStopJB.setText("STOP"); gamePanelJP.removeAll(); initGame(); }else{ timer.stopT(); startStopJB.setText("START"); playPauseJB.setText("PLAY"); timeJL.setText("0:0"); gamePanelJP.setVisible(false); } //shuffle(); } private void playPauseJBActionPerformed(java.awt.event.ActionEvent evt) { if (playPauseJB.getText().equals("PAUSE")) { playPauseJB.setText("PLAY"); timer.pauseT(); } else { playPauseJB.setText("PAUSE"); timer.resumeT(); } } private void helpJLMouseClicked(java.awt.event.MouseEvent evt) { if(evt.getButton()==MouseEvent.BUTTON1){ new Help(img,this.getX()+this.getWidth(),this.getY()).setVisible(true); } if(evt.getButton()==MouseEvent.BUTTON3){ if(controlPanel.isVisible()){ this.setSize(this.getWidth(), this.getHeight()-40); controlPanel.setVisible(false); }else{ this.setSize(this.getWidth(), this.getHeight()+40); controlPanel.setVisible(true); } } } private void timeJLMouseDragged(java.awt.event.MouseEvent evt) { setLocation(evt.getXOnScreen()-175,evt.getYOnScreen()); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new Game().setVisible(true); } }); } public void shuffle(){ gamePanelJP.removeAll(); for(int i=0;i<100;i++){ int x=(int)(Math.random()*15); gamePanelJP.add(buttons[x]); } gamePanelJP.add(swapB); gamePanelJP.updateUI(); } public void check() { boolean won = false; for (int i = 0; i < 15; i++) { if (buttons[i] == gamePanelJP.getComponent(i)) { won = true; } else { won = false; break; } } if (won) { timer.stopT(); swapB.setIcon(icon[15]); JOptionPane.showMessageDialog(gamePanelJP,"You Won! "+timeJL.getText()); startStopJB.setText("START"); playPauseJB.setText("PLAY"); } } public void move(JButton btn){ if(swapB==gamePanelJP.getComponentAt(btn.getX()+btn.getWidth(),btn.getY())){ int swapIndex=gamePanelJP.getComponentZOrder(swapB); int btnIndex=gamePanelJP.getComponentZOrder(btn); gamePanelJP.add(btn,swapIndex); gamePanelJP.add(swapB,btnIndex); gamePanelJP.updateUI(); } if(swapB==gamePanelJP.getComponentAt(btn.getX()-btn.getWidth(),btn.getY())){ int swapIndex=gamePanelJP.getComponentZOrder(swapB); int btnIndex=gamePanelJP.getComponentZOrder(btn); gamePanelJP.add(btn,swapIndex); gamePanelJP.add(swapB,btnIndex); gamePanelJP.updateUI(); } if(swapB==gamePanelJP.getComponentAt(btn.getX(),btn.getY()+btn.getHeight())){ int swapIndex=gamePanelJP.getComponentZOrder(swapB); int btnIndex=gamePanelJP.getComponentZOrder(btn); gamePanelJP.add(btn,swapIndex); gamePanelJP.add(swapB,btnIndex); gamePanelJP.updateUI(); } if(swapB==gamePanelJP.getComponentAt(btn.getX(),btn.getY()-btn.getHeight())){ int swapIndex=gamePanelJP.getComponentZOrder(swapB); int btnIndex=gamePanelJP.getComponentZOrder(btn); gamePanelJP.add(btn,swapIndex); gamePanelJP.add(swapB,btnIndex); gamePanelJP.updateUI(); } } public ImageIcon[] splitImage(Image img){ ImageIcon[] splittedIcons = new ImageIcon[16]; BufferedImage bi=new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics g=bi.createGraphics(); g.drawImage(img, 0, 0, null); int width = bi.getWidth(); int height = bi.getHeight(); int pos = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { img = bi.getSubimage(j * (width / 4), i * (height / 4), width / 4, height / 4).getScaledInstance(85, 55, 2); splittedIcons[pos] = new ImageIcon(); splittedIcons[pos].setImage(img); pos++; } } return splittedIcons; } private javax.swing.JButton swapB; private javax.swing.JButton[] buttons; private javax.swing.ImageIcon[] icon; private java.awt.Image img; private Timer timer; // Variables declaration - do not modify private javax.swing.JLabel closeJL; private javax.swing.JPanel controlPanel; private javax.swing.JPanel gamePanelJP; private javax.swing.JLabel helpJL; private javax.swing.JButton loadJB; private javax.swing.JButton playPauseJB; private javax.swing.JButton shuffleJB; private javax.swing.JButton startStopJB; private javax.swing.JTextField timeJL; private javax.swing.JPanel timerPanel; // End of variables declaration @Override public void actionPerformed(ActionEvent e) { move((JButton)e.getSource()); check(); } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461 /* * To change this template, choose Tools | Templates * and open the template in the editor. */package zatackcoder; import java.awt.Graphics;import java.awt.Image;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.MouseEvent;import java.awt.image.BufferedImage;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFileChooser;import javax.swing.JOptionPane; /** * * @author Rajesh Kumar Sahanee */public class Game extends javax.swing.JFrame implements ActionListener{ /** * Creates new form Game */ public Game() { initComponents(); gamePanelJP.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { controlPanel = new javax.swing.JPanel(); startStopJB = new javax.swing.JButton(); playPauseJB = new javax.swing.JButton(); shuffleJB = new javax.swing.JButton(); loadJB = new javax.swing.JButton(); gamePanelJP = new javax.swing.JPanel(); timerPanel = new javax.swing.JPanel(); closeJL = new javax.swing.JLabel(); timeJL = new javax.swing.JTextField(); helpJL = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(204, 204, 255)); setIconImage(new ImageIcon(getClass().getResource("/img/logo.png")).getImage()); setLocationByPlatform(true); setUndecorated(true); getContentPane().setLayout(new java.awt.BorderLayout()); controlPanel.setBackground(new java.awt.Color(204, 204, 255)); controlPanel.setFocusable(false); controlPanel.setOpaque(false); controlPanel.setPreferredSize(new java.awt.Dimension(300, 40)); controlPanel.setLayout(new java.awt.GridLayout(1, 3)); startStopJB.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N startStopJB.setForeground(new java.awt.Color(0, 153, 153)); startStopJB.setText("START"); startStopJB.setToolTipText("Start or Stop"); startStopJB.setBorder(null); startStopJB.setBorderPainted(false); startStopJB.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); startStopJB.setFocusable(false); startStopJB.setMaximumSize(new java.awt.Dimension(85, 31)); startStopJB.setMinimumSize(new java.awt.Dimension(85, 31)); startStopJB.setPreferredSize(new java.awt.Dimension(85, 31)); startStopJB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startStopJBActionPerformed(evt); } }); controlPanel.add(startStopJB); playPauseJB.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N playPauseJB.setForeground(new java.awt.Color(0, 153, 153)); playPauseJB.setText("PLAY"); playPauseJB.setToolTipText("Play or Pause"); playPauseJB.setBorder(null); playPauseJB.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); playPauseJB.setFocusable(false); playPauseJB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { playPauseJBActionPerformed(evt); } }); controlPanel.add(playPauseJB); shuffleJB.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N shuffleJB.setForeground(new java.awt.Color(0, 153, 153)); shuffleJB.setText("SHUFFLE"); shuffleJB.setToolTipText("Shuffle Tiles"); shuffleJB.setBorder(null); shuffleJB.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); shuffleJB.setFocusable(false); shuffleJB.setOpaque(false); shuffleJB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { shuffleJBActionPerformed(evt); } }); controlPanel.add(shuffleJB); loadJB.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N loadJB.setForeground(new java.awt.Color(0, 153, 153)); loadJB.setText("LOAD"); loadJB.setToolTipText("Load Image"); loadJB.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); loadJB.setFocusable(false); loadJB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadJBActionPerformed(evt); } }); controlPanel.add(loadJB); getContentPane().add(controlPanel, java.awt.BorderLayout.SOUTH); gamePanelJP.setBackground(new java.awt.Color(204, 204, 255)); gamePanelJP.setFocusable(false); gamePanelJP.setMaximumSize(new java.awt.Dimension(240, 200)); gamePanelJP.setMinimumSize(new java.awt.Dimension(240, 200)); gamePanelJP.setPreferredSize(new java.awt.Dimension(240, 200)); gamePanelJP.setRequestFocusEnabled(false); gamePanelJP.setLayout(new java.awt.GridLayout(4, 4)); getContentPane().add(gamePanelJP, java.awt.BorderLayout.CENTER); timerPanel.setBackground(new java.awt.Color(204, 204, 255)); timerPanel.setFocusCycleRoot(true); timerPanel.setPreferredSize(new java.awt.Dimension(300, 25)); timerPanel.setLayout(new java.awt.BorderLayout()); closeJL.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N closeJL.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); closeJL.setText("X"); closeJL.setToolTipText("Close"); closeJL.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); closeJL.setFocusable(false); closeJL.setMaximumSize(new java.awt.Dimension(10, 10)); closeJL.setMinimumSize(new java.awt.Dimension(20, 20)); closeJL.setPreferredSize(new java.awt.Dimension(25, 25)); closeJL.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { closeJLMouseClicked(evt); } }); timerPanel.add(closeJL, java.awt.BorderLayout.EAST); timeJL.setEditable(false); timeJL.setBackground(new java.awt.Color(0, 102, 102)); timeJL.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N timeJL.setForeground(new java.awt.Color(255, 255, 255)); timeJL.setHorizontalAlignment(javax.swing.JTextField.CENTER); timeJL.setText("0:0"); timeJL.setToolTipText(""); timeJL.setBorder(null); timeJL.setCursor(new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR)); timeJL.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { timeJLMouseDragged(evt); } }); timeJL.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { timeJLKeyPressed(evt); } }); timerPanel.add(timeJL, java.awt.BorderLayout.CENTER); helpJL.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N helpJL.setForeground(new java.awt.Color(0, 153, 153)); helpJL.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); helpJL.setText("?"); helpJL.setToolTipText("Left Click to see Image and Right Click to Hide Controls"); helpJL.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); helpJL.setFocusable(false); helpJL.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); helpJL.setPreferredSize(new java.awt.Dimension(25, 25)); helpJL.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { helpJLMouseClicked(evt); } }); timerPanel.add(helpJL, java.awt.BorderLayout.LINE_START); getContentPane().add(timerPanel, java.awt.BorderLayout.PAGE_START); pack(); }// </editor-fold> private void initGame(){ buttons=new JButton[15]; img=new ImageIcon(getClass().getResource("/img/C15.jpg")).getImage(); icon=splitImage(img); for(int i=0;i<buttons.length;i++){ buttons[i]=new JButton(); buttons[i].setFocusable(false); buttons[i].setSize(60, 50); buttons[i].addActionListener(this); buttons[i].setIcon(icon[i]); gamePanelJP.add(buttons[i]); } swapB=new JButton(); swapB.setIcon(new ImageIcon(getClass().getResource("/img/blank.png"))); gamePanelJP.add(swapB); gamePanelJP.setVisible(true); gamePanelJP.updateUI(); } private void changeImage() { gamePanelJP.removeAll(); for (int i = 0; i < buttons.length; i++) { buttons[i].setIcon(icon[i]); gamePanelJP.add(buttons[i]); } swapB = new JButton(); swapB.setIcon(new ImageIcon(getClass().getResource("/img/blank.png"))); gamePanelJP.add(swapB); gamePanelJP.updateUI(); } private void shuffleJBActionPerformed(java.awt.event.ActionEvent evt) { shuffle(); } private void closeJLMouseClicked(java.awt.event.MouseEvent evt) { if(evt.getButton()==MouseEvent.BUTTON1){ this.dispose(); System.exit(1); } } private void timeJLKeyPressed(java.awt.event.KeyEvent evt) { if(evt.getKeyCode()==KeyEvent.VK_LEFT){ this.setLocation(this.getLocation().x-10, this.getLocation().y); } if(evt.getKeyCode()==KeyEvent.VK_RIGHT){ this.setLocation(this.getLocation().x+10, this.getLocation().y); } if(evt.getKeyCode()==KeyEvent.VK_UP){ this.setLocation(this.getLocation().x, this.getLocation().y-10); } if(evt.getKeyCode()==KeyEvent.VK_DOWN){ this.setLocation(this.getLocation().x, this.getLocation().y+10); } } private void loadJBActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser filechooser=new JFileChooser(); int response=filechooser.showOpenDialog(startStopJB); if(response==JFileChooser.APPROVE_OPTION){ img=new ImageIcon(filechooser.getSelectedFile().toString()).getImage(); icon=splitImage(img); changeImage(); } } private void startStopJBActionPerformed(java.awt.event.ActionEvent evt) { if(startStopJB.getText().equals("START")){ timer=new Timer(timeJL); timer.start(); playPauseJB.setText("PAUSE"); startStopJB.setText("STOP"); gamePanelJP.removeAll(); initGame(); }else{ timer.stopT(); startStopJB.setText("START"); playPauseJB.setText("PLAY"); timeJL.setText("0:0"); gamePanelJP.setVisible(false); } //shuffle(); } private void playPauseJBActionPerformed(java.awt.event.ActionEvent evt) { if (playPauseJB.getText().equals("PAUSE")) { playPauseJB.setText("PLAY"); timer.pauseT(); } else { playPauseJB.setText("PAUSE"); timer.resumeT(); } } private void helpJLMouseClicked(java.awt.event.MouseEvent evt) { if(evt.getButton()==MouseEvent.BUTTON1){ new Help(img,this.getX()+this.getWidth(),this.getY()).setVisible(true); } if(evt.getButton()==MouseEvent.BUTTON3){ if(controlPanel.isVisible()){ this.setSize(this.getWidth(), this.getHeight()-40); controlPanel.setVisible(false); }else{ this.setSize(this.getWidth(), this.getHeight()+40); controlPanel.setVisible(true); } } } private void timeJLMouseDragged(java.awt.event.MouseEvent evt) { setLocation(evt.getXOnScreen()-175,evt.getYOnScreen()); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new Game().setVisible(true); } }); } public void shuffle(){ gamePanelJP.removeAll(); for(int i=0;i<100;i++){ int x=(int)(Math.random()*15); gamePanelJP.add(buttons[x]); } gamePanelJP.add(swapB); gamePanelJP.updateUI(); } public void check() { boolean won = false; for (int i = 0; i < 15; i++) { if (buttons[i] == gamePanelJP.getComponent(i)) { won = true; } else { won = false; break; } } if (won) { timer.stopT(); swapB.setIcon(icon[15]); JOptionPane.showMessageDialog(gamePanelJP,"You Won! "+timeJL.getText()); startStopJB.setText("START"); playPauseJB.setText("PLAY"); } } public void move(JButton btn){ if(swapB==gamePanelJP.getComponentAt(btn.getX()+btn.getWidth(),btn.getY())){ int swapIndex=gamePanelJP.getComponentZOrder(swapB); int btnIndex=gamePanelJP.getComponentZOrder(btn); gamePanelJP.add(btn,swapIndex); gamePanelJP.add(swapB,btnIndex); gamePanelJP.updateUI(); } if(swapB==gamePanelJP.getComponentAt(btn.getX()-btn.getWidth(),btn.getY())){ int swapIndex=gamePanelJP.getComponentZOrder(swapB); int btnIndex=gamePanelJP.getComponentZOrder(btn); gamePanelJP.add(btn,swapIndex); gamePanelJP.add(swapB,btnIndex); gamePanelJP.updateUI(); } if(swapB==gamePanelJP.getComponentAt(btn.getX(),btn.getY()+btn.getHeight())){ int swapIndex=gamePanelJP.getComponentZOrder(swapB); int btnIndex=gamePanelJP.getComponentZOrder(btn); gamePanelJP.add(btn,swapIndex); gamePanelJP.add(swapB,btnIndex); gamePanelJP.updateUI(); } if(swapB==gamePanelJP.getComponentAt(btn.getX(),btn.getY()-btn.getHeight())){ int swapIndex=gamePanelJP.getComponentZOrder(swapB); int btnIndex=gamePanelJP.getComponentZOrder(btn); gamePanelJP.add(btn,swapIndex); gamePanelJP.add(swapB,btnIndex); gamePanelJP.updateUI(); } } public ImageIcon[] splitImage(Image img){ ImageIcon[] splittedIcons = new ImageIcon[16]; BufferedImage bi=new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics g=bi.createGraphics(); g.drawImage(img, 0, 0, null); int width = bi.getWidth(); int height = bi.getHeight(); int pos = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { img = bi.getSubimage(j * (width / 4), i * (height / 4), width / 4, height / 4).getScaledInstance(85, 55, 2); splittedIcons[pos] = new ImageIcon(); splittedIcons[pos].setImage(img); pos++; } } return splittedIcons; } private javax.swing.JButton swapB; private javax.swing.JButton[] buttons; private javax.swing.ImageIcon[] icon; private java.awt.Image img; private Timer timer; // Variables declaration - do not modify private javax.swing.JLabel closeJL; private javax.swing.JPanel controlPanel; private javax.swing.JPanel gamePanelJP; private javax.swing.JLabel helpJL; private javax.swing.JButton loadJB; private javax.swing.JButton playPauseJB; private javax.swing.JButton shuffleJB; private javax.swing.JButton startStopJB; private javax.swing.JTextField timeJL; private javax.swing.JPanel timerPanel; // End of variables declaration @Override public void actionPerformed(ActionEvent e) { move((JButton)e.getSource()); check(); }} Help.java Help.java Java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package zatackcoder; import java.awt.Image; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; /** * * @author Rajesh Kumar Sahanee */ public class Help extends javax.swing.JFrame { /** * Creates new form Help */ public Help(Image img,int x,int y) { initComponents(); setLabelIcon(img); this.setLocation(x, y); } private void setLabelIcon(Image img){ BufferedImage bi=new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); bi.createGraphics().drawImage(img, 0, 0, null); img=bi.getScaledInstance(jLabel1.getWidth(),jLabel1.getHeight(), 1); jLabel1.setIcon(new ImageIcon(img)); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setAlwaysOnTop(true); setIconImage(new ImageIcon(getClass().getResource("/img/logo.png")).getImage()); setLocationByPlatform(true); setUndecorated(true); jLabel1.setPreferredSize(new java.awt.Dimension(240, 200)); jLabel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel1MouseClicked(evt); } }); getContentPane().add(jLabel1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold> private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) { this.dispose(); } /** * @param args the command line arguments */ // Variables declaration - do not modify private javax.swing.JLabel jLabel1; // End of variables declaration } 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 /* * To change this template, choose Tools | Templates * and open the template in the editor. */package zatackcoder; import java.awt.Image;import java.awt.image.BufferedImage;import javax.swing.ImageIcon;/** * * @author Rajesh Kumar Sahanee */public class Help extends javax.swing.JFrame { /** * Creates new form Help */ public Help(Image img,int x,int y) { initComponents(); setLabelIcon(img); this.setLocation(x, y); } private void setLabelIcon(Image img){ BufferedImage bi=new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); bi.createGraphics().drawImage(img, 0, 0, null); img=bi.getScaledInstance(jLabel1.getWidth(),jLabel1.getHeight(), 1); jLabel1.setIcon(new ImageIcon(img)); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setAlwaysOnTop(true); setIconImage(new ImageIcon(getClass().getResource("/img/logo.png")).getImage()); setLocationByPlatform(true); setUndecorated(true); jLabel1.setPreferredSize(new java.awt.Dimension(240, 200)); jLabel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel1MouseClicked(evt); } }); getContentPane().add(jLabel1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold> private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) { this.dispose(); } /** * @param args the command line arguments */ // Variables declaration - do not modify private javax.swing.JLabel jLabel1; // End of variables declaration } Timer.java Timer.java Java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package zatackcoder; import javax.swing.JTextField; /** * * @author Rajesh Kumar Sahanee */ public class Timer extends Thread{ boolean pause; boolean exit; JTextField tf; int min=0,sec=0; public Timer(JTextField tf){ this.tf=tf; } @Override public void run(){ min=0;sec=0; while (!exit) { if(!pause){ timeLoop(); }else{ } } } public void timeLoop(){ try { tf.setText("" + min + ":" + sec); if (sec == 59) { min += 1; sec = 0; } Thread.sleep(1000); sec++; } catch (InterruptedException ex) { System.out.println(ex); } } public synchronized void resumeT(){ pause=false; } public synchronized void pauseT(){ pause=true; } public synchronized void stopT(){ exit=true; } } 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 /* * To change this template, choose Tools | Templates * and open the template in the editor. */package zatackcoder; import javax.swing.JTextField; /** * * @author Rajesh Kumar Sahanee */public class Timer extends Thread{ boolean pause; boolean exit; JTextField tf; int min=0,sec=0; public Timer(JTextField tf){ this.tf=tf; } @Override public void run(){ min=0;sec=0; while (!exit) { if(!pause){ timeLoop(); }else{ } } } public void timeLoop(){ try { tf.setText("" + min + ":" + sec); if (sec == 59) { min += 1; sec = 0; } Thread.sleep(1000); sec++; } catch (InterruptedException ex) { System.out.println(ex); } } public synchronized void resumeT(){ pause=false; } public synchronized void pauseT(){ pause=true; } public synchronized void stopT(){ exit=true; }} Output Executable Jar Download Tile Puzzle Game Jar File 1 file(s) 159.28 KB Download Netbeans Project Download Tile Puzzle Game Netbeans Project 1 file(s) 437.08 KB Download Thanks Please Like & Share