Java Battleboats

0

Good morning everyone, I'm doing an exercise in java on the Naval Battle game, I have a lot of code but I'm stuck in the part of validating the position of the boats. The exercise asks that 4 bards of different sizes (2,3,4,5) be created in the vertical and horizontal position (calling the method) and that the position is random until ok. The problem is that sometimes a boat is built inside the other, sometimes it seems that it leaves the board (even without the message outofbounds). The method to validate is called this Free (I could not do much of it ...) Can anyone give me a tip? Thank you.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Random;

public class BatallaNaval {

/**
 * @param args the command line arguments
 */
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

static int cont = 0;
static int miss = 50;
static int[][] field = new int[10][10];

public static void main(String[] args) {

    int acertos = 0;
    iniciarField();
    colocarBarco(2, 'H');
    colocarBarco(3, 'V');
    colocarBarco(4, 'H');
    colocarBarco(5, 'V');
    mostraTabuleiro();

    while(cont<14 || miss>0){
    if(cont==14||miss==0){break;}
    jogar();
    System.out.println();
    mostraTabuleiro();

    }

}

public static void iniciarField() {

    for (int i = 0; i < field.length; i++) {

        for (int j = 0; j < field.length; j++) {

            field[i][j] = -1;
        }

    }
}

public static void colocarBarco(int longitud, char orientacion) {
     Random r = new Random();
int X;
int Y;
boolean livre = false;

if (orientacion == 'H') {

    do { 
        X = r.nextInt(9);
        Y = r.nextInt(9);
        livre = estaLivre(X, Y, longitud, 1); // 1 = horizontal
    } while(!livre); //podes alterar e colocar um limite mximo de iterações para precaver ciclos infinitos

    // se chegou aqui significa que encontraste uma posição para colocar o navio       
    for ( int i = Y; i <= Y + (longitud - 1); ++i) 
        field[X][i] = 2;

}

if (orientacion == 'V') {
  do { 
        X = r.nextInt(9);
        Y = r.nextInt(9);
        livre = estaLivre(X, Y, longitud, 0); 
    } while(!livre); 
  for ( int i = X; i <= X + (longitud - 1); ++i) 
        field[i][Y] = 2;
}
}

public static void mostraTabuleiro() {
    System.out.println("\t0\t1 \t2 \t3 \t4 \t5\t6\t7\t8\t9");
    System.out.println();

    for (int i = 0; i < 10; i++) {
        System.out.print((i) + "");
        for (int j = 0; j < 10; j++) {
            if (field[i][j] == 0) {
                System.out.print("\t" + "*");
            } else if (field[i][j] == 1) {
                System.out.print("\t" + "X");
            } else if (field[i][j] == 2) {
                System.out.print("\t" + "B");
            } else {
                System.out.print("\t" + "~");
            }

        }
        System.out.println();
    }

}

public static void jogar() {
    try {
        System.out.print("Linha: ");
        String num1Str = in.readLine();
        int linha = Integer.parseInt(num1Str);
        System.out.print("Coluna: ");
        String numStr = in.readLine();
        int coluna = Integer.parseInt(numStr);

        if (field[linha][coluna] == 2) {
            System.out.print("Barco tocado!");
            field[linha][coluna] = 1;
            cont++;
        }
        if (field[linha][coluna] == -1) {
            System.out.print("Agua!");
            field[linha][coluna] = 0;
            miss--;
        }
        if (cont == 14) {

            System.out.print("Has ganado!");

        }
        if (miss==0){
            System.out.print("GAME OVER!");
        }

    } catch (Exception e) {
        e.printStackTrace();

    }
}

// comprueba se o barco cabe

public static boolean estaLivre(int fila, int coluna, int tamanho, int direcao) {
   boolean eValido = true;

switch (direcao) {
    case 0: // Vertical
        if (fila + (tamanho - 1) >= 10) //valida se existe espaço suficiente na vertical para colocar o navio
            eValido = false;
        else
            for (int i = fila; i <= fila + (tamanho - 1) && eValido; i++)
                eValido  = eValido & (field[i][coluna] == -1);
        break;

    default: // Horizontal
        if (coluna - (tamanho - 1) >= 10) 
            eValido = false;
        else
            for (int i = coluna; i >= coluna - (tamanho- 1) && eValido; i++) 
                eValido = eValido & (field[fila][i] == -1);
        break;
}
return eValido;

}

}

    
asked by anonymous 03.05.2015 / 15:56

1 answer

0

Here is an outline of what you can do to validate whether the ship can be placed on the board.

private boolean estaLivre(int fila, int coluna, int tamanho, int direcao) {

    boolean eValido = true;

    switch (direcao) {
        case 0: // horizontal
            if (coluna + (tamanho - 1) >= 10) //valida se existe espaço suficiente na horizontal para colocar o navio
                eValido = false;
            else
                for (int i = coluna; i <= coluna + (tamanho - 1) && eValido; i++)
                    eValido  = eValido && (field[fila][i] == -1);
            break;

        default: // vertical
            if (linha + (tamanho - 1) >= 10) 
                eValido = false;
            else
                for (int i = linha; i <= linha+ (tamanho - 1) && eValido; i++) 
                    eValido = eValido && (field[i][coluna] == -1);
            break;
    }
    return eValido;
 }

Explanation of the code:

  • Receive as a parameter the line (row) and column where you want to place the first position of the ship;
  • It also receives the direction (Vertical / Horizontal) and the size of the ship;
  • If you want to put in Vertical: First validate if the board has enough space: row + (size - 1) must be less than 10 (assumes index starts at 0 and has 10 positions in total);
  • If passed the previous test means that there is space to place the ship. It remains to be checked whether each of the following positions is free;

Validation to position a ship horizontally is similar.

Important detail: This code does not check for "leaning" ships. It's just a starting point to help you understand the logic of validation.

As I said your function placesBarco is also not working well:

public static void colocarBarco(int longitud, char orientacion) {

    Random r = new Random();
    int X;
    int Y;
    boolean livre = false;

    if (orientacion == 'H') {

        do { 
            X = r.nextInt(9);
            Y = r.nextInt(9);
            livre = estaLivre(X, Y, longitud, 0); // 0 = Horizontal            
        } while(!livre); 

        // se chegou aqui significa que encontraste uma posição para colocar o navio       
        for ( int i = Y; i <= Y + (tamanho - 1); ++i) 
            field[X][i] = 2;

    }

    if (orientacion == 'V') {
      do { 
            X = r.nextInt(9);
            Y = r.nextInt(9);
            livre = estaLivre(X, Y, longitud, 1); // 1 = Vertical            
      } while(!livre); 

      // se chegou aqui significa que encontraste uma posição para colocar o navio       
        for ( int i = X; i <= X + (tamanho - 1); ++1) 
            field[i][Y] = 2;   
    }
}

I tested this implementation and it looks like everything is working correctly.

    
03.05.2015 / 16:39