0

I am building simple java game which the user has to find gold. There are some obstacles like Orc, Goblin, and Poop.

What I am trying to do is that I am creating Cell and Board class.

Inside of my Cell class,

public Cell{
  public enum TheCell { Orc, Goblin, Poop, Gold, Empty};
    TheCell type;
  public Cell(TheCell type){
    this.type = type;
  }
}

and I make two dimensions in Board class,

public Board{
  Cell[][] grid = new Cell[7][7];
  Random r = new Random();

  for(int i = 0; i<3; i++){
    int randNum1 = r.nextInt(7);
    int randNum2 = r.nextInt(7);
    grid[randNum1][randNum2] = new Cell(Cell.TheCell.Orc);
  }
  for(int i = 0; i<3; i++){
    int randNum1 = r.nextInt(7);
    int randNum2 = r.nextInt(7);
    grid[randNum1][randNum2] = new Cell(Cell.TheCell.Goblin);
  }
}

My question is that, in case of Orc and Goblin are same cell, I wanna keep them both monster in same cell. Is there some how I can keep both or multiple obstacles in same cell? Thank you!

jayko03
  • 2,329
  • 7
  • 28
  • 51
  • the code certainly needs formatting. And I doubt you can save two values in a cell of the array. Maybe Map might solve it for you with multiple values -> http://stackoverflow.com/questions/4956844/hashmap-with-multiple-values-under-the-same-key – Naman Nov 08 '16 at 05:26

2 Answers2

2

One way to achieve this is to have the Cell class hold a list of all monsters/things that are currently on the cell (using the enum, that is already available)

A more "low level" approach is to use an Integer for the cell and then use bitflags to model multiple obstacles on the same cell.

Update: I agree with @ajb, in this case an Enum Set should be used

As pointed out by @JimGarrison, the EnumSet approach only works until you need to have more than one instance of an enum value for one cell.

Gernot
  • 384
  • 1
  • 3
  • 11
  • 2
    No need to use an integer--Java provides `EnumSet`. (Either way will work only if you can't have more than one of the same obstacle.) – ajb Nov 08 '16 at 05:26
  • @Jay Sure, or you can go to the javadoc [here](http://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html) – ajb Nov 08 '16 at 05:33
  • 2
    `EnumSet` works until you need to have more than one instance of an enum value. You could have 2 Orcs or 2 Goblins converge on a cell in some version of the game. – Jim Garrison Nov 08 '16 at 06:10
  • @Jay You're even encouraged to google for any terms you're not familiar with. – Kayaman Nov 08 '16 at 06:10
  • @JimGarrison Okay. I will check it out too Thank you! – jayko03 Nov 08 '16 at 17:11
  • @Kayaman Of course, I can. Problem is that sometimes I don't know what to google or keyword to search. – jayko03 Nov 09 '16 at 00:30
-2
public Cell{
  public enum TheCell { Orc, Goblin, Poop, Gold, Empty};

  List<TheCell> type = new ArrayList<TheCell>();

  public Cell(TheCell type){
    addType(type);
  }

  public addType(TheCell type) {
    this.type.add(type);
  }
}