Reputation: 61
I am trying to create a game in Java. In the game, a player will encounter some obstacles by clicking on buttons. Up until now, those obstacles were defined as integers, and if a button was clicked, numbers that represented these objects appeared. I would like to change those numbers into images, but I can't change the count[random1][random2] from int to string. Do you have any suggestions? (I will only add the tree obstacle here and its relevant code).
public class Tiles implements ActionListener {
final static int TREES = 10;
static JFrame frame = new JFrame("The Game");
JButton[] [] buttons = new JButton[5][5];
static int [] [] counts = new int [5] [5];
Panel grid = new Panel();
public Tiles() {
frame.setSize(400,400);
frame.setLayout(new BorderLayout());
makeGrid();
frame.add(grid, BorderLayout.CENTER);
grid.setLayout(new GridLayout(5,5));
for (int row = 0; row < buttons.length; row++) {
for (int col = 0; col < buttons[0].length; col++) {
buttons [row][col] = new JButton();
buttons [row][col].addActionListener(this);
grid.add(buttons[row] [col]);
buttons[row][col].setBackground(Color.WHITE);
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void makeGrid() {
int numTrees = 2;
Random random = new Random();
int i = 0;
while (i < numTrees) {
int random1 = random.nextInt(5);
int random2 = random.nextInt(5);
if( counts [random1] [random2] == 0) {
counts[random1] [random2] = TREES;
i++;
}
}
}
}
Upvotes: 1
Views: 54
Reputation: 3418
You could change the type of your count
variable from int[][]
to Map<Integer, Map<Integer, String>>
(or use the Table
class from Guava : https://www.baeldung.com/guava-table).
You could then retrieve the String
representing the image at the position (i,j)
with count.get(i).get(j)
.
Upvotes: 2