编写战列舰编组算法(java)

时间:2017-12-01 19:43:18

标签: java arrays algorithm

所以即时编程战舰游戏,我试图把船放在一块板上。我可以把它放在左边的船上,从起点上下来,但不能让它下降或离开。我理解我的方法总体上是无效的。

public static int[][] SetUserBoard(int[][] board) {

    int x;
    int y;

    y = 0;

    for (int z = 0; z < 10; z++) {
        String gridv;
        gridv = "";

        int direction;

        System.out.println("Set the Position for Ship no. " + (z+1));

        Scanner s1 = new Scanner(System.in);

        System.out.println("Enter the grid column(A-H):");

        gridv = s1.nextLine();


        if (gridv.equals("A")) {
            y = 0;
        }
        if (gridv.equals("B")) {
            y = 1;
        }
        if (gridv.equals("C")) {
            y = 2;
        }
        if (gridv.equals("D")) {
            y = 3;
        }
        if (gridv.equals("E")) {
            y = 4;
        }
        if (gridv.equals("F")) {
            y = 5;
        }
        if (gridv.equals("G")) {
            y = 6;
        }
        if (gridv.equals("H")) {
            y = 7;
        }


        System.out.println("Enter the y co=ordinate: ");
        x = s1.nextInt();
        x -= 1;

        System.out.println("Enter the direction of the ship 0-3(0=down,1=right,2=up,3=left): ");
        direction = s1.nextInt();

        if(z == 0) {    //placing 4 unit ship in first increment
            if(direction == 0 && x < 5){ //vertical placement - down
                for(int i=0; i < 4; i++) {
                    board[x][y] = 0;
                    x += 1;
                }
            }
            if(direction == 1 && y < 5) { //horizontal placement - right
                for(int i=0; i < 4; i++) {
                    board[x][y] = 0;
                    y += 1;
                }
            }
            if(direction == 2 && x > 3 ) {  //vertical placement - up
                for(int i=0; i < 4; i++) {
                    board[x][y] = 0;
                    x -= 1;
                }
            }
            if(direction == 3 && y > 3) {   //horizontal placement - left
                for(int i=0; i < 4; i++) {
                    board[x][y] = 0;
                    y -= 1;
                }
            }
        }
        ...if(z > 0 && z < 3) { //placing 3 unit ships in 2nd and 3rd increment....

    return board;


}

如果你忽略底部,并专注于if z = 0部分,那就是我用哪个部分用我最新的尝试来测试它。最初我有一个索引错误,我设法解决,但现在所有的程序都照常运行,除非进入下一个,董事会没有更新,仍然是空的。所以我很难理解用于向上/向左的逻辑。

1 个答案:

答案 0 :(得分:0)

对于对角线更改,您需要在穿越船舶时更改 ij。例如:

UP_LEFT = 4
...
ship_len = 4
...

        if(direction == UP_LEFT && 
           y > ship_len-1 &&
           x > ship_len-1) {   // SE-NW placement
            for(int i=0; i < ship_len; i++) {
                board[x][y] = 0;
                y -= 1;
                x -= 1;
            }
        }