【问题标题】:How do I make Random generating objects come on my Screen?如何让随机生成的对象出现在我的屏幕上?
【发布时间】:2019-01-19 01:15:56
【问题描述】:

This is my background Image that i have used我是一名新程序员,我还在学习编程。我正在尝试创建一个飞扬的小鸟游戏,但我的代码似乎不起作用。我要做的是创建代码,在我的程序中生成随机管道,并试图让它们与红球发生碰撞。

我试图四处寻找可以向我解释它是如何工作的 Flappy Bird 游戏,但它在我的代码中不起作用,或者它非常复杂,我无法理解。

您好,感谢您的帮助,但我曾尝试实现您的代码,但出现此错误。我正在尝试解决这个问题。至于您的其他 cmets,我正在尝试制作一个名为 flappy bird 的游戏,在该游戏中,我必须生成具有不同高度的随机管道,并且它们之间的空间量相同。这就是正在发生的事情:

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();
  }

}

我到目前为止所拥有的一切。希望你能帮助我

我打算在程序中生成不同高度的管道。

【问题讨论】:

  • 究竟是什么问题:您发布的代码是否运行?您收到错误消息了吗?
  • 在您的水平上,您可能应该遵循一些有据可查的游戏教程,而不是开发自己的游戏。

标签: java drjava


【解决方案1】:

我将在 2 个方面解决您的问题。

1.首先是项目设计

在提出问题或开始编写程序之前,最好先了解自己想要什么。从它的声音来看,我假设您正在尝试制作一个游戏,您可以控制一只必须避开障碍物的小鸟。

目前,您通过将组件绘制到框架上来生成游戏。这是一个不错的选择,但我更喜欢将组件生成为对象(通常是JLabels,以便为它们提供图形)。通过创建对象,它允许您仅在游戏过程中移动它时修改屏幕上的对象,而不是重新绘制所有组件。

Java 是一种面向对象的编程语言,因此最好使用模块化结构来设计程序。

以下是必须创建的程序的主要功能:

  • 后台JFrame
  • 障碍创造者
  • 输入监听器
  • 碰撞检查器

我将仅针对障碍物制造者,因为这是您在问题中提出的问题。

在编写障碍创建器时,您希望以一种健壮且易于多次使用的方式编写它。理想情况下,这将以类或函数的形式出现,可以在屏幕上调用并返回和对象。这将允许最大的灵活性。

另外值得注意的是,除非您打算在其他类中使用您的过程,否则修饰符public 是不必要的,使用private void 是更好的做法。

2。编写代码

在这里,我以更简单的方式重新编写了您的程序。通过不覆盖绘制方法,您可以省去很多麻烦。

注意我所做的关键更改:

  1. 我现在将您的游戏组件生成为 JLabels。它们由 Game() 方法中的过程创建。

  2. 不再绘制矩形,这样在您编写程序的那部分时可以更轻松地检测碰撞

  3. 请注意我是如何创建一个随机生成数字的函数的。我现在可以在以后从程序的其他地方轻松调用这个函数了。

  4. 最后我删除了你的延迟Thread.sleep(delay); 代码。最好使用timer thread 来处理您的事件而不是延迟。我建议您创建一个与您的程序并行运行的计时器线程。线程运行的每半秒,您可以将小鸟朝输入的方向移动,然后检查它是否与来自columns 数组的对象发生碰撞。

    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.
        }
    

【讨论】:

  • 嘿,感谢您的帮助,但我曾尝试实现您的代码,但出现此错误。我正在努力解决这个问题。至于您的其他 cmets,我正在尝试制作一个名为 flappy bird 的游戏,在该游戏中,我必须生成具有不同高度的随机管道,并且它们之间的空间量相同,并且必须这样做直到结束。我已经编辑了我的代码发生的事情。我认为我没有以正确的方式调用该方法,但我不确定如何解决它
  • @Vish - 好的,是的,这是有道理的。您收到的错误是什么?
  • 好的,所以我没有收到错误,但我的管道没有显示我正在调用我的矩形中的变量号,因此它会生成随机高度。我是否正确调用了变量,因为一切都可以编译,但管道不会生成。我已经展示了我所做的。
  • @Vish - 你的问题是你的代码从来没有真正调用过我写的过程,所以它从来没有被使用过。看看这个链接beginnersbook.com/2013/03/constructors-in-java 它解释了构造函数是如何工作的。
  • 是的,我查看了链接,但我不知道调用 apon 的过程过程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 2022-06-13
  • 2014-04-07
  • 2012-01-24
相关资源
最近更新 更多