Как хранить объекты из класса в массиве - PullRequest
0 голосов
/ 23 марта 2020

Привет, так что мне было поручено создать «падающую игру», и у меня есть классы для каждой вещи, такой как пользователь и враг. Мне было интересно, как бы я go о хранении врагов в массиве. Я провел некоторые исследования, пробную версию и тестирование, и мне кажется, что мне нужно использовать массив объектов, чтобы хранить их в массиве и вызывать их из массива. Правильно ли я в это верю? Я попытался сохранить их в массиве для PImage, но это не сработало. Я не уверен, как создать массив объектов. Вот мой класс для врага, который называется салат lol:

class Salad {
 float x,y;
 float speedX, speedY; //declaring variables
 PImage saladImage;

 Salad(int x, int y, int speedY) {
  this.x = x;
  this.y = y;
  this.speedY = speedY;
  saladImage = loadImage("salad.png");
  saladImage.resize (60, 52);  
 } //end of salad

 void move() {
   y=y-speedY;
   float stepY = random(-5,5);
   y = y + (int)stepY;

   float rand = random(25,475);
   int intRand = int(rand);   

   if (this.y < 0) {
    this.y = 900; // once the salads y is less than 0 they restart at 900
    this.x = intRand;
    speedY = speedY + 0.5;
   }
 } //end of void move

 //draw a salad
 void render()
 {
image(saladImage,x,y);

} //end of void render 

 void update() {
  move();
  render();
 }
}// end of alien class

Вот мой основной класс, и я хотел сохранить класс бургер и салат в массиве, если это было возможно:

PImage background;
PImage MenuBackground;
int y=0;//global variable background location
final int End = 0;
final int Active = 1;
final int Menu = 2;
int gameMode = Menu;
int score = 0;
int lives = 3;
Boolean BurgerCollisionInProgress = false;
Boolean BurgerCollisionInProgress2 = false;


Salad salad1;
Salad salad2;
Salad salad3;
Homer user1;
Burger Burger;


public void settings() {
 size(500,1000); //setup size of canvas
}

void menu() {
 background = loadImage("spaceBackground.jpg"); //image used for background
 background.resize(500,1000); //resizes the background
 gameMode = Active; 

float rand = random(25,475);
int intRand = int(rand);

float rand2 = random(25,475);
int intRand2 = int(rand2); 

float rand3 = random(25,475);
int intRand3 = int(rand3); 

float rand4 = random(25,475);
int intRand4 = int(rand4); 


 user1 = new Homer(250,100);  //declares new defender as user1
 Burger = new Burger(intRand,900,2);
 salad1 = new Salad(intRand2,900,3);
 salad2 = new Salad(intRand3,900,3);
 salad3 = new Salad(intRand4,900,3); //3 aliens declared with their x and y position and their speed they move at
 draw();
}


void setup() {
  if(gameMode == 2) {    
    MenuBackground = loadImage("simpMenu.png");
    MenuBackground.resize(540,1000);
    image(MenuBackground, 0, y);
    textAlign(CENTER);
    textSize(40);
    fill(252, 3, 3);
    text("Press 'p' to play", 250,500);     
  } 
}


void draw () {  
  if (gameMode == Active) {        
    if(crash() == false) {
      drawBackground();//calls the drawBackground method
      textSize(32);
      fill(22,100,8);
      text("Score: " + score,75,40); 
      text("Lives: " + lives,75,80);
      salad1.update();//calls the update method which holds the move and render methods for alien
      salad2.update();
      salad3.update();
      user1.render();//calls the update method which holds the move and render methods for user
      Burger.update();//calls the update method which holds the move and render methods for burger

      if(Bcrash() == true && BurgerCollisionInProgress == false) {
      score = score+1;
      BurgerCollisionInProgress = true;
      Burger.y = 900;
      float rand = random(25,475);
      int intRand = int(rand);
      Burger.x = intRand;
      }

      if(Bcrash() == false) {
      BurgerCollisionInProgress = false;
      }


      if(crash() == true && BurgerCollisionInProgress2 == false) {
        if (lives < 1) {   gameMode = End;
            textSize(28);
            fill(22,100,8);
            text("Game Over, press 'r' to restart",50,200);
        }
        else {
          lives = lives - 1;
          BurgerCollisionInProgress2 = true;
          menu();
          //salad1.update();
          //salad2.update();
          //salad3.update();
        }
        if (crash() == false) {
          BurgerCollisionInProgress2 = false;
      }
     }      
    }
  }
}

void drawBackground() {
 image(background, 0, y); //draw background twice adjacent
 image(background, 0, y-background.width);
 y -=2;
 if(y == -background.width)
 y=0; //wrap background
}


void keyPressed() //allows the user to press the up and down keys to move the defender
{ 
  if(key == CODED) {
     if (keyCode == UP) {
       user1.y = user1.y - 7;
     }

     else if (keyCode == DOWN) {
       user1.y = user1.y + 7;
     }

     else if (keyCode == LEFT) {
       user1.x = user1.x - 7;
     }

     else if (keyCode == RIGHT) {
       user1.x = user1.x + 7;
     }

  } //key   

  if(key=='r') {
       menu();
     }

     if(key=='p') {
       menu();
     }
}


  boolean crash() {
    if(user1.crash(salad1)) {
      return true;
    }
    if(user1.crash(salad2)) {
      return true;
    }
    if(user1.crash(salad3)) {     
      return true;
    }
    return false;
  }


  boolean Bcrash() {
    if(user1.crash(Burger))
    {      
      return true;
    }
    return false;
  }

Ответы [ 2 ]

1 голос
/ 23 марта 2020

Вы можете создать интерфейс с именем Food и реализовать его в Salad и Burger, а также создать список Food

public interface Food {}
public class Salad implements Food {}
public class Salad implements Burger {}

и создать список с помощью:

List<Food> list = new ArrayList<>();
Burger burger = new Burger();
Salad salad = new Salad();

list.add(burger);
list.add(salad);

, и вы можете проверить их при получении по

Food food = list.get(0);
if (food instanceof Salad) {
  Salad s = (Salad) food;
  // do somesthing
} else if (food instanceof Burger) {
  Burger b = (Burger) food;
  // do somesthing
}
0 голосов
/ 23 марта 2020

Вот синтаксис: Допустим, вам нужен ArrayList of Salad:

ArrayList<Salad> mySalads = new ArrayList<Salad>();

Если у вас есть только одно изображение для ваших салатов, вы можете загрузить его в глобальную переменную только один раз и использовать из там вместо загрузки его в память для каждого экземпляра Salad, но это совсем другое.

Ваш проект выглядит интересно, получайте удовольствие!

...