Selasa, 30 Mei 2017

Contoh Game Sederhana JAVA ( ULAR MENCARI MAKANAN )

GAME ULAR MENCARI MAKANAN

      Kali ini saya akan memberikan contoh tentang sebuah game java sederhana yang pernah saya buat dan ini merupakan game Ke Tiga yang saya buat dengan menggunakan bahasa pemograman Java. Mungkin bagi temen - temen yang ingin mengembangkan game saya ini menjadi lebih baik lagi silakan saja.





Logika game ini adalah :


* Player harus menjalankan  Ular untuk mencari makanan yg berbentuk lingkaran  merah dengan          cepat dan tepat yang untuk mendapatkan point.
* Player harus menjalankan Ular biar tidak menabrak diding arena supaya tidak mati bro..hehehe  :D )
* Player semakin banyak memakan maka akan mendapatkan poit banyak dan semakin banyak makan    pula semakin panjang ularnya alias dowo uler'e bro..hehehe :D )
  • Game ini terdiri dari ini semua bro.


Class engin


package Snake_engin;

import javax.swing.JOptionPane;
import m_snake.MainPanel.snakeBody.Food;
import m_snake.MainPanel.snakeBody.snake;

public class engin {
    
   
    public engin() 
    {
   
    }

    public   void Move_mySnake(int newDirection,boolean food_eaten)
    {
       
      
        if(!Game_Over)
        {
        
        switch(newDirection)
        {
            case 1:    if(direction!=3)
                            {
                       my_snake.put_Head_postion(0,-step_to_move);
                      direction=1;
                            }
                    else move_as_last(direction);
                       break;//UP
                       
            case 2:   if(direction!=4)   
                       {
                   my_snake.put_Head_postion(step_to_move,0);
                     direction=2; 
                            }
                        else move_as_last(direction);
                    break;//RIGHT
            case 3:    
                      if(direction!=1)
                      {
                   my_snake.put_Head_postion(0,step_to_move);
                      direction=3;
                      }
                      else move_as_last(direction);
                     break;//DOWN
                                  
            case 4:   
                       if(direction!=2)
                       {
                  my_snake.put_Head_postion(-step_to_move,0);
                        direction=4; 
                       }
                      else move_as_last(direction);
                     
                      break;//LEFT
        } 
      
          
            if(food_eaten)
            {
               my_snake.Increase_lenght();// IF the Snake ate new Food
            }
        my_snake.Move_snake();
        
      
       if((my_snake.getHeadX()==snakeFood.get_int_X())&&(my_snake.getHeadY()== snakeFood.get_int_Y()))
        {
            snakeFood.getFood();
            Score+=20;
            
            my_snake.Increase_lenght();
            while(check_food_place())
            {
               snakeFood.getFood();    
            }
            
        }
        
        Game_Over=my_snake.check_game_over();
        
        
        }
        if(Game_Over)
        {
            JOptionPane.showConfirmDialog(null,"Score = "+Integer.toString(Score),"Your Score",JOptionPane.DEFAULT_OPTION);
        //    Thread.yield();
        }
                 
        
    }
    public void move_as_last(int diirec)
    {
         switch(direction)
        {
            case 1:    
                           
                       my_snake.put_Head_postion(0,-step_to_move);
                   
                           
                       break;//UP
                       
            case 2:    
                   my_snake.put_Head_postion(step_to_move,0);
                    
                    break;//RIGHT
            case 3:    
                       
                   my_snake.put_Head_postion(0,step_to_move);
                        
                     break;//DOWN
                                  
            case 4:   
                     
                  my_snake.put_Head_postion(-step_to_move,0);
                       
                     
                      break;//LEFT
        } 
      
       
    }
    public int[] return_Snake_postionsX()
    {
        return my_snake.get_All_postionsX();
    }
    public int[] return_Snake_postionsY()
    {
        return my_snake.get_All_postionsY();
    }
   
    public int get_Oval_size()
    {
        return my_snake.getOval_Size();
    }
    
    public int get_my_snake_lenght()
    {
        return my_snake.get_lenght();
    }
    public void set_step_length()
    {
        step_to_move=5;
    }
    public int get_Food_X()
    {
        return (int)snakeFood.getX();
    }
    public int get_Food_Y()
    {
        return (int)snakeFood.getY();
    }
    public boolean check_food_place()
    {
       int xfood=(int)snakeFood.getX();
       int yfood=(int)snakeFood.getY();
       if(xfood>260||yfood>260)return true;
       else 
        return my_snake.compare_with_foodPostion(xfood,yfood);
       
    }
    
     public boolean get_Game_over()
    {
        return Game_Over;
    }
     
   private int direction=2;
   private boolean Game_Over;
   private boolean Moving_vertical=false;
   private snake my_snake=new snake();
   private final Food snakeFood=new Food();
   private int step_to_move=20;    
   private int Score;
   
}




Class main frame


package m_snake;
import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JApplet;
import javax.swing.JFrame;
import m_snake.MainPanel.myPanel;


public class MainFrame extends JApplet implements KeyListener{
 
    /** Creates a new instance of MainFrame */
    public void init() {
        setSize(540,540);
        Container cpane=getContentPane();
     
     
     
        cpane.add(snakePanel);
        addKeyListener(this);
     
     
     
     
     
    }
 
    /**
     * @param args the command line arguments
     *
     */
    public static void main(String[] args) {
        // TODO code application logic here
        MainFrame my_Game=new MainFrame();
        JFrame myFrame=new JFrame(" Simple Snake Game ");
        myFrame.setSize(300,300);
        myFrame.getContentPane().add(my_Game);
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.addKeyListener(my_Game);
     
        my_Game.init();
        my_Game.start();
        my_Game.setVisible(true);
        myFrame.setVisible(true);
     
    }
 
    public void keyTyped(KeyEvent e) {
    }
 
    public void keyPressed(KeyEvent e) {
     
        if(e.getKeyCode()==UP) {
            snakePanel.set_Direction(1);
        } else if (e.getKeyCode()==RIGHT) {
            snakePanel.set_Direction(2);
        } else if(e.getKeyCode()==DOWN) {
            snakePanel.set_Direction(3);
        } else if(e.getKeyCode()==LEFT) {
            snakePanel.set_Direction(4);
        }
    }
 
    public void keyReleased(KeyEvent e) {
    }
    private final int LEFT = 37;
    private final int RIGHT = 39;
    private final int UP = 38;
    private final int DOWN = 40;
    private   myPanel snakePanel=new myPanel();
 
}


Class mypanel


package m_snake.MainPanel;

import Snake_engin.engin;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import m_snake.MainPanel.snakeBody.Food;
import m_snake.MainPanel.snakeBody.snake;

/**
 *
 * @author SQLStudent
 */
public class myPanel extends JPanel  {
 
    /** Creates a new instance of myPanel */
    public myPanel() {
     
     
     
        setBorder(my_border);
     
        // mythread.setPriority(1);
        mythread.start();
     
    }
    public   void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D  g2D=(Graphics2D)g;
     
        g2D.setColor(Color.BLUE);
     
 
     
        Parts_X=my_engin.return_Snake_postionsX();
        Parts_Y=my_engin.return_Snake_postionsY();
     
        for(int i=0;i<my_engin.get_my_snake_lenght();i++) {
         
         
         
            g2D.fillRect(Parts_X[i],Parts_Y[i],my_Oval_size,my_Oval_size);
         
        }
        g2D.setColor(Color.RED);
     
        g2D.fillOval(my_engin.get_Food_X()+5,my_engin.get_Food_Y()+5,my_Oval_size-5,my_Oval_size-5);
     
     
    }
 
 
    class MY_Thread extends Thread {
        public   void run() {
            while(true) {
                my_engin.Move_mySnake(direction,false);
                try {
                 
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                repaint();
                if(my_engin.get_Game_over()) {
                    stop();
                }
            }
        }
    }
 
    public void set_Direction(int newDirection) {
        direction=newDirection;
    }
 
 
    private engin my_engin=new engin();
    private int Parts_X[];
    private int Parts_Y[];
    private int direction=2;
 
    private boolean is_my_first_moves=true;
 
    private final MY_Thread mythread=new MY_Thread();
    private final int my_Oval_size=my_engin.get_Oval_size();
 
    private final int LEFT = 37;
    private final int RIGHT = 39;
    private final int UP = 38;
    private final int DOWN = 40;
    private LineBorder my_border=new LineBorder(Color.green.darker(),3);
 
 
}




Note : Shilakan mencoba bila masih kesulitan mebuat game ini bisa komentar di bawah ini siap saya bantu.

Terimakasih telah mengunjungi blog saya ini.
Pengunjung yg baik selalu ninggalin jejak :)

Salam Wani Sinau!

Sabtu, 27 Mei 2017

Contoh Game Sederhana Dengan JAVA ( PUKUL BOLA )

GAME PUKUL BOLA

      Kali ini saya akan memberikan contoh tentang sebuah game java sederhana yang pernah saya buat dan ini merupakan game Ke Dua yang saya buat dengan menggunakan bahasa pemograman Java. Mungkin bagi temen - temen yang ingin mengembangkan game saya ini menjadi lebih baik lagi silakan saja.



Logika game ini adalah :

*klik bola merah dengan cepat dan tepat yang bergerak untuk mendapatkan point

Class Game GUI :


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*

 * GUI.java
 *
 * Created on Oct 9, 2010, 11:03:59 PM
 */
package gamepukulbola;

import java.awt.Cursor;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

public class GUI extends javax.swing.JFrame {


    objek Objek = new objek();

    pemain player;
    level lev=new level();
    animasi anime = new animasi(Objek);
    Cursor kursor;
    int xx = 0, yy = 0;
    //int count;

    /** Creates new form GUI */

    public GUI() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.out.println("error " + e);
        }
        initComponents();
        getContentPane().add(Objek);
        Objek.setBounds(12, 95, 795, 330);
        Objek.setVisible(true);
        areaInfo.setText("Untuk bermain, klik bola merah\nyang bergerak untuk mendapatkan point\n\n");
        txtLevel.setText("1");
    }

    void klikKanvas() {

        Objek.addMouseListener(new MouseListener() {

            public void mouseClicked(MouseEvent evt) {


                Objek.mouseClicked(evt);


                xx = Objek.posX();

                yy = Objek.posY();
                int objekX = Objek.getX();
                int objekY = Objek.getY();

                if ((xx > objekX && xx <= objekX + 50) && (yy > objekY && yy <= objekY + 50)) {


                    player.setScore();


                }


            }


            public void mousePressed(MouseEvent me) {

            }

            public void mouseReleased(MouseEvent me) {

            }

            public void mouseEntered(MouseEvent me) {

            }

            public void mouseExited(MouseEvent me) {

            }
        });
    }

    void countdown() {

        Thread thread = new Thread(new Runnable() {

            int count = Integer.parseInt(labelTime.getText());


            public void run() {

                for (int i = count; i >= 0; i--) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        System.out.println("error count " + e);

                    } finally {

                        labelTime.setText(String.valueOf(i));
                        if (i == 0) {
                            anime.stop();
                            
                            JOptionPane.showMessageDialog(null, "Score Anda = " + String.valueOf(player.getScore()));
                            txtPlayerScore.setText(String.valueOf(player.getScore()));
                        }
                    }
                }
            }
        });
        thread.start();
    }

    void reset(){

        txtPlayerScore.setText("");
        labelTime.setText("30");
    }

    /** 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() {

        jPanel1 = new javax.swing.JPanel();

        jLabel4 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtPlayerName = new javax.swing.JTextField();
        txtPlayerScore = new javax.swing.JTextField();
        txtLevel = new javax.swing.JTextField();
        buttonStart = new javax.swing.JButton();
        buttonLevel = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        areaInfo = new javax.swing.JTextArea();
        jPanel4 = new javax.swing.JPanel();
        labelTime = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        setTitle("Game Pukul Bola v1.0");
        setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(251, 246, 246));

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel4.setFont(new java.awt.Font("augie", 0, 18)); // NOI18N

        jLabel4.setForeground(new java.awt.Color(19, 19, 19));
        jLabel4.setText("PUKUL BOLA MERAH SEBISAMU");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);

        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(306, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addGap(222, 222, 222))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Pemain"));


        jLabel1.setText("Nama");


        jLabel2.setText("Score");


        jLabel3.setText("Level");


        txtPlayerScore.setEditable(false);


        txtLevel.setEditable(false);


        buttonStart.setText("Start");

        buttonStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonStartActionPerformed(evt);
            }
        });

        buttonLevel.setText("Next Level");

        buttonLevel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLevelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);

        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(buttonLevel, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonStart, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(txtPlayerScore, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE)
                    .addComponent(txtPlayerName, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE)
                    .addComponent(txtLevel, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtPlayerName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtPlayerScore, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonStart)
                    .addComponent(buttonLevel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Info"));


        areaInfo.setColumns(20);

        areaInfo.setRows(5);
        jScrollPane1.setViewportView(areaInfo);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);

        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jScrollPane1)
                .addContainerGap())
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Waktu"));


        labelTime.setFont(new java.awt.Font("Liberation Sans", 0, 36)); // NOI18N

        labelTime.setText("30");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);

        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(labelTime)
                .addGap(67, 67, 67))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addComponent(labelTime)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton3.setText("Keluar");

        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(351, 351, 351)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)))
                .addContainerGap())
        );

        pack();

    }// </editor-fold>                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        System.exit(1);
    }                                        

    private void buttonStartActionPerformed(java.awt.event.ActionEvent evt) {                                            

        String name = txtPlayerName.getText();
        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Isi dulu nama Anda!");
        } else {
            player = new pemain(name);
            areaInfo.append("Nama anda: " + player.getName());
            klikKanvas();
            countdown();
            anime.start();
        }


    }                                           


    private void buttonLevelActionPerformed(java.awt.event.ActionEvent evt) {                                            


        int skornya=Integer.parseInt(txtPlayerScore.getText());

       int levelnya=Integer.parseInt(txtLevel.getText());
       if(skornya>=15 && levelnya == 1){
            //txtPlayerScore.setText("");
            reset();
            lev.setLevelBaru();
            txtLevel.setText("2");
            if(skornya < 15 && levelnya == 1){
                JOptionPane.showMessageDialog(this, "Minimal score Anda harus 15 jika ingin ke level 2");
            }
       }
       else if (skornya >=5 && levelnya == 2){
            reset();
            txtPlayerScore.setText("");
            lev.setLevelBaru();
            txtLevel.setText("3");
            if(skornya < 5 && levelnya == 2){
                JOptionPane.showMessageDialog(this, "Minimal score Anda harus 5 jika ingin ke level 3");
            }
       }
       else if(skornya >= 3 && levelnya == 3){
            reset();
            txtPlayerScore.setText("");
            JOptionPane.showMessageDialog(this, "Selamat, anda telah menempuh semua level game ini");
            if(skornya < 3 && levelnya == 3){
                JOptionPane.showMessageDialog(this, "Sulit ya?");
            }
       }
    }                                           
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new GUI().setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify                     
    private javax.swing.JTextArea areaInfo;
    private javax.swing.JButton buttonLevel;
    private javax.swing.JButton buttonStart;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelTime;
    private javax.swing.JTextField txtLevel;
    private javax.swing.JTextField txtPlayerName;
    private javax.swing.JTextField txtPlayerScore;
    // End of variables declaration                   
}

            for (int i = 0; i < musuhs.size(); i++) {
                Rectangle musuhHitbox = musuhs.get(i).getHitbox();
                Rectangle playerHitbox = getPlayerHitbox();
                if (musuhHitbox.intersects(playerHitbox))
                    Pemain = false ;               
            }                              
            try {
                Thread.sleep(5);
            } catch (InterruptedException ex) {
                System.err.println("Error: Thread Interrupted.");
            }
        }
    }    
    private void move() {
        x += xArah;
        y += yArah;
        if (x < 0)
            x = 0;
        if (y < 20)
            y = 20;
        if (x > 580)
            x = 580;
        if (y > 440)
            y = 440;
    }    
    Game() {        
        setPreferredSize(size);
        setSize(640, 480);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBackground(Color.WHITE);
        setVisible(true);
        setTitle("Iron Cockroach");
        x = 320;
        y = 240;
        xArah = 0;
        yArah = 0;
        addKeyListener(new KeyListener());        
        musuhs = new ArrayList<musuh>();
        makanann = new ArrayList<Makanan>();
        Pemain = true;
        size = new Dimension();
        background = new ImageIcon(this.getClass().getResource("papan.jpg")).getImage();
        size.width = background.getWidth(null);
        size.height = background.getHeight(null);
        setPreferredSize(size);
        soundTrack = Applet.newAudioClip(getClass().getResource("lick-01.wav"));
        soundTrack.loop();
    }    
    public void paint(Graphics g) {         
        Image dbImg = createImage(getWidth(), getHeight());
        Graphics dbg = dbImg.getGraphics();
        draw(dbg);
        g.drawImage(dbImg, 0, 0, this);           
    }    
    public void draw(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(background, 0, 0, null);        
        if (Pemain) {
            Image serangga = new ImageIcon(this.getClass().getResource("bugg.png")).getImage();
            g.drawImage(serangga, x, y, this);  
        }   
        for (int i = 0; i < musuhs.size(); i++) {
            musuh e = musuhs.get(i);
            e.draw(g);
        }
        for (int i = 0; i < makanann.size(); i++) {
            Makanan e = makanann.get(i);
            e.draw(g);             
        }
        repaint();
        g2d.setFont(new Font("Arial",Font.BOLD,18));
        g2d.setColor(Color.WHITE);
        g2d.drawString("SCORE : " + Integer.toString(skor),20,50);
        g2d.setFont(new Font("Arial",Font.PLAIN,10));
        g2d.setColor(Color.GRAY);
    }    
    public static Image loadImage(String fileName) {
        ImageIcon icon = new ImageIcon(fileName);
        return icon.getImage();
    }   
    private void Lawanmusuh() {
        musuh e = new musuh();
        musuhs.add(e);
        Thread t = new Thread(e);
        t.start();
    }
    private void munculMakanan() {
        Makanan e = new Makanan();
        makanann.add(e);
       Thread t = new Thread(e);
        t.start();        
    }        
    private Rectangle getPlayerHitbox() {
        return new Rectangle(x, y, 69, 42);
    }
    public static void main(String[] args) {
        Game gh = new Game();
        Thread t = new Thread(gh);
        t.start();
        while (true) {
            if (gh.musuhs.size() < 15) {
                gh.Lawanmusuh();
            }
            if (gh.makanann.size() < 15) {
                gh.munculMakanan();
            }            
            try {
                Thread.sleep(2500);
            } catch (InterruptedException ex) {
                System.err.println("Error: Thread Interrupted.");
            }
        }
    }   
    private class KeyListener extends KeyAdapter {
        public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) {
                case KeyEvent.VK_UP:
                    yArah = -2;
                    break;
                case KeyEvent.VK_DOWN:
                    yArah = 2;
                    break;
                case KeyEvent.VK_LEFT:
                    xArah = -2;
                    break;
                case KeyEvent.VK_RIGHT:
                    xArah = 2;
                    break;
                default:
                    break;
            }
        }     
        public void keyReleased(KeyEvent e) {
            switch (e.getKeyCode()) {
                case KeyEvent.VK_UP:
                case KeyEvent.VK_DOWN:
                    yArah = 0;
                    break;
                case KeyEvent.VK_LEFT:
                case KeyEvent.VK_RIGHT:
                    xArah = 0;
                    break;
                default:
                    break;
            }
        }  
    }  
}

1.DESIGN TAMPILAN




Class Main

package gamepukulbola;


public class Main {


    /**

     * @param args the command line arguments
     */
    public static void main(String[] args) {
        GUI gui = new GUI();
        gui.setVisible(true);
    }



Class Animasi

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gamepukulbola;

import java.util.Random;



public class animasi extends Thread {


    objek picture;

    Random acak;
    level lev=new level();
    //int speed = 1000;
    int x, y, dx, dy;

    public animasi(objek objeknya) {

        this.picture = objeknya;
    }

    @Override

    public void run() {

        while (true) {

            x = (int) (Math.random() * 750);
            y = (int) (Math.random() * 300);

            picture.setLocation(x, y, dx, dy);

            picture.setLocation(x, y);
            System.out.println("x=" + x + " y=" + y);
            picture.repaint();

            try {

                sleep(lev.getSpeed());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }

}




Class Level

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gamepukulbola;


public class level {
    int speed=1000;

    public void setLevelBaru(){
        speed-=250;
    }
    public int getSpeed(){
        return speed;
    }
}






Class Objek

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gamepukulbola;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;

public class objek extends Canvas{
    int x, y, l, t, dx, dy,posX,posY;
    boolean move = true;
    Canvas kanvas;

    public objek() {

        l = 30;
        t = 30;

        setBackground(Color.GRAY);
//        setBackground();
    }

    public void setLocation(int x, int y, int dx, int dy) {
        this.x = x;
        this.y = y;
        this.dx = dx;
        this.dy = dy;
    }
    @Override
    public void setLocation(int x, int y) {
        this.x = x;
        this.y = y;
//        this.dx = dx;
//        this.dy = dy;
    }

    @Override
    public int getX() {
        return x;
    }

    @Override
    public int getY() {
        return y;
    }

    public int getDX() {
        return dx;
    }

    public int getDY() {
        return dy;
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.RED);
        g2.fillOval(getX(), getY(), l, t);
    }

    public void mouseClicked(MouseEvent e){
        posX=e.getX();
        posY=e.getY();

    }

    public int posX(){
        return posX;
    }

    public int posY(){
        return posY;
    }

}



Class Pemain


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gamepukulbola;


public class pemain {

    String name;
    int score = 0;
    int total = 0;

    public pemain(String name) {
        this.name = name;
    }

    String getName() {
        return name;
    }

    void setScore() {
        score++;
    }

    int getScore() {
        return score;
    }

    void setTotalScore(int total) {
        this.total += total;
    }

    int getTotalScore() {
        return total;
    }
}



Terimakasih telah mengunjungi blog saya ini.
Pengunjung yg baik selalu ninggalin jejak :)

Salam Wani Sinau!