Смена номера не обновляет текущую комнату, она просто остается в той же комнате - PullRequest
0 голосов
/ 28 сентября 2019

Я прошу прощения за лишний код, но я полностью потерян, где моя проблема.У меня есть четыре класса, и у меня должна быть программа, которая играет в игру «Лабиринт старой школы».Вы начинаете в комнате, и вы должны иметь возможность перемещать комнаты, пока не доберетесь до комнаты с Граалем.Итак, в программе класс контроллера создает комнаты.Это берет в строке специфику комнаты.Я могу подтвердить, что строка правильно проанализирована.Моя проблема в том, что соседние комнаты, кажется, не устанавливаются.Я чувствую, что комнаты хранятся в классе игрока, но когда я пытаюсь получить доступ к соседним комнатам, все они устанавливаются в 0.

Room.java

public class Room {

    public static int DIRECTONS = 4;
    public static int NORTH = 0; 
    public static int EAST = 1;
    public static int SOUTH = 2;
    public static int WEST = 3;
    private boolean hasGrail;
    private String description;
    private Room adjacentRoom;
    private static Room[] roomNeighbors = new Room[4];

    public Room() {
        description = "";
        hasGrail = false;
    }

    public Room(String description) {
        this.description = description;
    }   

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setAdjacent(int direction, Room adjacentRoom) {
        this.adjacentRoom = adjacentRoom;
        roomNeighbors[direction] = adjacentRoom;        
    }

    public Room getAdjacent(int direction) {
        return roomNeighbors[direction];
    }

    public boolean hasGrail() {
        return hasGrail;
    }

    public void putGrail() {
        hasGrail = true;
    }

    public String toString() {
     String topbottom = "+-------------------+";
     String floor = "%n|                   |";
     String floorEastExit = "%n|                   _";
     String floorWestExit = "%n_                   |";
     String floorWestAndEastExit = "%n_                   _";
     String topbottomWithExit = "%n+--------- ---------+";
     String top, bottom, side = "";

     if (getAdjacent(0) == null)
         top = topbottom;
     else 
         top = topbottomWithExit;
     if (!(getAdjacent(1) == null) && !(getAdjacent(3) == null)) 
         side = floorWestAndEastExit;
     else if (!(getAdjacent(1)== null))
         side = floorEastExit;
     else if (!(getAdjacent(3)== null))
         side = floorWestExit;
     if (getAdjacent(2) == null)
         bottom = "%n" + topbottom;
     else 
         bottom = "%n" + topbottomWithExit; 
     if (hasGrail)
        bottom = bottom + "%n" + "The grail";

        return String.format(top + floor + floor + side + floor + floor + bottom);
    }

}

Controller.java

import java.util.Scanner;
public class Controller {
    int numberOfRooms;
    Room[] gameRooms;
    public Controller() {
        numberOfRooms = 0;
    }

    public Controller(int numberOfRooms) {
        this.numberOfRooms = numberOfRooms;
        gameRooms =  new Room[numberOfRooms];
        for (int x= 0; x < numberOfRooms; x++)
            gameRooms[x] = new Room();
    }

    public void buildRoom(int roomNumber, String fullDesc) {
        String description;

        description = fullDesc.substring(1, fullDesc.indexOf("| "));
        gameRooms[roomNumber] = new Room(description);
        fullDesc = fullDesc.substring(fullDesc.indexOf("| ") + 2);

        if (fullDesc.contains("true")) 
            gameRooms[roomNumber].putGrail();
        fullDesc = fullDesc.substring(fullDesc.indexOf(" "));       
        String[] roomString = fullDesc.split(" ");
        Integer[] adjRoomNum = new Integer[roomString.length];
        for (int i = 1; i < roomString.length; i++) {
            //roomString[i].replaceAll("\\s+", "");
            adjRoomNum[i - 1] = Integer.parseInt(roomString[i]);
            //System.out.println(adjRoomNum[i - 1] + " " + i);
            //System.out.println((roomString[i]));
        }


        if (adjRoomNum[0] >= 0)
            gameRooms[roomNumber].setAdjacent(0, gameRooms[Integer.valueOf(adjRoomNum[0])]);
        else if (adjRoomNum[0] == -1)
            gameRooms[roomNumber].setAdjacent(0, null);
        if (adjRoomNum[1] >= 0)
            gameRooms[roomNumber].setAdjacent(1, gameRooms[Integer.valueOf(adjRoomNum[1])]);
        else if (adjRoomNum[1] == -1)
            gameRooms[roomNumber].setAdjacent(1, null);
        if (adjRoomNum[2] >= 0)
            gameRooms[roomNumber].setAdjacent(2, gameRooms[Integer.valueOf(adjRoomNum[2])]);
        else if (adjRoomNum[2] == -1)
            gameRooms[roomNumber].setAdjacent(2, null);
        if (adjRoomNum[3] >= 0)
            gameRooms[roomNumber].setAdjacent(3, gameRooms[Integer.valueOf(adjRoomNum[3])]);
        else if (adjRoomNum[3] == -1)
            gameRooms[roomNumber].setAdjacent(3, null);
        System.out.println(roomNumber);
    }

    public Room getStartRoom() {
        int startRoom;
        do {
            startRoom = ((int)(Math.random()) % 4) + 1;
        }while(gameRooms[startRoom].hasGrail()==true);
        return gameRooms[startRoom];
    }
}

Game.java

import java.util.Scanner;

public class Game {
    private static Player player;

    private static void commandLoop() {
        Scanner iHateThisProject = new Scanner(System.in);
        String choice;
        String direction;
        do {
            System.out.println(player.getCurrent().getDescription());
            System.out.println(player.toString());
            System.out.print("What is your bidding(h for help)? ");
            choice = iHateThisProject.next(); 
            if ((!choice.equals("h")) && (!choice.equals("l")) && (!choice.equals("g")) && (!choice.equals("q"))){
                    System.out.print("Error, wrong input.");
            }
            if (choice.equals("h")) {
                System.out.println("h(elp) - print this text");
                System.out.println("l(ook) - show current location");
                System.out.println("g(o) direction - go into direction N, E, S, or W");
                System.out.println("q(uit) - exit game");
            }

            if (choice.equals("l"))
                System.out.println(player.getCurrent().getDescription());
            if (choice.equals("q"))
                return;
            if (choice.equals("g")) {
                System.out.print("Please enter the direction(N,E,S,W): ");
                direction = iHateThisProject.next();
                if ((direction == "N") && (player.getCurrent().getAdjacent(0) == null)) 
                    System.out.println("Cannot go this way");
                else if (direction == "N")
                        player.setCurrent(player.getCurrent().getAdjacent(0));
                if ((direction == "E") && (player.getCurrent().getAdjacent(1) == null)) 
                        System.out.println("Cannot go this way");
                else if (direction == "E")
                        player.setCurrent(player.getCurrent().getAdjacent(1));
                if ((direction == "S") && (player.getCurrent().getAdjacent(2) == null)) 
                        System.out.println("Cannot go this way");
                else if (direction == "S")
                        player.setCurrent(player.getCurrent().getAdjacent(2));
                if ((direction == "W") && (player.getCurrent().getAdjacent(3) == null))
                        System.out.println("Cannot go this way");
                else if (direction == "W")
                        player.setCurrent(player.getCurrent().getAdjacent(3));
            }
        }while (!(player.getCurrent().hasGrail()));
    iHateThisProject.close();
    }

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        String thisName;
        // Dungeon: 4 rooms (0 through 3)
        String[] rooms = {
                "|You're in a large dark room| false 1 -1 -1 2 ", 
                "|You're in a dark large room| false -1 0 -1 -1 ",
                "|You're in a large room, very dark| false 0 0 3 0 ",
                "|You're in a dark room, very small| true 0 0 0 0 "
        };

        // Set the dungeon up according to the input
        Controller c = new Controller(rooms.length);
        for (int i = 0; i < rooms.length; i++) {
            c.buildRoom(i, rooms[i]);
        }
        System.out.print("Please enter your name: ");
        thisName = scnr.next();
        // Create and position player
        player = new Player(thisName);
        player.setCurrent(c.getStartRoom());

        System.out.println(player.getCurrent().getAdjacent(0).getDescription());
        System.out.println(player.getCurrent().getAdjacent(1).getDescription());
        System.out.println(player.getCurrent().getAdjacent(2).getDescription());
        System.out.println(player.getCurrent().getAdjacent(3).getDescription());

        // Print room description and off you go!
        System.out.println(player.getCurrent().getDescription());
        commandLoop();
    }
}

Player.java


public class Player {
    private String name;
    private Room currentRoom;

    public Player() {
        name = "";
    }

    public Player(String name){
        this.name = name;
    }

    public Room getCurrent() {
        return currentRoom;
    }

    public void setCurrent(Room room){
        this.currentRoom = room;
    }

    public String getname() {
        return name;
    }

    public String toString() {
        return currentRoom.toString();
    }
}

токовый выход

Please enter your name: asfads
0
1
2
3
You're in a large dark room
You're in a large dark room
You're in a large dark room
You're in a large dark room
You're in a dark large room
You're in a dark large room

+--------- ---------+
|                   |
|                   |
_                   _
|                   |
|                   |

+--------- ---------+
What is your bidding(h for help)? 
  • 0, 1, 2, 3 - это проверка, которую я провел, чтобы убедиться, что класс контроллера перебирает 4 разных комнаты.4 утверждения «Ты в большой темной комнате» неверны.Они должны быть описаниями комнат, прилегающих к начальной комнате.Вместо этого 4 описания приходят из комнаты в позиции 0. Ожидаемый код должен напечатать описание соседней комнаты, если она есть.

Линии были напечатаны в основной части класса Game.java.Класс Game.java запускает игру, создавая экземпляр класса контроллера.Когда класс контроллера инициируется, комнаты создаются в классе контроллера.Класс контроллера управляет списком комнат, создавая комнаты.Класс игрока содержит информацию о комнате, в которой находится игрок. Игровой класс контролирует цикл, в котором происходят ходы.

Этот фрагмент находится в самом начале игры.Он инициализирует контроллер, а затем помещает стартовую комнату.Сразу после этого я хотел вызвать соседние комнаты в стартовую, чтобы проверить, существуют ли они.
В моем коде есть случайная стартовая комната.Я попытался установить начальную комнату, чтобы знать, какие есть доступные соседние комнаты.Это не сработало.Независимо от того, что я пытался, каждый раз, когда я пытался войти в соседнюю комнату, я получал одну и ту же комнату.4 числа после истины / ложи указывают доступные комнаты.0-3 представляют Север, Восток, Юг, Запад соответственно.-1 означает, что в этой комнате нет связи.Так, например, первая комната содержит описание «Вы находитесь в большой комнате для милых», и эта комната соединяется с комнатой 1 на севере и с комнатой 2 на юге.Таким образом, мои четыре строки повторяющегося кода являются определением каждой смежной комнаты.Он должен описывать комнату, соединяющуюся с севера, востока, юга и запада.
Кажется, что каждая из смежных комнат возвращается со значением комнаты в позиции 0.

public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        String thisName;
        // Dungeon: 4 rooms (0 through 3)
        String[] rooms = {
                "|You're in a large dark room| false 1 -1 -1 2 ", 
                "|You're in a dark large room| false -1 0 -1 -1 ",
                "|You're in a large room, very dark| false 0 0 3 0 ",
                "|You're in a dark room, very small| true 0 0 0 0 "
        };

        // Set the dungeon up according to the input
        Controller c = new Controller(rooms.length);
        for (int i = 0; i < rooms.length; i++) {
            c.buildRoom(i, rooms[i]);
        }
        System.out.print("Please enter your name: ");
        thisName = scnr.next();
        // Create and position player
        player = new Player(thisName);
        player.setCurrent(c.getStartRoom());

        System.out.println(player.getCurrent().getAdjacent(0).getDescription());
        System.out.println(player.getCurrent().getAdjacent(1).getDescription());
        System.out.println(player.getCurrent().getAdjacent(2).getDescription());
        System.out.println(player.getCurrent().getAdjacent(3).getDescription());
...