I’m making a game. In the game there is a grid that is populated by cells. Each cell has a partner (same type of cell). There should be 24 total cells which would mean 12 different pairs of cells. For example a cell can be type 1, there will be two type 1 cells on the grid.
All the way until type 12.
What I’m trying to achieve with my code is to randomly generate a row and column and then place a cell of type 1 on it. AGAIN, generate random row and column and place type 1 cell on it.
Then increment type.
Now what I am struggling with is the condition that will make sure my entire grid is fully populated with cells.
Further more a condition that makes sure that once a cell has been placed at a spot on the grid, it cannot be replaced by another cell.
Here is the code that I’ve come up with for now.
int type =1;
int row=0;
int column=0;
board[row][column] = new Cell(this, type, row, column);
while(board[row][column] != null){
if(type <=12){
row = generator.nextInt(4);
column = generator.nextInt(6);
board[row][column] = new Cell(this, type, row, column);
type++;
if (type < 13){
row = generator.nextInt(4);
column = generator.nextInt(6);
board[row][column] = new Cell(this, type, row, column);
row = generator.nextInt(4);
column = generator.nextInt(6);
board[row][column] = new Cell(this, type, row, column);
add(board[row][column]);} //Adding a Cell object **board is a 2d array of type Cell**
}
}
}
Tried my best to explain the problem in the most simple terms
A better way to do this than adding items at random would be to populate the array in a straightforward way and then randomise it, but there is no easy way to do that.
There is an equivalent thing you can do: create a
Listwith all the required values in, randomlyshuffletheListand then populate your array from that, mapping the entries in the List to the rows and columns on your array:The mapping of rows and columns to List entries isn’t all that important, as long as you use each entry from the shuffled List only once, so you could do this: