Membuat Game Flappy Bird Sederhana dengan Java Eclipse

Membuat Game Flappy Bird Sederhana dengan Java Eclipse

Membuat Game Flappy Bird Sederhana dengan Java Eclipse
Membuat Game Flappy Bird Sederhana dengan Java Eclipse


Hallo bro ruangcoder, artikel kali ini tentang membuat game dengan java eclipse dimana juga artikel sebelumnya admin sudah memberikan tutorial cara membuat game snake atau ular di java netbeans bisa lihat disini. Dalam pembahasan yang ditulis sekarang, admin ingin menunjukkan cara membuat game 2D dasar di Java Eclipse dengan nama game tersebut Flappy Bird. admin juga sudah menyediakan beberapa resource untuk membuat game nya , seperti image dll, nah untuk image flappy bird nya itu sendiri, kalian bisa ubah atau re design sesuka kalian, jika kalian bosan dengan tampilannya. Waktu yang kalian perlukan untuk menyelesaikan tutorial yang admin berikan ini hampir sepenuhnya bergantung pada tingkat keterampilan Java kalian sendiri. Tujuan admin adalah 1-2 jam untuk sobat capai pada tingkat keterampilan menengah. Jika Sobat seorang pemula, Tentu sobat jangan khawatir! Admin memberikan semua kode yang dibutuhkan bersama penjelasan konseptual untuk memandu kalian melalui proses ini yaitu dalam membuat game sederhana dengan java eclipse. dan perlu sobat ingat juga agar sobat lebih giat dalam belajar nya , yaitu tidak untuk di copas dulu codingan yang admin berikan , melainkan pure sobat ketik manual , sampai sobat menemukan error dan di solved sendiri , jika sobat masih mengalami kesusahan , silahkan sandingkan codingan yang sobat ketikkan dengan yang admin berikan di artikel ini, jika memang sudah serasa benar , tapi tetap mengalami error , baru sobat copas codingan yang admin berikan , tujuan ini memandirikan sobat dalam melatih kefokusan dalam mengetik agar tidak terjadi error dan agar melatih sobat bisa mengetik dengan secara cepat dalam membuat program.


Admin berharap untuk sobat sendiri menunjukkan betapa mudahnya membuat permainan sederhana ketika kalian sendiri memiliki waklu luang untuk belajar. Admin masuk ke setiap proyek pemrograman dengan keinginan untuk mempelajari sesuatu yang baru dan proyek ini untuk mengajari kalian beberapa trik. Admin harap sobat melakukan hal yang sama untuk diri sobat sendiri agar bisa berkembang. karena jujur saja admin lebih senang di Android dan Website , akan tetapi untuk memberikan pengalaman dasar yang pernah admin pelajari, apa salahnya bukan.

Dengan itu, mari mendalami proses belajar, mulai dengan demo permainan yang akan Kalian buat!  kali ini . langsung saja kita mulai tutorialnya yaitu membuat game menggunakan java eclipse cara membuat game di java 


Membuat Game Flappy Bird Sederhana dengan Java Eclipse:



Langkah pertama adalah tentunya sobat membuka eclipse sobat , disini admin anggep sobat sudah membuka eclipse sobat ya, langkah selanjutnya sobat silahkan download ketiga resource gambar dibawah ini , dimana yang natninya gambar ini akan dijadikan sebagai design dari game nya.




 Nah setelah sobat selesai mengunduk ketiga gambar tersebut, langkah selanjutnya adalah sobat buat project baru dengan cara File -> New -> Java Project, kemudian sobat beri nama game tersebut dengan nama Flappy Bird kemudian pada Create Module-info.java, silahkan sobat hilangkan centang nya :



 Nah pada langkah selanjutnya pada src silahkan sobat buat package baru dengan cara klik kanan -> New -> Package , kemudian silahkan berinama package tersebut dengan nama GameFlappy sobat bisa lihat gambar dibawah ini.




Selanjutnya pada package yang baru saja kita buat , kita akan membuat class pertama yang dimana class pertama ini akan kita beri nama TopClass , dengan cara sobat klik kanan pada package GameFlappy -> New -> Class dan sobat beri nama class tersebut dengan nama TopClass sobat bisa lihat gambar yang admin sertakan dibawah ini.





Nah setelah membuat class nya , silahkan sobat ketikkan codingan dibawah ini , ingat ya sobat yang seperti admin jelaskan di atas , silahkan sobat ketikkan terlebih dahulu agar melatih tingkat kefokusan sobat dan pengetikkan sobat, apabila error coba sobat pecahkan masalah itu sendiri , jika tidak berhasil silahkan bandingan codingan sobat dengan codingan admin , jika belum juga bisa , silahkan sobat copy paste codingan admin , kemudian dilihat lagi.



package GameFlappy;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Color;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;

import javax.swing.*;

public class TopClass implements ActionListener, KeyListener {
    //global constant variables
    private static final int SCREEN_WIDTH = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
    private static final int SCREEN_HEIGHT = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
    private static final int PIPE_GAP = SCREEN_HEIGHT/5; //distance in pixels between pipes
    private static final int PIPE_WIDTH = SCREEN_WIDTH/8, PIPE_HEIGHT = 4*PIPE_WIDTH;
    private static final int BIRD_WIDTH = 120, BIRD_HEIGHT = 75;
    private static final int UPDATE_DIFFERENCE = 25; //time in ms between updates
    private static final int X_MOVEMENT_DIFFERENCE = 5; //distance the pipes move every update
    private static final int SCREEN_DELAY = 300; //needed because of long load times forcing pipes to pop up mid-screen
    private static final int BIRD_X_LOCATION = SCREEN_WIDTH/7;
    private static final int BIRD_JUMP_DIFF = 10, BIRD_FALL_DIFF = BIRD_JUMP_DIFF/2, BIRD_JUMP_HEIGHT = PIPE_GAP - BIRD_HEIGHT - BIRD_JUMP_DIFF*2;
    
    //global variables
    private boolean loopVar = true; //false -> don't run loop; true -> run loop for pipes
    private boolean gamePlay = false; //false -> game not being played
    private boolean birdThrust = false; //false -> key has not been pressed to move the bird vertically
    private boolean birdFired = false; //true -> button pressed before jump completes
    private boolean released = true; //space bar released; starts as true so first press registers
    private int birdYTracker = SCREEN_HEIGHT/2 - BIRD_HEIGHT;
    private Object buildComplete = new Object();
    
    //global swing objects
    private JFrame f = new JFrame("Flappy Bird Redux");
    private JButton startGame;
    private JPanel topPanel; //declared globally to accommodate the repaint operation and allow for removeAll(), etc.
    
    //other global objects
    private static TopClass tc = new TopClass();
    private static PlayGameScreen pgs; //panel that has the moving background at the start of the game
    
    /**
     * Default constructor
     */
    public TopClass() {
        
    }
    
    /**
     * Main executable method invoked when running .jar file
     * @param args
     */
    public static void main(String[] args) {
        //build the GUI on a new thread
        
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                tc.buildFrame();
                
                //create a new thread to keep the GUI responsive while the game runs
                Thread t = new Thread() {
                    public void run() {
                        tc.gameScreen(true);
                    }
                };
                t.start();
            }
        });
    }
    
    /**
     * Method to construct the JFrame and add the program content
     */
    private void buildFrame() {
        Image icon = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/blue_bird.png"));
        
        f.setContentPane(createContentPane());
        f.setResizable(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setAlwaysOnTop(false);
        f.setVisible(true);
        f.setMinimumSize(new Dimension(SCREEN_WIDTH*1/4, SCREEN_HEIGHT*1/4));
        f.setExtendedState(JFrame.MAXIMIZED_BOTH);
        f.setIconImage(icon);
        f.addKeyListener(this);
    }
    
    private JPanel createContentPane() {
        topPanel = new JPanel(); //top-most JPanel in layout hierarchy
        topPanel.setBackground(Color.BLACK);
        //allow us to layer the panels
        LayoutManager overlay = new OverlayLayout(topPanel);
        topPanel.setLayout(overlay);
        
        //Start Game JButton
        startGame = new JButton("Start Playing!");
        startGame.setBackground(Color.BLUE);
        startGame.setForeground(Color.WHITE);
        startGame.setFocusable(false); //rather than just setFocusabled(false)
        startGame.setFont(new Font("Calibri", Font.BOLD, 42));
        startGame.setAlignmentX(0.5f); //center horizontally on-screen
        startGame.setAlignmentY(0.5f); //center vertically on-screen
        startGame.addActionListener(this);
        topPanel.add(startGame);
        
        //must add last to ensure button's visibility
        pgs = new PlayGameScreen(SCREEN_WIDTH, SCREEN_HEIGHT, true); //true --> we want pgs to be the splash screen
        topPanel.add(pgs);
        
        return topPanel;
    }
    
    /**
     * Implementation for action events
     */
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == startGame) {
            //stop the splash screen
            loopVar = false;
            
            fadeOperation();
        }
        else if(e.getSource() == buildComplete) {
            Thread t = new Thread() {
                public void run() {
                    loopVar = true;
                    gamePlay = true;
                    tc.gameScreen(false);
                }
            };
            t.start();
        }
    }
    
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_SPACE && gamePlay == true && released == true){
            //update a boolean that's tested in game loop to move the bird
            if(birdThrust) { //need this to register the button press and reset the birdYTracker before the jump operation completes
                birdFired = true;
            }
            birdThrust = true;
            released = false;
        }
        else if(e.getKeyCode() == KeyEvent.VK_B && gamePlay == false) {
            birdYTracker = SCREEN_HEIGHT/2 - BIRD_HEIGHT; //need to reset the bird's starting height
            birdThrust = false; //if user presses SPACE before collision and a collision occurs before reaching max height, you get residual jump, so this is preventative
            actionPerformed(new ActionEvent(startGame, -1, ""));
        }
        if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
            System.exit(0);
        }
    }
    
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_SPACE) {
            released = true;
        }
    }
    
    public void keyTyped(KeyEvent e) {
        
    }
    
    /**
     * Perform the fade operation that take place before the start of rounds
     */
    private void fadeOperation() {
        Thread t = new Thread() {
            public void run() {
                topPanel.remove(startGame);
                topPanel.remove(pgs);
                topPanel.revalidate();
                topPanel.repaint();
                
                //panel to fade
                JPanel temp = new JPanel();
                int alpha = 0; //alpha channel variable
                temp.setBackground(new Color(0, 0, 0, alpha)); //transparent, black JPanel
                topPanel.add(temp);
                topPanel.add(pgs);
                topPanel.revalidate();
                topPanel.repaint();
                
                long currentTime = System.currentTimeMillis();
                
                while(temp.getBackground().getAlpha() != 255) {
                    if((System.currentTimeMillis() - currentTime) > UPDATE_DIFFERENCE/2) {
                        if(alpha < 255 - 10) {
                            alpha += 10;
                        }
                        else {
                            alpha = 255;
                        }
                        
                        temp.setBackground(new Color(0, 0, 0, alpha));
                    
                        topPanel.revalidate();
                        topPanel.repaint();
                        currentTime = System.currentTimeMillis();
                    }
                }
                
                topPanel.removeAll();
                topPanel.add(temp);
                pgs = new PlayGameScreen(SCREEN_WIDTH, SCREEN_HEIGHT, false);
                pgs.sendText(""); //remove title text
                topPanel.add(pgs);
                
                while(temp.getBackground().getAlpha() != 0) {
                    if((System.currentTimeMillis() - currentTime) > UPDATE_DIFFERENCE/2) {
                        if(alpha > 10) {
                            alpha -= 10;
                        }
                        else {
                            alpha = 0;
                        }
                        
                        temp.setBackground(new Color(0, 0, 0, alpha));
                    
                        topPanel.revalidate();
                        topPanel.repaint();
                        currentTime = System.currentTimeMillis();
                    }
                }
                
                actionPerformed(new ActionEvent(buildComplete, -1, "Build Finished"));
            }
        };
        
        t.start();
    }
    
    /**
     * Method that performs the splash screen graphics movements
     */
    private void gameScreen(boolean isSplash) {
        BottomPipe bp1 = new BottomPipe(PIPE_WIDTH, PIPE_HEIGHT);
        BottomPipe bp2 = new BottomPipe(PIPE_WIDTH, PIPE_HEIGHT);
        TopPipe tp1 = new TopPipe(PIPE_WIDTH, PIPE_HEIGHT);
        TopPipe tp2 = new TopPipe(PIPE_WIDTH, PIPE_HEIGHT);
        Bird bird = new Bird(BIRD_WIDTH, BIRD_HEIGHT);
        
        //variables to track x and y image locations for the bottom pipe
        int xLoc1 = SCREEN_WIDTH+SCREEN_DELAY, xLoc2 = (int) ((double) 3.0/2.0*SCREEN_WIDTH+PIPE_WIDTH/2.0)+SCREEN_DELAY;
        int yLoc1 = bottomPipeLoc(), yLoc2 = bottomPipeLoc();
        int birdX = BIRD_X_LOCATION, birdY = birdYTracker;
        
        //variable to hold the loop start time
        long startTime = System.currentTimeMillis();
        
        while(loopVar) {
            if((System.currentTimeMillis() - startTime) > UPDATE_DIFFERENCE) {
                //check if a set of pipes has left the screen
                //if so, reset the pipe's X location and assign a new Y location
                if(xLoc1 < (0-PIPE_WIDTH)) {
                    xLoc1 = SCREEN_WIDTH;
                    yLoc1 = bottomPipeLoc();
                }
                else if(xLoc2 < (0-PIPE_WIDTH)) {
                    xLoc2 = SCREEN_WIDTH;
                    yLoc2 = bottomPipeLoc();
                }
                
                //decrement the pipe locations by the predetermined amount
                xLoc1 -= X_MOVEMENT_DIFFERENCE;
                xLoc2 -= X_MOVEMENT_DIFFERENCE;
                
                if(birdFired && !isSplash) {
                    birdYTracker = birdY;
                    birdFired = false;
                }
                
                if(birdThrust && !isSplash) {
                    //move bird vertically
                    if(birdYTracker - birdY - BIRD_JUMP_DIFF < BIRD_JUMP_HEIGHT) {
                        if(birdY - BIRD_JUMP_DIFF > 0) {
                            birdY -= BIRD_JUMP_DIFF; //coordinates different
                        }
                        else {
                            birdY = 0;
                            birdYTracker = birdY;
                            birdThrust = false;
                        }
                    }
                    else {
                        birdYTracker = birdY;
                        birdThrust = false;
                    }
                }
                else if(!isSplash) {
                    birdY += BIRD_FALL_DIFF;
                    birdYTracker = birdY;
                }
                
                //update the BottomPipe and TopPipe locations
                bp1.setX(xLoc1);
                bp1.setY(yLoc1);
                bp2.setX(xLoc2);
                bp2.setY(yLoc2);
                tp1.setX(xLoc1);
                tp1.setY(yLoc1-PIPE_GAP-PIPE_HEIGHT); //ensure tp1 placed in proper location
                tp2.setX(xLoc2);
                tp2.setY(yLoc2-PIPE_GAP-PIPE_HEIGHT); //ensure tp2 placed in proper location
                
                if(!isSplash) {
                    bird.setX(birdX);
                    bird.setY(birdY);
                    pgs.setBird(bird);
                }
                
                //set the BottomPipe and TopPipe local variables in PlayGameScreen by parsing the local variables
                pgs.setBottomPipe(bp1, bp2);
                pgs.setTopPipe(tp1, tp2);
                
                if(!isSplash && bird.getWidth() != -1) { //need the second part because if bird not on-screen, cannot get image width and have cascading error in collision
                    collisionDetection(bp1, bp2, tp1, tp2, bird);
                    updateScore(bp1, bp2, bird);
                }
                
                //update pgs's JPanel
                topPanel.revalidate();
                topPanel.repaint();
                
                //update the time-tracking variable after all operations completed
                startTime = System.currentTimeMillis();
            }
        }
    }
    
    /**
     * Calculates a random int for the bottom pipe's placement
     * @return int
     */
    private int bottomPipeLoc() {
        int temp = 0;
        //iterate until temp is a value that allows both pipes to be onscreen
        while(temp <= PIPE_GAP+50 || temp >= SCREEN_HEIGHT-PIPE_GAP) {
            temp = (int) ((double) Math.random()*((double)SCREEN_HEIGHT));
        }
        return temp;
    }
    
    /**
     * Method that checks whether the score needs to be updated
     * @param bp1 First BottomPipe object
     * @param bp2 Second BottomPipe object
     * @param bird Bird object
     */
    private void updateScore(BottomPipe bp1, BottomPipe bp2, Bird bird) {
        if(bp1.getX() + PIPE_WIDTH < bird.getX() && bp1.getX() + PIPE_WIDTH > bird.getX() - X_MOVEMENT_DIFFERENCE) {
            pgs.incrementJump();
        }
        else if(bp2.getX() + PIPE_WIDTH < bird.getX() && bp2.getX() + PIPE_WIDTH > bird.getX() - X_MOVEMENT_DIFFERENCE) {
            pgs.incrementJump();
        }
    }
    
    /**
     * Method to test whether a collision has occurred
     * @param bp1 First BottomPipe object
     * @param bp2 Second BottomPipe object
     * @param tp1 First TopPipe object
     * @param tp2 Second TopPipe object
     * @param bird Bird object
     */
    private void collisionDetection(BottomPipe bp1, BottomPipe bp2, TopPipe tp1, TopPipe tp2, Bird bird) {
        collisionHelper(bird.getRectangle(), bp1.getRectangle(), bird.getBI(), bp1.getBI());
        collisionHelper(bird.getRectangle(), bp2.getRectangle(), bird.getBI(), bp2.getBI());
        collisionHelper(bird.getRectangle(), tp1.getRectangle(), bird.getBI(), tp1.getBI());
        collisionHelper(bird.getRectangle(), tp2.getRectangle(), bird.getBI(), tp2.getBI());
        
        if(bird.getY() + BIRD_HEIGHT > SCREEN_HEIGHT*7/8) { //ground detection
            pgs.sendText("Game Over");
            loopVar = false;
            gamePlay = false; //game has ended
        }
    }
    
    /**
     * Helper method to test the Bird object's potential collision with a pipe object.
     * @param r1 The Bird's rectangle component
     * @param r2 Collision component rectangle
     * @param b1 The Bird's BufferedImage component
     * @param b2 Collision component BufferedImage
     */
    private void collisionHelper(Rectangle r1, Rectangle r2, BufferedImage b1, BufferedImage b2) {
        if(r1.intersects(r2)) {
            Rectangle r = r1.intersection(r2);
            
            int firstI = (int) (r.getMinX() - r1.getMinX()); //firstI is the first x-pixel to iterate from
            int firstJ = (int) (r.getMinY() - r1.getMinY()); //firstJ is the first y-pixel to iterate from
            int bp1XHelper = (int) (r1.getMinX() - r2.getMinX()); //helper variables to use when referring to collision object
            int bp1YHelper = (int) (r1.getMinY() - r2.getMinY());
            
            for(int i = firstI; i < r.getWidth() + firstI; i++) { //
                for(int j = firstJ; j < r.getHeight() + firstJ; j++) {
                    if((b1.getRGB(i, j) & 0xFF000000) != 0x00 && (b2.getRGB(i + bp1XHelper, j + bp1YHelper) & 0xFF000000) != 0x00) {
                        pgs.sendText("Game Over");
                        loopVar = false; //stop the game loop
                        gamePlay = false; //game has ended
                        break;
                    }
                }
            }
        }
    }
}

Oke kita lanjut ke codingan berikutnya kita akan membuat class lagi caranya nama seperti dalam membuat TopClass yang dimana class yang sebelumnya kita buat , disini kita akan memberi nama class ini dengan nama PlayGameScreen sobat bisa lihat gambar dibawah ini.



Setelah itu silahkan sobat ketikan codingan dibawah ini , pada class PlayGameScreen yang baru saja kita buat.



package GameFlappy;
import javax.swing.*;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Color;

public class PlayGameScreen extends JPanel {
    //default reference ID
    private static final long serialVersionUID = 1L;
    
    //global variables
    private int screenWidth, screenHeight;
    private boolean isSplash = true;
    private int successfulJumps = 0;
    private String message = "Flappy Bird";
    private Font primaryFont = new Font("Goudy Stout", Font.BOLD, 56), failFont = new Font("Calibri", Font.BOLD, 56);
    private int messageWidth = 0, scoreWidth = 0;
    private BottomPipe bp1, bp2;
    private TopPipe tp1, tp2;
    private Bird bird;

    /**
     * Default constructor for the PlayGameScreen class
     */
    public PlayGameScreen(int screenWidth, int screenHeight, boolean isSplash) {
        this.screenWidth = screenWidth;
        this.screenHeight = screenHeight;
        this.isSplash = isSplash;
    }
    
    /**
     * Manually control what's drawn on this JPanel by calling the paintComponent method
     * with a graphics object and painting using that object
     */
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        g.setColor(new Color(89, 81, 247)); //color for the blue sky
        g.fillRect(0, 0, screenWidth, screenHeight*7/8); //create the sky rectangle
        g.setColor(new Color(147, 136, 9)); //brown color for ground
        g.fillRect(0, screenHeight*7/8, screenWidth, screenHeight/8); //create the ground rectangle
        g.setColor(Color.BLACK); //dividing line color
        g.drawLine(0, screenHeight*7/8, screenWidth, screenHeight*7/8); //draw the dividing line
        
        //objects must be instantiated before they're drawn!
        if(bp1 != null && bp2 != null && tp1 != null && tp2 != null) {
            g.drawImage(bp1.getPipe(), bp1.getX(), bp1.getY(), null);
            g.drawImage(bp2.getPipe(), bp2.getX(), bp2.getY(), null);
            g.drawImage(tp1.getPipe(), tp1.getX(), tp1.getY(), null);
            g.drawImage(tp2.getPipe(), tp2.getX(), tp2.getY(), null);
        }
        
        if(!isSplash && bird != null) {
            g.drawImage(bird.getBird(), bird.getX(), bird.getY(), null);
        }
        
        //needed in case the primary font does not exist
        try {
            g.setFont(primaryFont);
            FontMetrics metric = g.getFontMetrics(primaryFont);
            messageWidth = metric.stringWidth(message);
            scoreWidth = metric.stringWidth(String.format("%d", successfulJumps));
        }
        catch(Exception e) {
            g.setFont(failFont);
            FontMetrics metric = g.getFontMetrics(failFont);
            messageWidth = metric.stringWidth(message);
            scoreWidth = metric.stringWidth(String.format("%d", successfulJumps));
        }
        
        g.drawString(message, screenWidth/2-messageWidth/2, screenHeight/4);
        
        if(!isSplash) {
            g.drawString(String.format("%d", successfulJumps), screenWidth/2-scoreWidth/2, 50);
        }
    }
    
    /**
     * Parsing method for PlayGameScreen's global BottomPipe variables
     * @param bp1 The first BottomPipe
     * @param bp2 The second BottomPipe
     */
    public void setBottomPipe(BottomPipe bp1, BottomPipe bp2) {
        this.bp1 = bp1;
        this.bp2 = bp2;
    }
    
    /**
     * Parsing method for PlayGameScreen's global TopPipe variables
     * @param tp1 The first TopPipe
     * @param tp2 The second TopPipe
     */
    public void setTopPipe(TopPipe tp1, TopPipe tp2) {
        this.tp1 = tp1;
        this.tp2 = tp2;
    }
    
    /**
     * Parsing method for PlayGameScreen's global Bird variable
     * @param bird The Bird object
     */
    public void setBird(Bird bird) {
        this.bird = bird;
    }
    
    /**
     * Method called to invoke an increase in the variable tracking the current
     * jump score
     */
    public void incrementJump() {
        successfulJumps++;
    }
    
    /**
     * Method called to return the current jump score
     * @return
     */
    public int getScore() {
        return successfulJumps;
    }
    
    /**
     * Method called to parse a message onto the screen
     * @param message The message to parse
     */
    public void sendText(String message) {
        this.message = message;
    }
}

Langkah selanjutnya kita akan membuat class lagi , langkahnya sama , kek nya admin gak perlu jelasin cara buat nya deh haha , oke buat class baru lagi dengan nama class tersebut yaitu TopPipe , kemudian sobat ketikkan codingan dibawah ini :



package GameFlappy;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.image.BufferedImage;


public class TopPipe {
    //global variables
    private Image topPipe;
    private int xLoc = 0, yLoc = 0;

    /**
     * Default constructor
     */
    public TopPipe(int initialWidth, int initialHeight) {
        topPipe = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/tube_top.png"));
        scaleTopPipe(initialWidth, initialHeight);
    }

    /**
     * Method to scale the topPipe sprite into the desired dimensions
     * @param width The desired width of the topPipe
     * @param height The desired height of the topPipe
     */
    public void scaleTopPipe(int width, int height) {
        topPipe = topPipe.getScaledInstance(width, height, Image.SCALE_SMOOTH);        
    }

    /**
     * Getter method for the TopPipe object.
     * @return Image
     */
    public Image getPipe() {
        return topPipe;
    }

    /**
     * Method to obtain the width of the TopPipe object
     * @return int
     */
    public int getWidth() {
        return topPipe.getWidth(null);
    }

    /**
     * Method to obtain the height of the TopPipe object
     * @return int
     */
    public int getHeight() {
        return topPipe.getHeight(null);
    }

    /**
     * Method to set the x location of the TopPipe object
     * @param x
     */
    public void setX(int x) {
        xLoc = x;
    }

    /**
     * Method to get the x location of the TopPipe object
     * @return int
     */
    public int getX() {
        return xLoc;
    }

    /**
     * Method to set the y location of the TopPipe object
     * @param y
     */
    public void setY(int y) {
        yLoc = y;
    }

    /**
     * Method to get the y location of the TopPipe object
     * @return int
     */
    public int getY() {
        return yLoc;
    }

    /**
     * Method used to acquire a Rectangle that outlines the TopPipe's image
     * @return Rectangle outlining the TopPipe's position on screen
     */
    public Rectangle getRectangle() {
        return (new Rectangle(xLoc, yLoc, topPipe.getWidth(null), topPipe.getHeight(null)));
    }
    
    /**
     * Method to acquire a BufferedImage that represents the TopPipe's image object
     * @return TopPipe's BufferedImage object
     */
    public BufferedImage getBI() {
        BufferedImage bi = new BufferedImage(topPipe.getWidth(null), topPipe.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics g = bi.getGraphics();
        g.drawImage(topPipe, 0, 0, null);
        g.dispose();
        return bi;
    }
}

Langkah selanjutnya membuat class lagi dengan nama class nya ini yaitu BottomPipe , silahkan sobat buat caranya sama ya , kebangetan dah sampe tahap ini gak paham buatnya mah hahaha, oke lanjut sobat ketikkan codingan dibawah ini.




package GameFlappy;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.image.BufferedImage;

public class BottomPipe {
    //global variables
    private Image bottomPipe;
    private int xLoc = 0, yLoc = 0;
    
    /**
     * Default constructor
     */
    public BottomPipe(int initialWidth, int initialHeight) {
        bottomPipe = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/tube_bottom.png"));
        scaleBottomPipe(initialWidth, initialHeight);
    }
    
    /**
     * Method to scale the BottomPipe sprite into the desired dimensions
     * @param width The desired width of the BottomPipe
     * @param height The desired height of the BottomPipe
     */
    public void scaleBottomPipe(int width, int height) {
        bottomPipe = bottomPipe.getScaledInstance(width, height, Image.SCALE_SMOOTH);        
    }
    
    /**
     * Getter method for the BottomPipe object.
     * @return Image
     */
    public Image getPipe() {
        return bottomPipe;
    }
    
    /**
     * Method to obtain the width of the BottomPipe object
     * @return int
     */
    public int getWidth() {
        return bottomPipe.getWidth(null);
    }
    
    /**
     * Method to obtain the height of the BottomPipe object
     * @return int
     */
    public int getHeight() {
        return bottomPipe.getHeight(null);
    }
    
    /**
     * Method to set the x location of the BottomPipe object
     * @param x
     */
    public void setX(int x) {
        xLoc = x;
    }
    
    /**
     * Method to get the x location of the BottomPipe object
     * @return int
     */
    public int getX() {
        return xLoc;
    }
    
    /**
     * Method to set the y location of the BottomPipe object
     * @param y
     */
    public void setY(int y) {
        yLoc = y;
    }
    
    /**
     * Method to get the y location of the BottomPipe object
     * @return int
     */
    public int getY() {
        return yLoc;
    }
    
    /**
     * Method used to acquire a Rectangle that outlines the BottomPipe's image
     * @return Rectangle outlining the BottomPipe's position on screen
     */
    public Rectangle getRectangle() {
        return (new Rectangle(xLoc, yLoc, bottomPipe.getWidth(null), bottomPipe.getHeight(null)));
    }
    
    /**
     * Method to acquire a BufferedImage that represents the TopPipe's image object
     * @return TopPipe's BufferedImage object
     */
    public BufferedImage getBI() {
        BufferedImage bi = new BufferedImage(bottomPipe.getWidth(null), bottomPipe.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics g = bi.getGraphics();
        g.drawImage(bottomPipe, 0, 0, null);
        g.dispose();
        return bi;
    }
}

Dan langkah yang terakhir adalah sobat membuat class untuk bird nya itu sendiri ya tentu jelas , sobat buat dengan nama class nya itu Bird , kemudian sobat ketikkan codingan dibawah ini.




package GameFlappy;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.image.BufferedImage;

public class Bird {
    //global variables
        private Image flappyBird;
        private int xLoc = 0, yLoc = 0;
        
        /**
         * Default constructor
         */
        public Bird(int initialWidth, int initialHeight) {
            flappyBird = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/blue_bird.png"));
            scaleBird(initialWidth, initialHeight);
        }
        
        /**
         * Method to scale the bird sprite into the desired dimensions
         * @param width The desired width of the flappy bird
         * @param height The desired height of the flappy bird
         */
        public void scaleBird(int width, int height) {
            flappyBird = flappyBird.getScaledInstance(width, height, Image.SCALE_SMOOTH);        
        }
        
        /**
         * Getter method for the flappyBird object.
         * @return Image
         */
        public Image getBird() {
            return flappyBird;
        }
        
        /**
         * Method to obtain the width of the Bird object
         * @return int
         */
        public int getWidth() {
            try {
                return flappyBird.getWidth(null);
            }
            catch(Exception e) {
                return -1;
            }
        }
        
        /**
         * Method to obtain the height of the Bird object
         * @return int
         */
        public int getHeight() {
            try {
                return flappyBird.getHeight(null);
            }
            catch(Exception e) {
                return -1;
            }
        }
        
        /**
         * Method to set the x location of the Bird object
         * @param x
         */
        public void setX(int x) {
            xLoc = x;
        }
        
        /**
         * Method to get the x location of the Bird object
         * @return int
         */
        public int getX() {
            return xLoc;
        }
        
        /**
         * Method to set the y location of the Bird object
         * @param y
         */
        public void setY(int y) {
            yLoc = y;
        }
        
        /**
         * Method to get the y location of the Bird object
         * @return int
         */
        public int getY() {
            return yLoc;
        }
        
        /**
         * Method used to acquire a Rectangle that outlines the Bird's image
         * @return Rectangle outlining the bird's position on screen
         */
        public Rectangle getRectangle() {
            return (new Rectangle(xLoc, yLoc, flappyBird.getWidth(null), flappyBird.getHeight(null)));
        }
        
        /**
         * Method to acquire a BufferedImage that represents the Bird's image object
         * @return Bird's BufferedImage object
         */
        public BufferedImage getBI() {
            BufferedImage bi = new BufferedImage(flappyBird.getWidth(null), flappyBird.getHeight(null), BufferedImage.TYPE_INT_ARGB);
            Graphics g = bi.getGraphics();
            g.drawImage(flappyBird, 0, 0, null);
            g.dispose();
            return bi;
        }
    }

Dan pada langkah terakhir silahkan sobat klik kanan pada folder project flappy bird -> Export -> sobat pilih Runnable JAR File -> Silahkan Select Top Class -> Browse -> Buat Nama Flappy Bird -> Kemudian Finsih sobat bisa lihat gambar dibawah ini





Langkah selanjutnya adalah , sobat lihat pada folder jar yang baru saja kita buat barusan , kemudian sobat ganti extension .jar menjadi .zip , kemudian sobat extrack , nah pada gambar yang sebelumnya , yaitu gambar bird , dan pipa nya , sobat baut folder dengan nama folder resources , dan masukkan ketiga gambar tersebut didalam folder resource , bisa lihat detail gambar dibawah.


Jika sobat memakai windows 10 seperti admin ,silahkan sobat ke menu View, Ceklis pada bagian File Name Extenesion agar nanti bisa di ubah , saat muncul extensionnya , silahkan sobat renama yang tadjinya Flappy Bird.jar , menjadi Flappy Bird.zip, kemudian sobat extract kemudian masuk ke dalam Folder Flappy Bird nya seperti gambar dibawah ini :



Kemudian sobat masuk ke dalam folder GameFlappy , nah sobat buat folder resources , dan sobat masukkan ketiga gambar yang sebelumnya sobat sudah download , sobat bisa lihat gambar dibawah ini.




Setelah itu , silahkan sobat block kedua file yaitu , GameFlappy dan META-INF ,sobat klik kanan kemudian sobat jadikan folder zip lagi , yaitu dengan nama "FlappyBird.zip" , sehabis dijadikan zip balikan lagi ke FlappyBird.jar sobat bisa lihat gambar dibawah ini.




CATATAN : sobat jangan make spasi penamaan nya jadi cukup FlappyBird.jar oke jangan make spasi

dan langkah terakhir adalah untuk menjalankan nya ,caranya gampang banget sobat bisa lihat gambar dibawah ini, nah pada kotak merah itu adalah tempat dimana FlappyBird.jar kita berada , nah sobat tinggal perlu inget inget saja , eh btw itu belom tentu sama dengan direktori sobat ya , jadi samain aja di direktori sobat


Kemudian sobat gabungkan gambar Windows + R, kemudian sobat ketikkan cmd agar membuka command prompt , seperti gambar dibawah ini.


Saat kebuka , silahkan sobat ketikkan seperti gambar dibawah ini , contohnya , inget loh ya ini contoh , jadi setiap pengetikan sesuaikan dengan direktori dimana sobat menyimpan file .jar tersebut.


Ingat silahkan sobat ketikkan , sampai direktori .jar tersebut terimpan , nah ini langkah terakhir sobat , yaitu memulai game nya, kita masih berada di cmd ya , dengan cara ketikkan FlappyBird.jar di CMD seperti gambar dibawah ini :


Dan taraaaaa , sobat telah memulai game nya  hasilnya akan seperti gambar dibawah ini , mainnya untuk lompat lompat ya make space / tekan keyboard spasi aja.



Nah jadi tutorial Membuat Game Flappy Bird Sederhana dengan Java Eclipse sudah selesai cukup panjang dan menguras tenaga admin ngetik artikel ini hahaha, gpp demi sobat ku belajar bersama , semoga bermanfaat sobat, dan jangan lupa dishare jika bermanfaat , apabila error dan tidak mengerti menjalankan game nya , silahkan sobat komentar saja, dan sampai jumpai di tutorial selanjutnya

Anda mungkin menyukai postingan ini