2

This is my background Image that i have usedI am a New programmer and I am still learning to code. I am tring to create a flappy bird game but my code does not seem to work. What I am tring to do is create code that generates random pipes within my program and tring to make them have collision with the red Ball.

I have tried to look around for flappy bird games that explain to me how it works but it does not work within my code or it is very very complicated I can not understand.

Hey Thanks for the help but I had tried to implement your code and I got this error. I am trying to fix this. As for your other comments I was trying to make a game called flappy bird in which I must generate random pipes with varying heights of pipes with the same amount of space in between. This is what is happening:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;
import java.awt.Rectangle;

/**
 * Auto Generated Java Class.
 */
public class Game extends JFrame implements ActionListener{
  static final int NUMBER_OF_OBSTACLES = 30; // pre-assign the number of obstacles to be generated

  // setup our objects for our game
  JLabel[] columns = new JLabel [NUMBER_OF_OBSTACLES];
  public Rectangle bird;
  public final int WIDTH = 100, HEIGHT = 100;
  public Random rand;

  int number;
  ImageIcon lblBackground = new ImageIcon("Test1.jpg");
  ImageIcon lblBackground2 = new ImageIcon("Background2.jpg");
  static int randomNumber; 
  int xLocation = 0;
  int yLocation = 0;
  int wLocation = 450;
  int xForRect = 300;
  int yForBall = 300;
  int xForRectTop = 300;
  static int randY; 
  int xSpeed = 1;
  int ySpeed = 1;
  int delay = 5;
  Rectangle rect;

  public Game() { 
    Rectangle column [];
    column = new Rectangle [150];

    setLayout(null);
    setSize (404, 600);
    setVisible(true);   //sets everything to visable 

  }
  private void generateRectangles() {
    for (int i = 0; i < columns.length; i ++ ) {
      columns[i] = new JLabel("" + i); // the name of the object will be shown as the number it is
      columns[i].setBackground(Color.green);
      columns[i].setOpaque(true);
      columns[i].setBounds(randomRect());
    }
  }

  private Rectangle randomRect() {

    // create a rectangle to store the bounds of our new object
    Rectangle rect = new Rectangle();

    rect.height = randomizer(5, 100); // random height 1 to 100
    rect.width = randomizer(5, 100);  // random width 1 to 100

    return rect;
  }

  private static int randomizer(int min, int max) {
    Random random = new Random(); // create new randomizer

    int number = random.nextInt(max - min); //randomizes a number from 0 to dist between them (for example if we are generating from 50 to 100 it will run from 0 to 50)
    number = number + min; // then add 50 to match the bottom range

    return number; // return this random number to the method that called for it
  }



  public void makeColumn(Graphics g, Rectangle column) {
    g.setColor(Color.green);
    g.fillRect(column.x, column.y, column.width, column.height);
  }


  public static int addRandomColumn() {
    randomNumber = (int)(Math.random() * 300 + 250); 
    randomNumber = randY;
    return  randY;
  }


  public void paint(Graphics g){
    super.paint(g);
    for (int p = 0; p < 9999999; p = p+1)  { 
      for (int i = 0; i <=630; i= i + 1){

        lblBackground.paintIcon(this,g, xLocation, yLocation);
        System.out.println(xLocation);
        xLocation = xLocation - xSpeed;



        g.setColor(Color.red);
        g.fillRect(150, yForBall, 20, 20);

        yForBall = yForBall + 1;

        rect = new Rectangle(xForRect,450,50,number);

        makeColumn(g,rect);
        rect = new Rectangle(xForRectTop,0,50,number);
        makeColumn(g,rect); 

        xForRect = xForRect -1;
        xForRectTop = xForRectTop -1;

        try { 
          Thread.sleep(delay);
        }
        catch (Exception error) {
        }
      }
    }

  }

  public void actionPerformed(ActionEvent evt){

  }
  public static void main(String[] args) { 
    new Game();
  }

}

That I what I have so far. Hope you can help me

What I was planing to do was generate pipes in in the program with varying heights.

JFreeman
  • 974
  • 1
  • 10
  • 26
Vish
  • 29
  • 4
  • 1
    FYI [Java is to JavaScript as Car is to Carpet](https://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java) – p.s.w.g Jan 19 '19 at 01:21
  • What exactly is the issue: Does the code you posted run? Are you receiving an error? – JFreeman Jan 19 '19 at 01:59
  • 1
    At your level, you should probably be following along with some well documented game tutorials rather than developing your own game. – MarsAtomic Jan 19 '19 at 03:39

1 Answers1

0

I will address you question in 2 areas.

1. Firstly project design

It is good to have an idea of what you want before you ask a question or begin writing your program. From the sounds of it I assume you are trying to make a game where you control a bird which must avoid obstacles.

Currently you are generating your game by drawing the components onto the frame. This is a good option but I prefer to generate the components as objects (usually JLabels so that it is easy to give them graphics). By creating objects it allows you to only modify the object on the screen if you want to move it during the game rather than repainting all the components.

Java is an object oriented programming language so it is best if you design your program with a modular structure.

Here are the key features of your program which must be created:

  • Background JFrame
  • Obstacle creator
  • Input listener
  • Collision checker

I will address merely the obstacle creator because that is what you have asked about in your question.

When writing the obstacle creator you want to write it in a way that is robust and easy to use multiple times. Ideally this will come in the form of a class or function which can be called and returns and object on your screen. This will allow for maximum flexibility.

Also it is worth noting that unless you plan on using your procedures in other classes the modifier public is unnecessary, using private void is better practice.

2. Writing Code

Here I have re-written your program in a simpler way. By not overriding the paint method you save yourself much hassle.

Note the key changes I have made:

  1. I am now generating your game components as JLabels. They are created by the procedures in the Game() method.

  2. The rectangles are no longer painted which will allow easier collision detecting when you write that part of the program

  3. Notice how I created a function which randomly generates numbers. I can now easily call this function from other places in the program later.

  4. Lastly I removed your delay Thread.sleep(delay); code. It is better to use a timer thread to handle your events rather than a delay. I would recommend you create a timer thread which runs parallel to your program. Ever half second when the thread runs you can move the bird in the direction of the input and then check if it has collided with an object from columns array.

    import javax.swing.*;       
    import java.awt.*;      
    import java.awt.event.*;        
    import java.util.Random;        
    import java.awt.Rectangle;      
    
    
    public class Game extends JFrame implements ActionListener{
    
      static final int NUMBER_OF_OBSTACLES = 30; // pre-assign the number of obstacles to be generated
    
      // setup our objects for our game
      JLabel[] columns = new JLabel [NUMBER_OF_OBSTACLES];
      JLabel bird;
    
      public Game() { 
    
        // setup the frame
        setLayout(null);
        setSize (404, 600);
        setVisible(true);   //sets everything to visable 
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    
        generateRectangles();
    
        placeBird();
    
      }
    
       private void placeBird() {
            // create the new bird
            bird = new JLabel("B");
            bird.setBackground(Color.red); // set background
            bird.setOpaque(true);          // make the label's background color not invisible but opaque
            bird.setBounds(this.getWidth()/2, 0 , 30, 30); // place bird at top midpoint of screen, its size is a 30,30 square
            this.add(bird);               // add the bird to our frame
            bird.setVisible(true);        // show the bird on our frame
       }
    
       private void generateRectangles() {
           for (int i = 0; i < columns.length; i ++ ) {
               columns[i] = new JLabel("" + i); // the name of the object will be shown as the number it is
               columns[i].setBackground(Color.green);
               columns[i].setOpaque(true);
               columns[i].setBounds(randomRect());
               this.add(columns[i]);
               columns[i].setVisible(true);
           }
       }
    
       private Rectangle randomRect() {
    
           // create a rectangle to store the bounds of our new object
           Rectangle rect = new Rectangle();
    
           rect.height = randomizer(5, 100); // random height 1 to 100
           rect.width = randomizer(5, 100);  // random width 1 to 100
           rect.x = randomizer(1, this.getWidth()); // random x position up to the width of the frame
           rect.y = randomizer(30, this.getHeight()); // random y position from 30 up to the height of the frame (NOTE: the 30 gap is so no obstacles start on top of the bird)
    
           return rect;
       }
    
       private static int randomizer(int min, int max) {
            Random random = new Random(); // create new randomizer
    
            int number = random.nextInt(max - min); //randomizes a number from 0 to dist between them (for example if we are generating from 50 to 100 it will run from 0 to 50)
            number = number + min; // then add 50 to match the bottom range
    
            return number; // return this random number to the method that called for it
        }
    
    
        // main runs on startup creating our frame
        public static void main(String[] args) { 
            Game game = new Game(); // start a new game
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    
JFreeman
  • 974
  • 1
  • 10
  • 26
  • Hey Thanks for the help but I had tried to implement your code and I got this error. I am tring to fix this. As for your other comments I was tring to make a game called flappy bird in which I must generate random pipes with varring hieghts of pipes with the same amount of space in between and it must do this until the end. I have edited what is happening to my code. I think I am not calling the method the right way but I am not sure how to solve it – Vish Jan 19 '19 at 23:20
  • @Vish - Okay yes that makes sense. What is the error you recieved? – JFreeman Jan 19 '19 at 23:36
  • Okay So I am not getting a error but my pipes are not showing I am calling the variable number in my rect so it generates a random height. Am I calling the variable right because everything compiles but the the pipes wont generate. I have showed what I have done. – Vish Jan 20 '19 at 14:42
  • @Vish - Your issue is that your code never actually calls the procedure I wrote, so it never is used. Have a look at this link https://beginnersbook.com/2013/03/constructors-in-java/ it explains how constructors work. – JFreeman Jan 20 '19 at 20:02
  • Yea I have looked at the link but I dont know which procedure procedure to call apon. – Vish Jan 21 '19 at 00:32
  • @Vish - I am sorry but I don't think I can help you any further because you are asking a technical question but do not yet know enough about java. I would suggest practicing designing simpler programs with graphics before you attempt this. This is a great link for game design : https://www.gamedesigning.org/learn/java/ – JFreeman Jan 25 '19 at 04:07