0 votes
asked in JAVA by

    Java: Concatenate String-Int array & using array for possibilities?

1 Answer

0 votes
answered by (8.2k points)

Yes, there is a much simpler way. What you need to do is to be able to answer the question "is there a mine at coordinate X,Y?" This is done with a two dimensional array and the only thing you need is a yes/no boolean at each spot.

boolean[][] minePos = new boolean[5][5];

You set the mines like this (both parameters are numbers):

minePos[1][1] = true;  //this is 1A
minePos[1][2] = true;  //this is 1B

and so on. You have been using A, B, C, for the Y coordinate, and you need to use 1 for A, 2 for B, etc. The places where you set to true will be the places of mines. All the rest are false, indicating no mine is there. When the user want to move to position xpos, ypos, you test whether there is a mine there with this:

if (minePos[xpos,ypos]) {
    //tell them they were blown up
else {
    //you are OK, not blown up

If they are safe at xpos,ypos, and you want to restrict the movement to the squares around them, then it is easy to enumerate the eight possible jumps:

(xpos, ypos-1)
(xpos+1, ypos-1) 
(xpos+1, ypos) 
(xpos, ypos+1)
(xpos+1, ypos+1) 

and so on. They choose one of the eight directions, and based on this you find out where they are going to land. Then you test whether the landing position has a mine.

It is not clear how you want to prompt for user movement. Do they indicate "I want to move one square up"? You should already know where they are (in a couple variables) so given a direction it is easy to calculate where they land. Or are you going to ask them to enter a coordinate, like "A1"? Then you need to make sure that the coordinate they enter is next to the one that you know they are at. or you could show all the possible coordinates they might move to and let them select one. However you do it, you figure out what the destination numeric coordinate is, and then check if there is a mine there.

Start with a mines in fixed position, but later it will be easy to write a small loop that places mines at random X and Y positions. Something like this:

Random rand = new Random();

for (int count:=1; count<8; count++) {
    int randx = rand.nextInt(5);
    int randy = rand.nextInt(5);
    minePos[randx, randy] = true;

That will place 8 mines at a random x value (0 thru 4) and random y position (0 thru 4). You can change the size of the board, and the number of mines you want to place.