ArrayList из ArrayLists переопределяется при установке значений второго - PullRequest
1 голос
/ 25 апреля 2020

Я пытаюсь сделать игру на линкоре, и именно здесь игроки устанавливают свои доски. Когда второй игрок, который устанавливает доску, делает свою, доска первого игрока становится такой же, как и у второго игрока (хотя, играя в игру, можно предположить, что места на этой доске упущены, но это еще одна проблема, которая, надеюсь, будет исправлена, как только это произойдет) , Например, если я установил корабли первого игрока как A1 A2 A3, B1 B2 B3 и C1 C2 C3, то установил корабли второго игрока как D1 D2 D3, E1 E2 E3 и F1 F2 F3, когда оба списка кораблей распечатаны я получаю D1 D2 D3, E1 E2 E3 и F1 F2 F3 для обоих кораблей. Я нашел другие вопросы здесь с той же проблемой, но у них всегда была проблема, потому что они не делали новые списки каждый раз, что я делаю (по крайней мере, я почти уверен, что я делаю), поэтому я не могу найти, где моя проблема. Вот весь основной класс игры, GetShipLocations, SetShipLocations и PlayersMakeTheirBoards, функции, которые доставляют мне проблемы.

import java.util.*;
import java.lang.*;
public class MainGame {
    InputReader read = new InputReader();
    Grid p1Board = new Grid();
    Grid p2Board = new Grid();
    Grid p1ShipsBoard = new Grid();
    Grid p2ShipsBoard = new Grid();
    ArrayList<Ship> p1Ships = new ArrayList<Ship>();
    ArrayList<Ship> p2Ships = new ArrayList<Ship>();
    String activePlayer = "P1";

    public void SetUp() {
        p1Board.PrepPrintGrid();
        p2Board.PrepPrintGrid();
        Ship ship1 = new Ship();
        Ship ship2 = new Ship();
        Ship ship3 = new Ship();
        p1Ships.add(ship1);
        p1Ships.add(ship2);
        p1Ships.add(ship3);
        p2Ships.add(ship1);
        p2Ships.add(ship2);
        p2Ships.add(ship3);
    }
    public void GameIntro() {
        System.out.println("Welcome to battleship!");
        String rulesOption = read.getUserInput("Do you need to see the rules?");
        if(rulesOption.equals("Yes") || rulesOption.equals("yes"))
        {
            System.out.println("Put rules here");
        }
        System.out.println("Randomly determining which player goes first");
        int random = (int) (Math.random() * 2);
        if(random == 1)
        {
            activePlayer = "P2";
        }
        System.out.println(activePlayer + " starts!");
    }
    public ArrayList<ArrayList<String>> GetShipLocations(Grid board) {
        ArrayList<ArrayList<String>> ships = new ArrayList<ArrayList<String>>();
        ArrayList<String> ship1 = new ArrayList<String>();
        ArrayList<String> ship2 = new ArrayList<String>();
        ArrayList<String> ship3 = new ArrayList<String>();
        ships.add(ship1);
        ships.add(ship2);
        ships.add(ship3);
        String[] numbers = {"first", "second", "third"};
        board.PrepPrintGrid();
        board.PrintGrid();
        for(int i = 0; i < 3; i++)
        {
            for(int j = 0; j < 3; j++)
            {
                String coordinate = read.getUserInput("Enter the " + numbers[j] + " coordinate of your " + numbers[i] + " ship (3 long):");
                ships.get(i).add(coordinate);
                board.SetGridDisplay(coordinate, "hit");
                board.PrintGrid();
            }
        }
        return ships;
    }
    public void SetShipLocations(ArrayList<Ship> ship, Grid activeBoard) {
        ArrayList<ArrayList<String>> shipLocations = GetShipLocations(activeBoard);
        for(int i = 0; i < 3; i++) {
            ship.get(i).SetCells(shipLocations.get(i));
        }
    }
    public void PlayersMakeTheirBoards() {
        if(activePlayer.equals("P1")) 
        {
            System.out.println("Hand the computer to player one.");
            System.out.println("Player one, time to set your board.");
            SetShipLocations(p1Ships, p1ShipsBoard);//the effects of this seem to maybe be overriden when the second board is set
            for(int i = 0; i < /*100*/3; i++) 
            {
                for(int j = 0; j < 3; j++)
                {
                    System.out.println(p1Ships.get(i).cells.get(j));
                }

            }
            System.out.println("Hand the computer to player two.");
            System.out.println("Player two, time to set your board.");
            SetShipLocations(p2Ships, p2ShipsBoard);
            for(int i = 0; i < /*100*/3; i++) 
            {
                for(int j = 0; j < 3; j++)
                {
                    System.out.println(p2Ships.get(i).cells.get(j));
                }

            }
            for(int i = 0; i < /*100*/3; i++) 
            {
                for(int j = 0; j < 3; j++)
                {
                    System.out.println(p1Ships.get(i).cells.get(j));
                }

            }
        }
        else
        {
            System.out.println("Hand the computer to player two.");
            System.out.println("Player two, time to set your board.");
            SetShipLocations(p2Ships, p2ShipsBoard);
            /*for(int i = 0; i < 100; i++) 
            {
                System.out.println("");
            }*/
            for(int i = 0; i < /*100*/3; i++) 
            {
                for(int j = 0; j < 3; j++)
                {
                    System.out.println(p2Ships.get(i).cells.get(j));
                }

            }
            System.out.println("Hand the computer to player one.");
            System.out.println("Player one, time to set your board.");
            SetShipLocations(p1Ships, p1ShipsBoard);
            for(int i = 0; i < /*100*/3; i++) 
            {
                for(int j = 0; j < 3; j++)
                {
                    System.out.println(p1Ships.get(i).cells.get(j));
                }

            }
            for(int i = 0; i < /*100*/3; i++) 
            {
                for(int j = 0; j < 3; j++)
                {
                    System.out.println(p2Ships.get(i).cells.get(j));
                }

            }
        }
    }
    public void PlayTheGame() {
        String guess = new String();
        String result = new String();
        for(int i = 0; i < 100; i++) 
            {
                System.out.println("");
            }
        while(!p1Ships.isEmpty() && !p2Ships.isEmpty())
        {
            if(activePlayer.equals("P1"))
            {
            //print the grid
            p1Board.PrintGrid();
            //ask user for their guess
            guess = read.getUserInput("Player one, enter your guess:");
            for(Ship boat:p2Ships)
            {
                result = boat.CheckYourself(guess);
                if(result.equals("hit"))
                {
                    System.out.println(result + "!");
                    break;
                }
                if(result.equals("kill"))
                {
                    System.out.println(result + "!");
                    p2Ships.remove(boat);
                    break;
                }
            }
            if(result.equals("miss"))
            {
                System.out.println(result);
            }
            p1Board.SetGridDisplay(guess, result);
            activePlayer = "P2";
            }
            else
            {
            p2Board.PrintGrid();
            //ask user for their guess
            guess = read.getUserInput("Player two, enter your guess:");
            for(Ship boat:p1Ships)
            {
                result = boat.CheckYourself(guess);
                if(result.equals("hit"))
                {
                    System.out.println(result + "!");
                    break;
                }
                if(result.equals("kill"))
                {
                    System.out.println(result + "!");
                    p1Ships.remove(boat);
                    break;
                }
            }
            if(result.equals("miss"))
            {
                System.out.println(result);
            }
            p2Board.SetGridDisplay(guess, result);
            activePlayer = "P1";
            }
        }
    }
    public void EndTheGame() {
        String winner = new String();
        if(p1Ships.isEmpty()) 
        {
            winner = "Player two";
            p2Board.PrintGrid();
        }
        else
        {
            winner = "Player one";
            p1Board.PrintGrid();
        }
        System.out.println("The game is over!");
        System.out.println(winner + " wins! Congratulations!");
    }
    public static void main(String[] args) {
        MainGame game = new MainGame();
        game.SetUp();
        game.GameIntro();
        game.PlayersMakeTheirBoards();
        game.PlayTheGame();
        game.EndTheGame();
    }
}

, а вот класс Ship

import java.util.*;
public class Ship {
    ArrayList<String> cells = new ArrayList<String>();
    //String name = new String();
    public void SetCells(ArrayList<String> locations) {
        cells = locations;
    }
    /*public void SetName(String word) {
        name = word;
    }*/
    public String CheckYourself(String guess) {
            if(cells.contains(guess)) 
            {
                cells.remove(guess);
                if(cells.isEmpty()) 
                {
                    return "kill";
                }
                else
                {
                    return "hit";
                }
            }
            return "miss";
    }
}

Сетка и читательские классы работают отлично, поэтому я их не включил. (Все это основано на игре линкора dotcom в headfirst java)

1 Ответ

2 голосов
/ 26 апреля 2020

В вашей функции настройки:

public void SetUp() {
        p1Board.PrepPrintGrid();
        p2Board.PrepPrintGrid();
        Ship ship1 = new Ship();
        Ship ship2 = new Ship();
        Ship ship3 = new Ship();
        p1Ships.add(ship1);
        p1Ships.add(ship2);
        p1Ships.add(ship3);
        p2Ships.add(ship1);
        p2Ships.add(ship2);
        p2Ships.add(ship3);
    }

Вы добавляете одинаковые экземпляры ship1-3 для обоих p1Ships и p2Ships. Поэтому, когда вы меняете корабли игрока 2, ArrayList p1Ships по-прежнему указывает на те же корабли, что и p2Ships, и поэтому всегда будет одинаковым.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...