删除,添加和使用列表

时间:2015-08-24 02:59:04

标签: java arrays

我试图为家庭作业创建一个text_game,但是在使用drop和drop命令时遇到了麻烦;

  • 如何创建锁定的门并使用项目(例如钥匙)打开它们

请帮忙。

有两个班 - 游戏和房间;这就是我到目前为止所做的:

游戏

package text_game;

import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;

public class Game {

private Room yard;
private Room frontdoor;
private Room hallway;
private Room bathroom;
private Room lounge;
private Room kitchen;
private Room bedroom;
private Room basementdoor;
private Room basement;
private Room exit;
private Room current;
//create an inventory
private ArrayList<String> inventory = new ArrayList<String>();

public Game() {
    yard = new Room("You're standing in open area.\n"
            + "There is a house to the north.\n");

    frontdoor = new Room("You come to an old timber door, but it's locked.\n"
            + "There's a key on the ground. Talk about security...\n"
            + "There's a yard to the south.\n");
            frontdoor.getItems().add("Front Door Key");

    hallway = new Room("A hall stretches out into darkness.\n"
            + "There is a small flicker of light to the North.\n"
            + "There's a faint dripping sound to the west"
            + "There's a strange smell comming from the east");

    bathroom = new Room("You enter what looks like a bathroom. It doesn't look like anyones cleaned it it months.\n"
            + "There's four numbers scratched into the wall - '1517'.\n"
            + "The hall is to the east.");

    kitchen = new Room("You come into a kitchen, there's moldy food still in grocery bags on the bench.\n"
            + "You see a sandwhich and pick it up to investigate. Fortunately it looks fresh, and you're pretty hungry.\n"
            + "The hall is back to the west.");
            kitchen.getItems().add("Mouldy Sandwhich?");

    lounge = new Room("You come to a dimly lit loungeroom.\n"
            + "The couches have been toppled over, a book case lies fallen on the floor. The embers are still hot and flickering in the fireplace.\n"
            + "There's a door on the western wall.");

    bedroom = new Room("You walk into a bedroom.\n"
            + "There's snoring comming from a huddled lump on the bed. Better be quiet.\n"
            + "There's a large metal door on the southern wall");

    basementdoor = new Room("There's no breaking through this thing, it's too solid.\n"
            + "There's a small keypad next to the door. Hmm?\n");

    basement = new Room("The code unlocks the door. You climb down a dimly lit staircase into what looks like a basement.\n"
            + "Suddenly, you hear some yelling from upstairs and some footsteps making their way down the staircase!\n"
            + "There's a window to north, quick!\n");

    exit = new Room("You crawl through the window, out into the open and run down the street.\n"
            + "Why did you even go into that house in first place?\n");

    current = yard;

    //Connect the rooms
    yard.connectNorth(frontdoor);
    frontdoor.connectNorth(hallway);
    hallway.connectNorth(lounge);
    hallway.connectWest(bathroom);
    kitchen.connectWest(hallway);
    lounge.connectWest(bedroom);
    basementdoor.connectNorth(bedroom);
    basement.connectNorth(basementdoor);
    basement.connectNorth(exit);
}

/**
 * Play the interactive text game.
 *
 * Reads commands from the given input, line by line.
 *
 * @param in
 */

private void take(String item) {
    if (current.getItems().contains(item)== true) {
        Room.al.items().remove(item); // can't get this to work
        inventory.add(item);
        System.out.println("You picked up the " + item + "and stashed it away");
    } else {
        System.out.println("Unknown object '" + item + "'.");
    }
}

private void drop(String item) {
    if (current.getItems().contains(item) == true) {
        inventory.remove(item);
        Room.al.items().add(item); // or this
        System.out.println("You dropped the " + item + "and left it in the " + current);
    } else {
        System.out.println("Unknown object '" + item + "'.");
    }
}

public void play(Scanner in) {
    current.describe();
    while (current != exit) {
        String line = in.nextLine().toLowerCase();
        if (line.equals("quit")) {
            System.out.println("You gave up!");
            break;
        } else if (line.startsWith("go ")) {
            current = current.move(line.substring(3));
            current.describe();
        } else if (line.startsWith("take ")) {
            take(line.substring(5));
        } else if (line.startsWith("print inventory")) {
            System.out.print(inventory);
        } else {
            System.out.println("Unknown command '" + line + "'.  Try go/take/quit.");
        }
    }
}

/** Starts the whole game. */
public static void main(String[] args) {
    Game game = new Game();
    game.play(new Scanner(System.in));
}

}

package text_game;

import java.util.List;
import java.util.ArrayList;

/**
 *
 * @author
 *
 */

public class Room {
private String description;
private Room north;
private Room east;
private Room south;
private Room west;
//add a list of empty items to each room
private ArrayList<String> items = new ArrayList<>();

private String key; //null means no key

public Room(String desc) {
    description = desc;
}

/**
 * Connect the west exit of this room to the 'other' room.
 * It automatically makes the connection in both directions.
 *
 * @param other
 */
public void connectWest(Room other) {
    this.west = other;
    other.east = this;
}

public void connectNorth(Room other) {
    this.north = other;
    other.south = this;
}

/**
 * Prints a description of this room and its contents.
 */
public void describe() {
    final StringBuilder itemsString = new StringBuilder("");
    for (String item : items) {
        itemsString.append(" ").append(item);
    }
    System.out.println(itemsString.toString());
    System.out.println(description);
}

public List<String> getItems() {
    return(items);
}

/**
 * Try to move in the given direction from this room.
 *
 * @param dir Should be "north", "east", "south" or "west".
 * @return the new room.
 */
public Room move(String dir, ArrayList<String> inventory) {
    Room nextRoom = null;

    if (dir.equals("north") && current.equals("frontdoor") { // i don't know what i'm doing or if i'm even in the right class
        if (inventory("Front Door Key") == True) {
            nextRoom 
        }
    }

    if (dir.equals("north")) {
        nextRoom = north;
    } else if (dir.equals("east")) {
        nextRoom = east;
    } else if (dir.equals("south")) {
        nextRoom = south;
    } else if (dir.equals("west")) {
        nextRoom = west;
    } else {
        System.out.println("Error: unknown direction " + dir);
    }
    if (nextRoom == null) {
        System.out.println("You cannot go " + dir + " from here.");
        nextRoom = this; // stay in this room
    } else {
        // TODO: check to see if a 'key' is required to enter nextRoom?
    }
    return nextRoom;
}
}

3 个答案:

答案 0 :(得分:3)

Room.al.items().remove(item);没有意义,因为Room没有static字段al ...或方法{{1} }

相反,我认为您要使用items(),但就个人而言,我会在您的current.getItems()中添加addItemremoveItem方法,以便更轻松使用。

我也摆脱了Room方法,没有人需要直接访问它,相反,getItems应该管理与Room {{1}的互动}}

items

你的List也应该更加愚蠢,也就是说,当你想要移动时,private void take(String item) { if (current.contains(item) == true) { current.removeItem(item); // can't get this to work inventory.add(item); System.out.println("You picked up the " + item + "and stashed it away"); } else { System.out.println("Unknown object '" + item + "'."); } } private void drop(String item) { if (current.contains(item) == true) { inventory.remove(item); current.addItem(item); // or this System.out.println("You dropped the " + item + "and left it in the " + current); } else { System.out.println("Unknown object '" + item + "'."); } } 应该只是按照你想要移动的方向返回房间然后让Room 1}}做出如何处理它的决定。

您还应该能够确定Room是否已被锁定,这样可以更轻松地进行编码

Game

现在,当您移动时,您会向当前Room询问要移动的方向的房间,如果它是public class Room { //... public boolean isLocked() { return key != null; } public String requiredKey() { return key; } /** * Try to move in the given direction from this room. * * @param dir Should be "north", "east", "south" or "west". * @return the new room. */ public Room getNextRoom(String dir) { Room nextRoom = null; if (dir.equals("north")) { nextRoom = north; } else if (dir.equals("east")) { nextRoom = east; } else if (dir.equals("south")) { nextRoom = south; } else if (dir.equals("west")) { nextRoom = west; } else { System.out.println("Error: unknown direction " + dir); } return nextRoom; } public boolean contains(String item) { return items.contains(item); } public void addItem(String item) { items.add(item); } public void removeItem(String item) { items.remove(item); } } ,则您无法移动方向,然后检查房间是否被锁定以及用户是否具有解锁所需的钥匙,如果是,请移至该房间。如果房间被锁定且他们没有钥匙,则显示错误消息,否则,移至下一个房间

Room

我在代码中添加的另一件事是能够为给定的

设置所需的密钥

可运行代码......

null

答案 1 :(得分:1)

对于take方法,为了从当前房间中正确删除项目,我想你想要:

current.getItems().remove(item);

然后在drop方法中:

current.getItems().add(item);

答案 2 :(得分:0)

有助于你的东西是java文档,在本例中是List。 https://docs.oracle.com/javase/8/docs/api/java/util/List.html

有两种方法可以帮助您:

boolean contains(Object)
boolean remove(Object)

我个人会考虑使用Set,除非这需要使用List。 通常,您也会将初始化编写为:

List<String> inventory = new HashList<String>();

其中inventory只是一个List,而不是List接口的一些具体实现。如果您将所有内容硬编码为ArrayList,那么将具体实现更改为LinkedList或其他类型的List将会更加困难。