
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
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
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.