对特定的char - TCP和char [] []问题做出反应

时间:2014-10-28 14:29:51

标签: java tcp network-programming char

我正在用Java创建一个战舰的TCP游戏,并且由于我已经使一些功能起作用,过去工作的方法不再有效。

以下是用户转向时发生的事情。炸弹被放在2个不同的char [] []上,其中clientGrid是客户端有船的实际网格。它正在这个正在打印dropBomb方法的网格上,并告诉我们炸弹是否已经命中。 clientDamage只是服务器的概述,可以看到他之前投下炸弹的位置。

if (inFromServer.ready()) {
                    System.out.println("\nInput coordinate");
                    int x = scan.nextInt();
                    int y = scan.nextInt();
                    System.out.println(dropBomb(x, y, clientGrid));
                    dropBomb(x, y, clientDamage);
                    outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
                    System.out.println(printBoard(clientDamage));
                }

这是滴弹方法。它之前被证明有效,但是我对它做了一些小改动。但是,我不明白为什么它不会起作用。 +表示有一艘船,x表示目标已被轰炸,而其他是〜,即水。该方法始终返回"此坐标上没有任何内容......",我似乎无法找出原因?

public static String dropBomb(int row, int col, char[][] board) {
        if (row < gridSize && col < gridSize) {
            if (board[row][col] == '+') {
                board[row][col] = 'x';
                return "Ship has been hit!";
            } else if (board[row][col] == 'x') {
                return "Already bombed.";
            } else {
                board[row][col] = 'x';
                return "Nothing was hit on this coordinate...";
            }
        } else {
            return "No such coordinate.";
        }
    }

以下是完整的代码......有人可以指出我错过的内容吗?

//server = player 1
//client = player 2
public class BattleshipGame {

    public static ArrayList<Ship> fleet;
    public static InetAddress clientAddress;
    public static BattleshipGame battleship;
    private final static int gridSize = 11;
    public final static int numberOfShips = 3;
    public static char[][] serverGrid;
    public static char[][] clientGrid;
    public static char[][] serverDamage;
    public static char[][] clientDamage;
    private int whosTurn;
    private int whoStarts;
    public static int count;
    public static int bombCount;

    public BattleshipGame() {
        whoStarts = 0;
        start();
        showShipList();
    }

    public static String printBoard(char[][] board) {
        String out = "";
        for (int i = 1; i < board.length; i++) {
            for (int j = 1; j < board.length; j++) {
                out += board[j][i];
            }
            out += '\n';
        }
        return out;
    }

    public void start() {
        Random rand = new Random();
        if (rand.nextBoolean()) {
            whoStarts = 1;
            whosTurn = 1;
        } else {
            whoStarts = 2;
            whosTurn = 2;
        }
        whoStarts = 1;
        whosTurn = 1;
        System.out.println("Player " + whoStarts + " starts\n");
    }

    public void initializeGrid(int playerNo) {
        serverGrid = new char[gridSize][gridSize];
        for (int i = 0; i < serverGrid.length; i++) {
            for (int j = 0; j < serverGrid.length; j++) {
                serverGrid[i][j] = '~';
            }
        }
        serverDamage = new char[gridSize][gridSize];
        for (int i = 0; i < serverDamage.length; i++) {
            for (int j = 0; j < serverDamage.length; j++) {
                serverDamage[i][j] = '~';
            }
        }
        clientGrid = new char[gridSize][gridSize];
        for (int i = 0; i < clientGrid.length; i++) {
            for (int j = 0; j < clientGrid.length; j++) {
                clientGrid[i][j] = '~';
            }
        }
        clientDamage = new char[gridSize][gridSize];
        for (int i = 0; i < clientDamage.length; i++) {
            for (int j = 0; j < clientDamage.length; j++) {
                clientDamage[i][j] = '~';
            }
        }
        if (playerNo == 1) {
            System.out.println("\nYour grid (player 1):\n"
                    + printBoard(serverGrid));

        } else if (playerNo == 2) {
            System.out.println("\nYour grid (player 2):\n"
                    + printBoard(clientGrid));
        } else {
            System.out.println("No such player.");
        }
    }

    public static void deployShip(char[][] board, Ship ship, char direction,
            int x, int y) {
        if (direction == 'H') {
            if (x < gridSize && y < gridSize) {
                for (int i = 0; i < ship.getSize(); i++) {
                    board[x + i][y] = '+';
                }
                System.out
                        .println("Ship has been placed horizontally on coordinates "
                                + x + ", " + y + ".");
            } else {
                System.out.println("Unable to place ship in this coordinate.");
            }
        } else if (direction == 'V') {
            if (x < gridSize && y < gridSize) {
                for (int i = 0; i < ship.getSize(); i++) {
                    board[x][y + i] = '+';
                }
                System.out
                        .println("Ship has been placed vertically on coordinates "
                                + x + ", " + y + ".");

            } else {
                System.out.println("Unable to place ship in this coordinate.");
            }
        }
    }

    public static String dropBomb(int row, int col, char[][] board) {
        if (row < gridSize && col < gridSize) {
            if (board[row][col] == '+') {
                System.out.println(board[row][col]);
                board[row][col] = 'x';
                bombCount++;
                return "Ship has been hit!";
            }
            if (board[row][col] == 'x') {
                System.out.println(board[row][col]);
                bombCount++;
                return "Already bombed.";
            }
            if (board[row][col] == '~') {
                System.out.println(board[row][col]);
                board[row][col] = 'x';
                bombCount++;
                return "Nothing was hit on this coordinate...";
            }
        } else {
            return "No such coordinate.";
        }
        return "";
    }

    public void showShipList() {
        System.out
                .println("Choose ships to add to your fleet from the following list ("
                        + numberOfShips + " ships allowed):");
        ArrayList<Ship> overview = new ArrayList<Ship>();
        Ship ac = new Ship("Aircraft carrier", 5, false);
        Ship bs = new Ship("Battleship", 4, false);
        Ship sm = new Ship("Submarine", 3, false);
        Ship ds = new Ship("Destroyer", 3, false);
        Ship sp = new Ship("Patrol Boat", 2, false);
        overview.add(ac);
        overview.add(bs);
        overview.add(sm);
        overview.add(ds);
        overview.add(sp);
        for (int i = 0; i < overview.size(); i++) {
            System.out.println(i + 1 + ". " + overview.get(i));
        }
    }

    public static ArrayList<Ship> createFleet(ArrayList<Ship> fleet, int choice) {
        if (count < numberOfShips && choice > 0 && choice < 6) {
            if (choice == 1) {
                Ship ac = new Ship("Aircraft carrier", 5, false);
                fleet.add(ac);
                count++;
                System.out.println("Aircraft carrier has been added to fleet.");
            } else if (choice == 2) {
                Ship bs = new Ship("Battleship", 4, false);
                fleet.add(bs);
                count++;
                System.out.println("Battleship has been added to fleet.");
            } else if (choice == 3) {
                Ship sm = new Ship("Submarine", 3, false);
                fleet.add(sm);
                count++;
                System.out.println("Submarine has been added to fleet.");
            } else if (choice == 4) {
                Ship ds = new Ship("Destroyer", 3, false);
                fleet.add(ds);
                count++;
                System.out.println("Destroyer has been added to fleet.");
            } else if (choice == 5) {
                Ship sp = new Ship("Patrol Boat", 2, false);
                fleet.add(sp);
                count++;
                System.out.println("Patrol boat has been added to fleet.");
            }
        } else {
            System.out.println("Not an option.");
        }
        System.out.println("\nYour fleet now contains:");
        for (Ship s : fleet) {
            System.out.println(s);
        }
        return fleet;
    }


}


public class TCPServer extends BattleshipGame {

    private static final int playerNo = 1;

    public static void main(String[] args) {

        System.out.println("You are player: " + playerNo);
        battleship = new BattleshipGame();
        try {
            InetAddress.getLocalHost().getHostAddress();
            ServerSocket serverSocket = new ServerSocket(6780);
            Socket socket = serverSocket.accept();
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(System.in));
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
            Scanner scan = new Scanner(System.in);
            while (true) {
                if (inFromServer.ready()) {
                    setup(scan, playerNo);
                    System.out.println("\nInput coordinate");
                    int x = scan.nextInt();
                    int y = scan.nextInt();
                    System.out.println(dropBomb(x, y, clientGrid));
                    System.out.println(printBoard(clientGrid));
                    dropBomb(x, y, clientDamage);
                    outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
                    printBoard(clientDamage);
                }
                if (inFromClient.ready()) {
                    System.out.println(inFromClient.readLine());
                    System.out.println(printBoard(serverGrid));
                }
            }
            // socket.close();
            // serverSocet.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void setup(Scanner inFromUser, int playerNo) {
        fleet = new ArrayList<Ship>();
        while (count < numberOfShips) {
            createFleet(fleet, inFromUser.nextInt());
        }
        battleship.initializeGrid(playerNo);
        for (int i = 0; i < fleet.size(); i++) {
            System.out.println(fleet.get(i));
            System.out.println("Define direction (V/H) plus coordinates");
            deployShip(serverGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
        }
        System.out.println("Placements:\n" + printBoard(serverGrid));
        System.out.println("Fleet has been deployed. Press enter to continue.\n");
    }

}


public class TCPClient extends BattleshipGame {

    private static final int playerNo = 2;

    public static void main(String[] args) {
        System.out.println("You are player: " + playerNo);
        battleship = new BattleshipGame();
        try {
            InetAddress.getLocalHost().getHostAddress();
            Socket socket = new Socket(InetAddress.getLocalHost()
                    .getHostAddress(), 6780);
            DataOutputStream dataOutputStream = new DataOutputStream(
                    socket.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(System.in));
            Scanner scan = new Scanner(System.in);
            setup(scan, playerNo);
            while (true) {
                if (inFromClient.ready()) {
                    System.out.println("\nInput coordinate");
                    int x = scan.nextInt();
                    int y = scan.nextInt();
                    System.out.println(dropBomb(x, y, serverGrid));
                    dropBomb(x, y, serverDamage);
                    dataOutputStream.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
                    System.out.println(printBoard(serverDamage));
                }
                if (inFromServer.ready()) { // modtag data fra server
                    System.out.println(inFromServer.readLine());
                    System.out.println(printBoard(clientGrid));
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void setup(Scanner inFromUser, int playerNo) {
        fleet = new ArrayList<Ship>();
        while (count < numberOfShips) {
            createFleet(fleet, inFromUser.nextInt());
        }
        battleship.initializeGrid(playerNo);
        for (int i = 0; i < fleet.size(); i++) {
            System.out.println(fleet.get(i));
            System.out.println("Define direction (V/H) plus coordinates");
            deployShip(clientGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
        }
        System.out.println("Placements:\n" + printBoard(clientGrid));
        System.out.println("Fleet has been deployed. Press enter to continue.\n");
    }
}

包裹战舰;

public class Ship {

    private String name;
    private int size;
    private boolean isDestroyed;

    public Ship(String n, int s, boolean d) {

        this.name = n;
        this.size = s;
        this.isDestroyed = d;
    }

    public String getName() {
        String output = "";
        output = "[" + name + "]";
        return output;

    }

    public int getSize() {
        return size;
    }

    public String toString() {
        String output = "";
        output = "[" + name + ", " + size + ", " + isDestroyed + "]";
        return output;

    }

}

0 个答案:

没有答案