【问题标题】:I'm trying to create random object using arrays and class with random locations?我正在尝试使用具有随机位置的数组和类创建随机对象?
【发布时间】:2020-03-10 22:31:41
【问题描述】:

我正在尝试使用类创建一个游戏,其中对象移动到随机位置并使用数组以随机数量相加。有人可以帮我更好地编码,因为它不起作用吗?顺便说一句,我用的是“Processing”软件。

我的代码

我的班级

*final color ALIEN_COLOR = color(30, 100, 0);
 PImage background;
 int x=0; //global variable background location
 Superhero hero1;
 Alien [] invader1 = new Alien[8];
 void setup(){

   size(800,400);
   background = loadImage("spaceB.jpg");
   background.resize(width,height);

   hero1 = new Superhero(10, height/2); 

   for(int i = 0; i < invader1.length; i++){
     invader1[i] = new Alien();
     invader1 = new Alien(width,300);
  }

  } // setup ends
   void draw ()
 {
   drawBackground();
   hero1.render();
   invader1.render();

   if(invader1.move() == false){
   invader1 =  new Alien(width, 500);
  }

  } // draw ends*

对象为:

  ***class Alien{
     int x;
     int y;

   Alien(int x, int y){
    this.x = x;
    this.y = y;
   }

  void render(){
    fill(ALIEN_COLOR);
    rect(x, y, 50, 50);
   }

  boolean move(){
    x = x - 1;
    return (x >= 0);
  } 
 }*** 

我收到的错误信息是:

  • 构造函数 Alien() 不存在。
  • 不匹配,Defenders.Alien 不匹配 Defenders.Alien[]

【问题讨论】:

  • invader1 = new Alien(width,300); 看起来不正确,只是猜测。我对processing了解不多。
  • 这里相同invader1 = new Alien(width, 500);。您似乎正在获取一个数组并将其视为单个变量。
  • 如果这不是一个任务并且你这样做是为了学习,我建议你看看代码的本质。这是一本免费的电子书,可以帮助您在掌握其他想法的同时学习处理。我使用这本书,但我使用 JavaFX 编码而不是处理。
  • 您的其他问题已在给定答案中得到解决。

标签: java arrays class object processing


【解决方案1】:

您正在调用invader1[i] = new Alien();,但Alien 类中没有无参数构造函数。在Alien 类中声明一个无参数构造函数,如下所示:

Alien() {
    // Put here some initialization code if needed else leave it as it is
}

【讨论】:

  • 这不是类似的吗,***class Alien{ int x;整数y;外星人(int x,int y){ this.x = x;这个.y = y; }
  • 没有。 Alien() 是一个无参数构造函数,而 Alien(int x, int y) 是一个有两个参数的构造函数。
  • @Unknown - 我希望该解决方案对您有用。不要忘记接受答案,以便将来的访问者也可以放心地使用该解决方案。检查meta.stackexchange.com/questions/5234/… 了解如何操作。如有任何疑问/问题,请随时发表评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 2023-03-15
  • 2020-11-10
  • 2018-05-17
  • 2018-02-18
  • 1970-01-01
  • 2014-05-05
相关资源
最近更新 更多