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
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 |
/* * 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
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 |
/* * 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
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 |
/* * 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
Netbeans Project Download
Tile Puzzle Game Netbeans Project
Thanks Please Like & Share
Comments