Matching Game in Java Java Java Projects by Rajesh Kumar Sahanee - February 15, 2019April 13, 20201 Post Views: 8,186 Hello Friends, I hope you are doing fine. Today I am going to share a Matching Game in Java. Matching games are games in which players have to find match similar elements. As the name implies, participants need to find a match for a word, picture, or card. I have developed this game when I was learning Java. In this game you can load your own images using Load button. I had used NetBeans IDE to develop this game. This game also play sounds on different events i.e when player wins or loose or finds correct match. Now I am sharing it, so that anyone need it can use it. By the way a Java learner can learn a lot from this code. So, Here is the code.. MainFrame.java MainFrame.java Java package game; 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 java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * * @author Rajesh Kumar Sahanee */ public class MainFrame extends javax.swing.JFrame implements ActionListener { /** * Creates new form MainFrame */ public MainFrame() { initComponents(); initIcons(); initGame(); } private void initGame() { score = 0; int x = 0; for (int i = 0; i < tiles.length; i++) { tiles[i] = new Tile(icons[x], new ImageIcon(getClass().getResource("/images/logo.png"))); tiles[i].addActionListener(this); gamePanel.add(tiles[i]); if ((i + 1) % 2 == 0) { x++; } } title.setText("Score: " + score); shuffle(); } private void initIcons() { Image img; for (int i = 0; i < icons.length; i++) { img = new ImageIcon(getClass().getResource("/images/img" + i + ".png")).getImage(); icons[i] = createIcon(img); } } private ImageIcon createIcon(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(80, 80, 1); return new ImageIcon(img); } private void showHelp() { //if tiles[0] would be null than all the tiles would be null here if (tiles[0] != null) { for (int i = 0; i < tiles.length; i++) { if (!tiles[i].isNoIcon()) { tiles[i].showTile(); tiles[i].removeActionListener(this); } } score -= 50; title.setText("Score: " + score); } } private void hideHelp() { for (int i = 0; i < tiles.length; i++) { if (!tiles[i].isNoIcon()) { tiles[i].hideTile(); tiles[i].addActionListener(this); } } } private void check() { if (predict1 != predict2 && predict1.getImage() == predict2.getImage()) { new Thread() { @Override public void run() { Sound sound = null; try { sound = new Sound(getClass().getResource("/sounds/guess.wav")); } catch (Exception e) { } InputStream stream = new ByteArrayInputStream(sound.getSamples()); sound.play(stream); } }.start();//sound new Thread() { @Override public void run() { for (int i = 0; i < 3; i++) { try { predict1.hideTile(); predict2.hideTile(); Thread.sleep(100); predict1.showTile(); predict2.showTile(); Thread.sleep(100); } catch (InterruptedException ex) { System.out.println(ex); } } predict1.setNoIcon(); predict2.setNoIcon(); for (int i = 0; i < tiles.length; i++) { if (!tiles[i].isNoIcon()) { won = false; break; } else { won = true; } } if (won) { if (score > 0) { new Thread() { @Override public void run() { Sound sound = null; try { sound = new Sound(getClass().getResource("/sounds/won.wav")); } catch (Exception e) { } InputStream stream = new ByteArrayInputStream(sound.getSamples()); sound.play(stream); } }.start();//won sound JOptionPane.showMessageDialog(gamePanel, "You Won! Your Score is " + score); } else { new Thread() { @Override public void run() { Sound sound = null; try { sound = new Sound(getClass().getResource("/sounds/loose.wav")); } catch (Exception e) { } InputStream stream = new ByteArrayInputStream(sound.getSamples()); sound.play(stream); } }.start();//loose sound JOptionPane.showMessageDialog(gamePanel, "You Loose! Your Score is " + score); } initGame(); } } }.start();//animation predict1.removeActionListener(this); predict2.removeActionListener(this); score += 100; title.setText("Score: " + score); } else { predict1.hideTile(); predict2.hideTile(); score -= 10; title.setText("Score: " + score); } } private void shuffle() { gamePanel.removeAll(); ArrayList<Integer> al = new ArrayList<Integer>(); for (int i = 0; i < 36;) { int x = (int) (Math.random() * 36); if (!al.contains(x)) { al.add(x); i++; } } for (int i = 0; i < 36; i++) { gamePanel.add(tiles[al.get(i)]); tiles[al.get(i)].hideTile(); } } /** * 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() { titlePanel = new javax.swing.JPanel(); title = new javax.swing.JTextField(); close = new javax.swing.JLabel(); help = new javax.swing.JLabel(); gamePanel = new javax.swing.JPanel(); controlPanel = new javax.swing.JPanel(); play = new javax.swing.JButton(); load = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Matching Game"); setBackground(new java.awt.Color(204, 204, 255)); setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage()); setLocationByPlatform(true); setName("MainFrame"); // NOI18N setUndecorated(true); titlePanel.setBackground(new java.awt.Color(153, 0, 153)); titlePanel.setPreferredSize(new java.awt.Dimension(300, 25)); titlePanel.setLayout(new java.awt.BorderLayout()); title.setEditable(false); title.setBackground(new java.awt.Color(153, 153, 255)); title.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N title.setForeground(new java.awt.Color(255, 255, 255)); title.setHorizontalAlignment(javax.swing.JTextField.CENTER); title.setText("Score: "); title.setToolTipText("After Clicking mouse here use arrow keys to move"); title.setBorder(null); title.setCursor(new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR)); title.setSelectionColor(new java.awt.Color(153, 153, 255)); title.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { titleMouseDragged(evt); } }); title.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { titleKeyPressed(evt); } }); titlePanel.add(title, java.awt.BorderLayout.CENTER); close.setBackground(new java.awt.Color(0, 153, 153)); close.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N close.setForeground(new java.awt.Color(255, 255, 255)); close.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); close.setText("X"); close.setToolTipText("Close"); close.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); close.setPreferredSize(new java.awt.Dimension(25, 25)); close.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { closeMouseClicked(evt); } }); titlePanel.add(close, java.awt.BorderLayout.LINE_END); help.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N help.setForeground(new java.awt.Color(255, 255, 255)); help.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); help.setText("?"); help.setToolTipText("Right click to hide controls and Left click to see Images"); help.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); help.setPreferredSize(new java.awt.Dimension(25, 25)); help.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { helpMouseClicked(evt); } }); titlePanel.add(help, java.awt.BorderLayout.LINE_START); getContentPane().add(titlePanel, java.awt.BorderLayout.NORTH); gamePanel.setBackground(new java.awt.Color(153, 0, 153)); gamePanel.setPreferredSize(new java.awt.Dimension(630, 630)); gamePanel.setLayout(new java.awt.GridLayout(6, 6, 5, 5)); getContentPane().add(gamePanel, java.awt.BorderLayout.CENTER); controlPanel.setBackground(new java.awt.Color(153, 153, 255)); controlPanel.setPreferredSize(new java.awt.Dimension(300, 40)); controlPanel.setLayout(new java.awt.GridLayout(1, 2)); play.setBackground(new java.awt.Color(153, 0, 153)); play.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N play.setForeground(new java.awt.Color(153, 153, 255)); play.setText("PLAY"); play.setToolTipText("Play new Game"); play.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); play.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { playActionPerformed(evt); } }); controlPanel.add(play); load.setBackground(new java.awt.Color(153, 0, 153)); load.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N load.setForeground(new java.awt.Color(153, 153, 255)); load.setText("LOAD"); load.setToolTipText("Load your favourite images"); load.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); load.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadActionPerformed(evt); } }); controlPanel.add(load); getContentPane().add(controlPanel, java.awt.BorderLayout.SOUTH); pack(); }// </editor-fold> private void closeMouseClicked(java.awt.event.MouseEvent evt) { if (evt.getButton() == MouseEvent.BUTTON1) { this.dispose(); } } private void helpMouseClicked(java.awt.event.MouseEvent evt) { if (evt.getButton() == MouseEvent.BUTTON1) { if (!helping) { new Thread() { @Override public void run() { try { helping = true; showHelp(); Thread.sleep(10000); hideHelp(); helping = false; } catch (InterruptedException ex) { System.out.println(ex); } } }.start(); } } if (evt.getButton() == MouseEvent.BUTTON3) { if (controlPanel.isVisible()) { setSize(600, 625); controlPanel.setVisible(false); } else { setSize(600, 665); controlPanel.setVisible(true); } } } private void titleKeyPressed(java.awt.event.KeyEvent evt) { if (evt.getKeyCode() == KeyEvent.VK_LEFT) { setLocation(getX() - 5, getY()); } if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { setLocation(getX() + 5, getY()); } if (evt.getKeyCode() == KeyEvent.VK_UP) { setLocation(getX(), getY() - 5); } if (evt.getKeyCode() == KeyEvent.VK_DOWN) { setLocation(getX(), getY() + 5); } } private void loadActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(true); int response = chooser.showOpenDialog(predict1); if (response == JFileChooser.APPROVE_OPTION) { File[] file = chooser.getSelectedFiles(); if (file.length >= 18) { for (int i = 0; i < 18; i++) { icons[i] = createIcon(new ImageIcon(file[i].toString()).getImage()); } initGame(); } else { JOptionPane.showMessageDialog(gamePanel, "Please select 18 Files !"); } } } private void playActionPerformed(java.awt.event.ActionEvent evt) { initGame(); } private void titleMouseDragged(java.awt.event.MouseEvent evt) { setLocation(evt.getXOnScreen() - 300, 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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { //do animation here if want //sleep here new MainFrame().setVisible(true); } }); } Tile[] tiles = new Tile[36]; ImageIcon[] icons = new ImageIcon[18]; int status, score; Tile predict1, predict2; private boolean won, helping; // Variables declaration - do not modify private javax.swing.JLabel close; private javax.swing.JPanel controlPanel; private javax.swing.JPanel gamePanel; private javax.swing.JLabel help; private javax.swing.JButton load; private javax.swing.JButton play; private javax.swing.JTextField title; private javax.swing.JPanel titlePanel; // End of variables declaration @Override public void actionPerformed(ActionEvent e) { if (status == 0) { predict1 = (Tile) e.getSource(); predict1.showTile(); status++; } else if (status == 1) { status++; predict2 = (Tile) e.getSource(); new Thread() { @Override public void run() { try { predict2.showTile(); Thread.sleep(500); check(); Thread.sleep(600); status = 0; } catch (Exception e) { System.out.println(e); } } }.start(); } } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480 package game; 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 java.io.ByteArrayInputStream;import java.io.File;import java.io.InputStream;import java.util.ArrayList;import javax.swing.ImageIcon;import javax.swing.JFileChooser;import javax.swing.JOptionPane; /** * * @author Rajesh Kumar Sahanee */public class MainFrame extends javax.swing.JFrame implements ActionListener { /** * Creates new form MainFrame */ public MainFrame() { initComponents(); initIcons(); initGame(); } private void initGame() { score = 0; int x = 0; for (int i = 0; i < tiles.length; i++) { tiles[i] = new Tile(icons[x], new ImageIcon(getClass().getResource("/images/logo.png"))); tiles[i].addActionListener(this); gamePanel.add(tiles[i]); if ((i + 1) % 2 == 0) { x++; } } title.setText("Score: " + score); shuffle(); } private void initIcons() { Image img; for (int i = 0; i < icons.length; i++) { img = new ImageIcon(getClass().getResource("/images/img" + i + ".png")).getImage(); icons[i] = createIcon(img); } } private ImageIcon createIcon(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(80, 80, 1); return new ImageIcon(img); } private void showHelp() { //if tiles[0] would be null than all the tiles would be null here if (tiles[0] != null) { for (int i = 0; i < tiles.length; i++) { if (!tiles[i].isNoIcon()) { tiles[i].showTile(); tiles[i].removeActionListener(this); } } score -= 50; title.setText("Score: " + score); } } private void hideHelp() { for (int i = 0; i < tiles.length; i++) { if (!tiles[i].isNoIcon()) { tiles[i].hideTile(); tiles[i].addActionListener(this); } } } private void check() { if (predict1 != predict2 && predict1.getImage() == predict2.getImage()) { new Thread() { @Override public void run() { Sound sound = null; try { sound = new Sound(getClass().getResource("/sounds/guess.wav")); } catch (Exception e) { } InputStream stream = new ByteArrayInputStream(sound.getSamples()); sound.play(stream); } }.start();//sound new Thread() { @Override public void run() { for (int i = 0; i < 3; i++) { try { predict1.hideTile(); predict2.hideTile(); Thread.sleep(100); predict1.showTile(); predict2.showTile(); Thread.sleep(100); } catch (InterruptedException ex) { System.out.println(ex); } } predict1.setNoIcon(); predict2.setNoIcon(); for (int i = 0; i < tiles.length; i++) { if (!tiles[i].isNoIcon()) { won = false; break; } else { won = true; } } if (won) { if (score > 0) { new Thread() { @Override public void run() { Sound sound = null; try { sound = new Sound(getClass().getResource("/sounds/won.wav")); } catch (Exception e) { } InputStream stream = new ByteArrayInputStream(sound.getSamples()); sound.play(stream); } }.start();//won sound JOptionPane.showMessageDialog(gamePanel, "You Won! Your Score is " + score); } else { new Thread() { @Override public void run() { Sound sound = null; try { sound = new Sound(getClass().getResource("/sounds/loose.wav")); } catch (Exception e) { } InputStream stream = new ByteArrayInputStream(sound.getSamples()); sound.play(stream); } }.start();//loose sound JOptionPane.showMessageDialog(gamePanel, "You Loose! Your Score is " + score); } initGame(); } } }.start();//animation predict1.removeActionListener(this); predict2.removeActionListener(this); score += 100; title.setText("Score: " + score); } else { predict1.hideTile(); predict2.hideTile(); score -= 10; title.setText("Score: " + score); } } private void shuffle() { gamePanel.removeAll(); ArrayList<Integer> al = new ArrayList<Integer>(); for (int i = 0; i < 36;) { int x = (int) (Math.random() * 36); if (!al.contains(x)) { al.add(x); i++; } } for (int i = 0; i < 36; i++) { gamePanel.add(tiles[al.get(i)]); tiles[al.get(i)].hideTile(); } } /** * 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() { titlePanel = new javax.swing.JPanel(); title = new javax.swing.JTextField(); close = new javax.swing.JLabel(); help = new javax.swing.JLabel(); gamePanel = new javax.swing.JPanel(); controlPanel = new javax.swing.JPanel(); play = new javax.swing.JButton(); load = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Matching Game"); setBackground(new java.awt.Color(204, 204, 255)); setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage()); setLocationByPlatform(true); setName("MainFrame"); // NOI18N setUndecorated(true); titlePanel.setBackground(new java.awt.Color(153, 0, 153)); titlePanel.setPreferredSize(new java.awt.Dimension(300, 25)); titlePanel.setLayout(new java.awt.BorderLayout()); title.setEditable(false); title.setBackground(new java.awt.Color(153, 153, 255)); title.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N title.setForeground(new java.awt.Color(255, 255, 255)); title.setHorizontalAlignment(javax.swing.JTextField.CENTER); title.setText("Score: "); title.setToolTipText("After Clicking mouse here use arrow keys to move"); title.setBorder(null); title.setCursor(new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR)); title.setSelectionColor(new java.awt.Color(153, 153, 255)); title.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { titleMouseDragged(evt); } }); title.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { titleKeyPressed(evt); } }); titlePanel.add(title, java.awt.BorderLayout.CENTER); close.setBackground(new java.awt.Color(0, 153, 153)); close.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N close.setForeground(new java.awt.Color(255, 255, 255)); close.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); close.setText("X"); close.setToolTipText("Close"); close.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); close.setPreferredSize(new java.awt.Dimension(25, 25)); close.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { closeMouseClicked(evt); } }); titlePanel.add(close, java.awt.BorderLayout.LINE_END); help.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N help.setForeground(new java.awt.Color(255, 255, 255)); help.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); help.setText("?"); help.setToolTipText("Right click to hide controls and Left click to see Images"); help.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); help.setPreferredSize(new java.awt.Dimension(25, 25)); help.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { helpMouseClicked(evt); } }); titlePanel.add(help, java.awt.BorderLayout.LINE_START); getContentPane().add(titlePanel, java.awt.BorderLayout.NORTH); gamePanel.setBackground(new java.awt.Color(153, 0, 153)); gamePanel.setPreferredSize(new java.awt.Dimension(630, 630)); gamePanel.setLayout(new java.awt.GridLayout(6, 6, 5, 5)); getContentPane().add(gamePanel, java.awt.BorderLayout.CENTER); controlPanel.setBackground(new java.awt.Color(153, 153, 255)); controlPanel.setPreferredSize(new java.awt.Dimension(300, 40)); controlPanel.setLayout(new java.awt.GridLayout(1, 2)); play.setBackground(new java.awt.Color(153, 0, 153)); play.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N play.setForeground(new java.awt.Color(153, 153, 255)); play.setText("PLAY"); play.setToolTipText("Play new Game"); play.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); play.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { playActionPerformed(evt); } }); controlPanel.add(play); load.setBackground(new java.awt.Color(153, 0, 153)); load.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N load.setForeground(new java.awt.Color(153, 153, 255)); load.setText("LOAD"); load.setToolTipText("Load your favourite images"); load.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); load.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadActionPerformed(evt); } }); controlPanel.add(load); getContentPane().add(controlPanel, java.awt.BorderLayout.SOUTH); pack(); }// </editor-fold> private void closeMouseClicked(java.awt.event.MouseEvent evt) { if (evt.getButton() == MouseEvent.BUTTON1) { this.dispose(); } } private void helpMouseClicked(java.awt.event.MouseEvent evt) { if (evt.getButton() == MouseEvent.BUTTON1) { if (!helping) { new Thread() { @Override public void run() { try { helping = true; showHelp(); Thread.sleep(10000); hideHelp(); helping = false; } catch (InterruptedException ex) { System.out.println(ex); } } }.start(); } } if (evt.getButton() == MouseEvent.BUTTON3) { if (controlPanel.isVisible()) { setSize(600, 625); controlPanel.setVisible(false); } else { setSize(600, 665); controlPanel.setVisible(true); } } } private void titleKeyPressed(java.awt.event.KeyEvent evt) { if (evt.getKeyCode() == KeyEvent.VK_LEFT) { setLocation(getX() - 5, getY()); } if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { setLocation(getX() + 5, getY()); } if (evt.getKeyCode() == KeyEvent.VK_UP) { setLocation(getX(), getY() - 5); } if (evt.getKeyCode() == KeyEvent.VK_DOWN) { setLocation(getX(), getY() + 5); } } private void loadActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(true); int response = chooser.showOpenDialog(predict1); if (response == JFileChooser.APPROVE_OPTION) { File[] file = chooser.getSelectedFiles(); if (file.length >= 18) { for (int i = 0; i < 18; i++) { icons[i] = createIcon(new ImageIcon(file[i].toString()).getImage()); } initGame(); } else { JOptionPane.showMessageDialog(gamePanel, "Please select 18 Files !"); } } } private void playActionPerformed(java.awt.event.ActionEvent evt) { initGame(); } private void titleMouseDragged(java.awt.event.MouseEvent evt) { setLocation(evt.getXOnScreen() - 300, 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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { //do animation here if want //sleep here new MainFrame().setVisible(true); } }); } Tile[] tiles = new Tile[36]; ImageIcon[] icons = new ImageIcon[18]; int status, score; Tile predict1, predict2; private boolean won, helping; // Variables declaration - do not modify private javax.swing.JLabel close; private javax.swing.JPanel controlPanel; private javax.swing.JPanel gamePanel; private javax.swing.JLabel help; private javax.swing.JButton load; private javax.swing.JButton play; private javax.swing.JTextField title; private javax.swing.JPanel titlePanel; // End of variables declaration @Override public void actionPerformed(ActionEvent e) { if (status == 0) { predict1 = (Tile) e.getSource(); predict1.showTile(); status++; } else if (status == 1) { status++; predict2 = (Tile) e.getSource(); new Thread() { @Override public void run() { try { predict2.showTile(); Thread.sleep(500); check(); Thread.sleep(600); status = 0; } catch (Exception e) { System.out.println(e); } } }.start(); } }} Tile.java Tile.java Java package game; import javax.swing.ImageIcon; import javax.swing.JButton; /** * * @author Rajesh Kumar Sahanee */ class Tile extends JButton { ImageIcon icon1; ImageIcon icon2; private boolean hidden, noIcon; public Tile(ImageIcon icon1, ImageIcon icon2) { this.icon1 = icon1; this.icon2 = icon2; setSize(100, 100); setFocusable(false); } public synchronized void showTile() { setIcon(icon1); hidden = false; } public synchronized void hideTile() { setIcon(icon2); hidden = true; } public synchronized void setNoIcon() { setIcon(null); noIcon = true; } public ImageIcon getImage() { return icon1; } public synchronized boolean isNoIcon() { return noIcon; } } 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 package game; import javax.swing.ImageIcon;import javax.swing.JButton; /** * * @author Rajesh Kumar Sahanee */class Tile extends JButton { ImageIcon icon1; ImageIcon icon2; private boolean hidden, noIcon; public Tile(ImageIcon icon1, ImageIcon icon2) { this.icon1 = icon1; this.icon2 = icon2; setSize(100, 100); setFocusable(false); } public synchronized void showTile() { setIcon(icon1); hidden = false; } public synchronized void hideTile() { setIcon(icon2); hidden = true; } public synchronized void setNoIcon() { setIcon(null); noIcon = true; } public ImageIcon getImage() { return icon1; } public synchronized boolean isNoIcon() { return noIcon; } } Sound.java Sound.java Java package game; /** * * @author Rajesh Kumar Sahanee */ import java.io.*; import java.net.URL; import javax.sound.sampled.*; /** * The Sound encapsulates a sound that can be opened from the file system and * later played. */ public class Sound { private AudioFormat format; private byte[] samples; /** * Opens a sound from a file. */ public Sound(URL filename) { try { // open the audio input stream AudioInputStream stream = AudioSystem.getAudioInputStream(filename); format = stream.getFormat(); // get the audio samples samples = getSamples(stream); } catch (UnsupportedAudioFileException ex) { System.out.println(ex); } catch (IOException ex) { System.out.println(ex); } } /** * Gets the samples of this sound as a byte array. */ public byte[] getSamples() { return samples; } /** * Gets the samples from an AudioInputStream as an array of bytes. */ private byte[] getSamples(AudioInputStream audioStream) { // get the number of bytes to read int length = (int) (audioStream.getFrameLength() * format.getFrameSize()); // read the entire stream byte[] samples = new byte[length]; DataInputStream is = new DataInputStream(audioStream); try { is.readFully(samples); } catch (IOException ex) { System.out.println(ex); } // return the samples return samples; } /** * Plays a stream. This method blocks (doesn't return) until the sound is * finished playing. */ public void play(InputStream source) { // use a short, 100ms (1/10th sec) buffer for real-time // change to the sound stream int bufferSize = format.getFrameSize() * Math.round(format.getSampleRate() / 10); byte[] buffer = new byte[bufferSize]; // create a line to play to SourceDataLine line; try { DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); line = (SourceDataLine) AudioSystem.getLine(info); line.open(format, bufferSize); } catch (LineUnavailableException ex) { System.out.println(ex); return; } // start the line line.start(); //copy data to the line try { int numBytesRead = 0; while (numBytesRead != -1) { numBytesRead = source.read(buffer, 0, buffer.length); if (numBytesRead != -1) { line.write(buffer, 0, numBytesRead); } } } catch (IOException ex) { System.out.println(ex); } // wait until all data is played line.drain(); // close the line line.close(); } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 package game; /** * * @author Rajesh Kumar Sahanee */import java.io.*;import java.net.URL;import javax.sound.sampled.*; /** * The Sound encapsulates a sound that can be opened from the file system and * later played. */public class Sound { private AudioFormat format; private byte[] samples; /** * Opens a sound from a file. */ public Sound(URL filename) { try { // open the audio input stream AudioInputStream stream = AudioSystem.getAudioInputStream(filename); format = stream.getFormat(); // get the audio samples samples = getSamples(stream); } catch (UnsupportedAudioFileException ex) { System.out.println(ex); } catch (IOException ex) { System.out.println(ex); } } /** * Gets the samples of this sound as a byte array. */ public byte[] getSamples() { return samples; } /** * Gets the samples from an AudioInputStream as an array of bytes. */ private byte[] getSamples(AudioInputStream audioStream) { // get the number of bytes to read int length = (int) (audioStream.getFrameLength() * format.getFrameSize()); // read the entire stream byte[] samples = new byte[length]; DataInputStream is = new DataInputStream(audioStream); try { is.readFully(samples); } catch (IOException ex) { System.out.println(ex); } // return the samples return samples; } /** * Plays a stream. This method blocks (doesn't return) until the sound is * finished playing. */ public void play(InputStream source) { // use a short, 100ms (1/10th sec) buffer for real-time // change to the sound stream int bufferSize = format.getFrameSize() * Math.round(format.getSampleRate() / 10); byte[] buffer = new byte[bufferSize]; // create a line to play to SourceDataLine line; try { DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); line = (SourceDataLine) AudioSystem.getLine(info); line.open(format, bufferSize); } catch (LineUnavailableException ex) { System.out.println(ex); return; } // start the line line.start(); //copy data to the line try { int numBytesRead = 0; while (numBytesRead != -1) { numBytesRead = source.read(buffer, 0, buffer.length); if (numBytesRead != -1) { line.write(buffer, 0, numBytesRead); } } } catch (IOException ex) { System.out.println(ex); } // wait until all data is played line.drain(); // close the line line.close(); } } Output NetBeans Project Download Matching Game 1 file(s) 1.34 MB Download Thanks for stopping by, Please do share if you like it
Hey I am so delighted I found your blog, I really found you by accident, while I was browsing on Bing for something else, Nonetheless I am here now and would just like to say kudos for a fantastic post and a all round thrilling blog (I also love the theme/design), I don’t have time to look over it all at the minute but I have bookmarked it and also added in your RSS feeds, so when I have time I will be back to read more, Please do keep up the excellent b. Reply