尝试从文件中将描述实现到游戏中

时间:2015-12-12 16:07:27

标签: java arrays filereader

主要

public class AdventureGameMain {

    public static void main(String[] args) {
        AdventureGame game = new AdventureGame();
        game.play();
    }

}

AdventureGame类

import java.util.Scanner;

public class AdventureGame {

    public void play() {

        Scanner kb = new Scanner(System.in);
        RoomMap map = new RoomMap();
        map.initialize();
        map.roomConnections();
        map.setCurrentRoom();
        map.getCurrentRoom();

        while (!map.hasWon()) {
            System.out.println("What would you like to do?");
            String input = kb.nextLine();
            map.mapMovement(input);
            map.getCurrentRoom().itemStuff(input);

            if (input.equalsIgnoreCase("quit") || input.equalsIgnoreCase("exit")) {
                System.out.println("Exiting Game.");
                map.quit();
            }
            if (input.equalsIgnoreCase("help") || input.equalsIgnoreCase("commands")
                    || input.equalsIgnoreCase("inputs")) {
                System.out.println("You may type north, south, east, or west to move from room to room.");
                System.out.println("You may type pick up or put down to pick up and put down items respectively.");
                System.out.println("You may type inventory to look at the items you currently hold.");
                System.out.println("Your goal is to get all 5 items into the box in the first room.");
                System.out.println("To place an item in the box, you may type place or put item");
                System.out.println("You may type quit or exit to quit the game.");
            }
            if (input.equalsIgnoreCase("get room")) {
                System.out.println("The room you are currently in is: " + map.getCurrentRoom().getRoomNum());
                System.out.println(
                        "The room to the north is: " + map.getCurrentRoom().getRoomDirections().get(0).getRoomNum());
                System.out.println(
                        "The room to the south is: " + map.getCurrentRoom().getRoomDirections().get(1).getRoomNum());
                System.out.println(
                        "The room to the east is: " + map.getCurrentRoom().getRoomDirections().get(2).getRoomNum());
                System.out.println(
                        "The room to the west is: " + map.getCurrentRoom().getRoomDirections().get(3).getRoomNum());
            }
        }
        map.getScoreCount();
        if (map.getScoreCount() > 15) {
            System.out.println("Congratulations, you won! Next time, try and get a lower score!");
        } else {
            System.out.println("You won, and you got the lowest score possible. You're a true hero!");
        }
        kb.close();
    }
}

房间等级

import java.util.ArrayList;

public class Room {
    private static int staticID = 1;
    private int roomNum;

    ArrayList<Room> roomDirections = new ArrayList<Room>();
    ArrayList<String> roomItem = new ArrayList<String>();
    static ArrayList<String> inventory = new ArrayList<String>();
    ArrayList<String> winBox = new ArrayList<String>();

    public Room() {
        roomNum = staticID;
        staticID++;
        switch (roomNum) {
        case 2:
            roomItem.add("Eye of Newt");
            break;
        case 4:
            roomItem.add("Lizard Leg");
            break;
        case 7:
            roomItem.add("Frog Toe");
            break;
        case 8:
            roomItem.add("Owl Wing");
            break;
        case 10:
            roomItem.add("Cat Hair");
            break;
        default:

        }
    }

    public void setRoomDirections(Room north, Room south, Room east, Room west) {
        roomDirections.add(north);
        roomDirections.add(south);
        roomDirections.add(east);
        roomDirections.add(west);

    }

    public void itemStuff(String input) {
        if (input.equalsIgnoreCase("pick up")) {
            if (!roomItem.isEmpty()) {
                System.out.println("You pick up a " + pickUpItem() + " and put it in your bag.");
            } else {
                System.out.println("There is nothing to pick up.");
            }
        }
        if (input.equalsIgnoreCase("drop") || input.equalsIgnoreCase("put down")) {
            if (!inventory.isEmpty()) {
                System.out.println("You take the " + dropItem() + " and put it on the ground.");
            } else {
                System.out.println("There is nothing for you to drop.");
            }

        }
        if (input.equalsIgnoreCase("put item") || input.equalsIgnoreCase("place")
                || input.equalsIgnoreCase("put in box")) {
            if (!inventory.isEmpty()) {
                System.out.println("You remove the " + putItemInBox() + " from your inventory.");
                System.out.println("You put the item in the box.");
            } else {
                System.out.println("You don't have anything to put in the box.");
            }
        }
    }

    public boolean canGoNorth() {
        if (roomDirections.get(0).getRoomNum() == 11) {
            return false;
        } else {
            return true;
        }
    }

    public boolean canGoSouth() {
        if (roomDirections.get(1).getRoomNum() == 11) {
            return false;
        } else {
            return true;
        }
    }

    public boolean canGoEast() {
        if (roomDirections.get(2).getRoomNum() == 11) {
            return false;
        } else {
            return true;
        }
    }

    public boolean canGoWest() {
        if (roomDirections.get(3).getRoomNum() == 11) {
            return false;
        } else {
            return true;
        }
    }

    public Room getRoomNorth() {
        return roomDirections.get(0);
    }

    public Room getRoomSouth() {
        return roomDirections.get(1);
    }

    public Room getRoomEast() {
        return roomDirections.get(2);
    }

    public Room getRoomWest() {
        return roomDirections.get(3);
    }

    public int getRoomNum() {
        return roomNum;
    }

    public ArrayList<Room> getRoomDirections() {
        return roomDirections;
    }

    public String getCurrentItem() {
        return roomItem.get(0);
    }

    public String getInventory() {
        return inventory.get(0);
    }
    public int getWinBoxSize() {
        return winBox.size();
    }

    public String pickUpItem() {
        inventory.add(roomItem.get(0));
        return roomItem.remove(0);
    }

    public String dropItem() {
        roomItem.add(inventory.get(0));
        return inventory.remove(0);
    }

    public String putItemInBox() {
        winBox.add(inventory.get(0));
        return inventory.remove(0);
    }
}

地图类

import java.util.ArrayList;

public class RoomMap {

    private Room currentRoom;
    private int scoreCount;

    public void initialize() {
        for (int i = 0; i < 11; i++) {
            Room room = new Room();
            roomList.add(room);
        }
    }

    ArrayList<Room> roomList = new ArrayList<Room>();

    public void roomConnections() {

        Room room1 = roomList.get(0);
        Room room2 = roomList.get(1);
        Room room3 = roomList.get(2);
        Room room4 = roomList.get(3);
        Room room5 = roomList.get(4);
        Room room6 = roomList.get(5);
        Room room7 = roomList.get(6);
        Room room8 = roomList.get(7);
        Room room9 = roomList.get(8);
        Room room10 = roomList.get(9);

        // 0, 1, 2, 3 || North, South, East, West
        room1.setRoomDirections(roomList.get(2), roomList.get(7), roomList.get(5), roomList.get(4));
        room2.setRoomDirections(roomList.get(10), roomList.get(1), roomList.get(2), roomList.get(1));
        room3.setRoomDirections(roomList.get(10), roomList.get(0), roomList.get(3), roomList.get(1));
        room4.setRoomDirections(roomList.get(2), roomList.get(7), roomList.get(6), roomList.get(4));
        room5.setRoomDirections(roomList.get(10), roomList.get(10), roomList.get(0), roomList.get(6));
        room6.setRoomDirections(roomList.get(3), roomList.get(7), roomList.get(8), roomList.get(0));
        room7.setRoomDirections(roomList.get(1), roomList.get(10), roomList.get(10), roomList.get(4));
        room8.setRoomDirections(roomList.get(10), roomList.get(10), roomList.get(5), roomList.get(10));
        room9.setRoomDirections(roomList.get(5), roomList.get(10), roomList.get(10), roomList.get(9));
        room10.setRoomDirections(roomList.get(10), roomList.get(8), roomList.get(10), roomList.get(10));
    }

    public boolean hasWon() {
        if (currentRoom.getWinBoxSize() < 5) {
            return false;
        } else {
            return true;
        }
    }

    public void mapMovement(String input) {
        if (input.equalsIgnoreCase("north") || input.equalsIgnoreCase("go north")
                || input.equalsIgnoreCase("move north") || input.equalsIgnoreCase("n")) {
            if (currentRoom.canGoNorth()) {
                currentRoom = currentRoom.getRoomNorth();
                System.out.println("Tick...");
                scoreCount++;
                System.out.println("You move north.");
                System.out.println("You are now in room number " + currentRoom.getRoomNum() + ".");
            } else {
                System.out.println("There is no room in that direction.");
            }
        }
        if (input.equalsIgnoreCase("south") || input.equalsIgnoreCase("go south")
                || input.equalsIgnoreCase("move south") || input.equalsIgnoreCase("s")) {
            if (currentRoom.canGoSouth()) {
                currentRoom = currentRoom.getRoomSouth();
                System.out.println("Tick...");
                scoreCount++;
                System.out.println("You move south.");
                System.out.println("You are now in room number " + currentRoom.getRoomNum() + ".");
            } else {
                System.out.println("There is no room in that direction.");
            }
        }
        if (input.equalsIgnoreCase("east") || input.equalsIgnoreCase("go east") || input.equalsIgnoreCase("move east")
                || input.equalsIgnoreCase("e")) {
            if (currentRoom.canGoEast()) {
                currentRoom = currentRoom.getRoomEast();
                System.out.println("Tick...");
                scoreCount++;
                System.out.println("You move east.");
                System.out.println("You are now in room number " + currentRoom.getRoomNum() + ".");
            } else {
                System.out.println("There is no room in that direction.");
            }
        }
        if (input.equalsIgnoreCase("west") || input.equalsIgnoreCase("go west") || input.equalsIgnoreCase("move west")
                || input.equalsIgnoreCase("w")) {
            if (currentRoom.canGoWest()) {
                currentRoom = currentRoom.getRoomWest();
                System.out.println("Tick...");
                scoreCount++;
                System.out.println("You move west.");
                System.out.println("You are now in room number " + currentRoom.getRoomNum() + ".");
            } else {
                System.out.println("There is no room in that direction.");
            }
        }
        if (input.equalsIgnoreCase("score")) {
            System.out.println("You currently have " + scoreCount + " points. Try and go for a low score.");
        }
    }

    public Room getCurrentRoom() {
        return currentRoom;
    }

    public int getScoreCount() {
        return scoreCount;
    }

    public void setCurrentRoom() {
        currentRoom = roomList.get(0);
        System.out.println("You are now in room number " + currentRoom.getRoomNum() + ".");
    }

    public void quit() {
        System.exit(0);
    }

}

FileReader类

import java.io.*;
import java.util.Scanner;

public class FileReader {

    String[] descriptions;

    public Scanner openFile(String filename) {
        try {
            File file = new File(filename);
            descriptions = filename.split("--");
            return new Scanner(file);
        } catch (FileNotFoundException e) {
            System.out.println("That is not a valid file name.");
        }
        return null;
    }
}

我需要从

中读取文本文件
You are in a dark cave. In the middle, there is a cauldron boiling.
With a clasp of thunder, three witches suddenly appear before you.
Room 1 (always)
--
The witches speak in unison:
 "Mortal, we have summoned thee, make haste!
 And go forth into the farrow'd waste.
 Find eye of newt, and toe of frog,
 And deliver thus to this Scottish bog.
 Lizard 's leg, and owlet's wing,
 And hair of cat that used to sing.
 These things we need t' brew our charm;
 Bring them forth -and suffer no 'arm.
 Leave us and go!
 'Tis no more to be said,
 Save if you fail, then thou be stricken, dead."
 Room 1 (first)
--
The witches stand before you, glaring; they seem to be expecting
something from you.
Room 1 (after)
--
The witches look at your items with suspicion, but decide to go
through with the incantation of the spell:
 "Take lizard's leg and owlet's wing,
 And hair of cat that used to sing.
 In the cauldron they all shall go;
 Stirring briskly, to and fro.
 When the color is of a hog,
 Add eye of newt and toe of frog.
 Bubble all i' the charmed pot;
 Bubble all 'til good and hot.
 Pour the broth into a cup of stone,
 And stir it well with a mummy's bone."
You take the resulting broth offered to you and drink...
As the fog clears, you find yourself at a computer terminal;
your adventure is at an end.
Room 1 (win)
--
You're transported back in time … you find yourself in Georgia during
the midst of a congressional campaign.
Room 2 (always)
--
There is a campaign poster of Newt Gingrich, the Speaker of the House
of Representatives, on the wall, with his large eyes looking right at
you.
Room 2 (before item)
--
There is a defaced poster of Newt Gingrich on the wall.
Room 2 (after item)
--
You enter a room and you are blinded as soon as you enter, a flash of holy light shining
down from the ceiling, seemingly pointing towards an object of importance.
Room 3 (always)
--
Upon further inspection, there is literally nothing in the room.
Room 3 (first)
--
Still nothing here.
Room 3 (after)
--
You walked through the door way and there is what seems to be a sign for a shopping complex, 
a shopping clerk standing at at the entrance and welcoming you in. You make your way inside.
Room 4 (always)
--
There is a woman at a small makeshift stall with a single
giant chocolate covered lizard leg with a sign next to it
that says free sample. She seems to be eyeing you excitedly.
The woman begins to call you over, asking if you would like 
to take the giant chocolate covered lizard leg away from her. 
She seems desperate.

Room 4 (before item)
--
With the leg gone, you find that the stall has been destroyed and all that is left is,
a single, leg-less lizard crying on the ground.

Room 4 (after item)
--
When stepping into the hall to enter the room, a gust of wind pushes you forward,
forcing you into a room with a small, seemingly self sustaining tornado.
Room 5 (always)
--
You attempt to see if there is anything of importance within the tornado,
but all you find is some hot dogs, some papers covered in things from quantum
physics, and a small, white, very annoying dog.
Room 5 (first)
--
While you were gone, the dog started a game of poker... with itself. It seems to be losing.
Room 5 (after)
--
Nothing special about this room. Just a room. A very roomy room. Full of room.
Room 6 (always)
--
You find yourself walking into a scene where the cast of Monty
Python's Flying Circus is performing the "Crunchy Frog" sketch. You
see the confectioner as he replies, "If we took the bones out it
wouldn't be crunchy now, would it?" You're a bit creeped out.
Room 7 (always)
--
You see a box of "Crunchy Frog" chocolates, the contents of which 
contains a single nicely cleaned frog toe that has been carefully 
hand-dipped in the finest chocolate.
Room 7 (before item)
--
With the chocolate frog toe now gone, the entirety of the circus
collapses in on itself, you being the only one to survive the
desctruction, it seems.
Room 7 (after item)
--
You walk into a strangely dark room, a spotlight shining down on something particular
in the center of the room. You feel as if this time there will actually be something there.
Room 8 (always)
--
There is an owl plush sitting on a table next to a pair of scissors.
The owl's right wing is extended with a definite sort of 'cut here' line
across the base of the wing. 
Room 8 (before item)
--
There is a scream echoing across the room, blood dripping from the owl plush's
vacant wing socket. What have you done?
Room 8 (after item)
--
As you step through the time portal, your head begins to spin you're
disoriented and then awaken. You find yourself at the outside door of
a dormitory kitchen.
Room 9 (always)
--
There is a group of strange looking cats wearing crowns and standing on their
hind legs, all screaming and banging on the kitchen back door to be let in. 
The kitchen's head chef is seething with anger, tightly gripping his
cleaver.

Room 9 (before item)
--
Upon returning to the kitchen, the meowing had stopped. You knew why.
You had asked the chef to kill those cats for you so you could have a tuft
of their hair. You monster.

Room 9 (after item)
--
The final room. Though you know this doesn't signal the end of your journey, you feel accomplished to have made it this far. 
The wind is blowing through your hair, and the room carries a sense of power with it.

Room 10 (always)
--
After venturing deeper into the room, you find a very large treasure chest in the center. It flings itself open and
reveals itself to be a mimic, attacking you and taking a chunk out of your left leg. This doesn't do anything
because the programmer hasn't coded battling into this game, so it is just a minor annoyance.

Room 10 (first)
--
You're still more than just a little peeved at that whole mimic thing.

Room 10 (after)
--

我目前正在尝试在java中制作游戏,只是为了它的乐趣和编码的额外体验,我遇到了一个问题。基本上,descriptions.txt文件应该适用于我在游戏中的所有描述。我没有对它们进行硬编码,而是希望从该文件中读取它们,将它们拆分为--并将它们添加到数组中(这是我在java类中的朋友给我的所有建议)。

事情是,我不知道如何去做所有这些。我知道我需要一个文件阅读器,通过stringSplit函数和--将文档分成多个字符串,但我不知道如何将它们添加到数组中,然后如何实际引用它们稍后在游戏中。

我可以获得的任何帮助都非常有用,并且非常感谢和希望获得有关清理我的代码的任何其他帮助。

1 个答案:

答案 0 :(得分:1)

示例代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Based on your request and keeping this dead simple this an example of reading
 * a description file using CSV  (comman delimited)
 *
 * Contents of the description.txt (in this example its in the same path)
 *
 *    Game 1, Description 1
 *    Game 2, Description 2
 *    Game 3, Description 3
 *    ....
 *    Game N, Description N
 *
 * You may want to investigate storage in a XML file or JSON file or use of database
 *
 */
 public class TestReader {

   public static void main(String[] args) {
     try {
        System.out.println("File CSV Reader Test, you should see outpout of the contents in description.txt:");

        Scanner scan = new Scanner(new File("description.txt"));
        while(scan.hasNextLine()){
          String line = scan.nextLine();

          // For testing, output to console each line
          System.out.println(line);

          // At this point you can do whatever with the line
          // Store it into a data object and added to a collection     like an ArrayList, 2d array...etc

         // Split the comma delimited string into individual values into an array
         // String[] lineValues = line.split(",");

      }

    } catch (Exception e){
      System.out.println(e.getMessage());
    }
  }
 }

控制台输出:

File CSV Reader Test, you should see outpout of the contents in description.txt:
Game 1,Game 1 Description
Game 2,Game 2 Description
Game 3,Game 3 Description