Fixed parser, added items starting in rooms, moved item room storage

This commit is contained in:
jslightham
2019-05-08 11:43:21 -04:00
parent 0c44589f03
commit 7fa30879c0
7 changed files with 711 additions and 626 deletions

View File

@@ -1,9 +1,12 @@
Room Name: Room 1 Room Name: Room 1
Room Description: You are in a stone-walled room, surrounded by Room Description: You are in a stone-walled room, surrounded by
Exit Rooms: E-Room 2 Items:Candlestick,Candlestick
Room Name: Room 2 Exit Rooms: E-Room 2
Room Description: This is Room 2 Room Name: Room 2
Exit Rooms: W-Room 1, U-Room 3 Room Description: This is Room 2
Room Name: Room 3 Items:
Room Description: You are upstairs. You are likely to be eaten by a giant worm! Exit Rooms: W-Room 1, U-Room 3
Exit Rooms: D-Room 2 Room Name: Room 3
Room Description: You are upstairs. You are likely to be eaten by a giant worm!
Items:
Exit Rooms: D-Room 2

View File

@@ -1,87 +1,99 @@
package com.bayviewglen.zork; package com.bayviewglen.zork;
import java.util.ArrayList; import java.util.ArrayList;
/** /**
* Class Command - Part of the "Zork" game. * Class Command - Part of the "Zork" game.
* *
* author: Michael Kolling version: 1.0 date: July 1999 * author: Michael Kolling version: 1.0 date: July 1999
* *
* This class holds information about a command that was issued by the user. A * This class holds information about a command that was issued by the user. A
* command currently consists of two strings: a command word and a second word * command currently consists of two strings: a command word and a second word
* (for example, if the command was "take map", then the two strings obviously * (for example, if the command was "take map", then the two strings obviously
* are "take" and "map"). * are "take" and "map").
* *
* The way this is used is: Commands are already checked for being valid command * The way this is used is: Commands are already checked for being valid command
* words. If the user entered an invalid command (a word that is not known) then * words. If the user entered an invalid command (a word that is not known) then
* the command word is <null>. * the command word is <null>.
* *
* If the command had only one word, then the second word is <null>. * If the command had only one word, then the second word is <null>.
* *
* The second word is not checked at the moment. It can be anything. If this * The second word is not checked at the moment. It can be anything. If this
* game is extended to deal with items, then the second part of the command * game is extended to deal with items, then the second part of the command
* should probably be changed to be an item rather than a String. * should probably be changed to be an item rather than a String.
*/ */
class Command { class Command {
private String commandWord; private String commandWord;
private String direction; private String direction;
private ArrayList<String> otherWords; private ArrayList<String> otherWords;
private String item; private String item;
/** /**
* Create a command object. First and second word must be supplied, but * Create a command object. First and second word must be supplied, but
* either one (or both) can be null. The command word should be null to * either one (or both) can be null. The command word should be null to
* indicate that this was a command that is not recognised by this game. * indicate that this was a command that is not recognised by this game.
*/ */
public Command(String firstWord, ArrayList<String> otherWords, String direction, String item) { public Command(String firstWord, ArrayList<String> otherWords, String direction, String item) {
commandWord = firstWord; commandWord = firstWord;
this.otherWords = otherWords; this.otherWords = otherWords;
this.direction = direction; this.direction = direction;
this.item = item; if(direction.equals("e"))
} this.direction = "east";
if(direction.equals("w"))
/** this.direction = "west";
* Return the command word (the first word) of this command. If the command if(direction.equals("s"))
* was not understood, the result is null. this.direction = "south";
*/ if(direction.equals("n"))
public String getCommandWord() { this.direction = "north";
return commandWord; if(direction.equals("u"))
} this.direction = "up";
if(direction.equals("d"))
/** this.direction = "down";
* Return the second word of this command. Returns null if there was no this.item = item;
* second word. }
*/
public ArrayList<String> getOtherWords() { /**
return otherWords; * Return the command word (the first word) of this command. If the command
} * was not understood, the result is null.
/* */
public String getSecondWord() { public String getCommandWord() {
return otherWords.get(0); return commandWord;
} }
*/
/**
/** * Return the second word of this command. Returns null if there was no
* Return true if this command was not understood. * second word.
*/ */
public boolean isUnknown() { public ArrayList<String> getOtherWords() {
return (commandWord == null); return otherWords;
} }
/*
/** public String getSecondWord() {
* Return true if the command has a second word. return otherWords.get(0);
*/ }
public boolean hasSecondWord() { */
return otherWords.size() > 0;
} /**
* Return true if this command was not understood.
public boolean hasItem(){ */
return item.equals(""); public boolean isUnknown() {
} return (commandWord == null);
public boolean hasDirection() { }
return CommandWords.isDirection(commandWord);
} /**
public String getDirection() { * Return true if the command has a second word.
return direction; */
} public boolean hasSecondWord() {
} return otherWords.size() > 0;
}
public boolean hasItem(){
return item.equals("");
}
public boolean hasDirection() {
return CommandWords.isDirection(direction);
}
public String getDirection() {
return direction;
}
}

View File

@@ -1,74 +1,78 @@
package com.bayviewglen.zork; package com.bayviewglen.zork;
import java.io.File; import java.io.File;
import java.util.HashMap; import java.util.HashMap;
import java.util.Scanner; import java.util.Scanner;
/* /*
* Author: Michael Kolling. * Author: Michael Kolling.
* Version: 1.0 * Version: 1.0
* Date: July 1999 * Date: July 1999
* *
* This class holds an enumeration of all command words known to the game. * This class holds an enumeration of all command words known to the game.
* It is used to recognise commands as they are typed in. * It is used to recognise commands as they are typed in.
* *
* This class is part of the "Zork" game. * This class is part of the "Zork" game.
*/ */
class CommandWords { class CommandWords {
// a constant array that holds all valid command words // a constant array that holds all valid command words
private static HashMap<String, String> m_words = new HashMap<String, String>();; private static HashMap<String, String> m_words = new HashMap<String, String>();;
/** /**
* Constructor - initialise the command words. * Constructor - initialise the command words.
*/ */
public CommandWords() { public CommandWords() {
// Import words from words.dat into HashMap // Import words from words.dat into HashMap
try { try {
Scanner in = new Scanner(new File("data/words.dat")); Scanner in = new Scanner(new File("data/words.dat"));
while(in.hasNext()){ while(in.hasNext()){
String text = in.nextLine(); String text = in.nextLine();
String[] textarr = text.split(","); String[] textarr = text.split(",");
m_words.put(textarr[0], textarr[1].substring(1)); m_words.put(textarr[0], textarr[1].substring(1));
} }
in.close(); in.close();
}catch (Exception e) { }catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Check whether a given String is a valid command word. Return true if it * Check whether a given String is a valid command word. Return true if it
* is, false if it isn't. * is, false if it isn't.
**/ **/
// Check if given string is verb or direction // Check if given string is verb or direction
public static boolean isCommand(String aString) { public static boolean isCommand(String aString) {
try { try {
return (m_words.get(aString).equals("verb") || m_words.get(aString).equals("direction")); return (m_words.get(aString).equals("verb") || m_words.get(aString).equals("direction"));
}catch(Exception e) { }catch(Exception e) {
return false; return false;
} }
} }
// Check if given string is direction // Check if given string is direction
public static boolean isDirection(String aString) { public static boolean isDirection(String aString) {
return m_words.get(aString).equals("direction"); try {
} return m_words.get(aString).equals("direction");
}catch(Exception e) {
public static boolean isItem(String aString){ return false;
try { }
return m_words.get(aString).equals("item"); }
} catch(Exception e) {
return false; public static boolean isItem(String aString){
} try {
} return m_words.get(aString).equals("item");
} catch(Exception e) {
/* return false;
* Print all valid commands to System.out. }
*/ }
public void showAll() {
for (String i : m_words.keySet()) { /*
if(m_words.get(i).equals("verb")){ * Print all valid commands to System.out.
System.out.print(i + " "); */
} public void showAll() {
} for (String i : m_words.keySet()) {
System.out.println(); if(m_words.get(i).equals("verb")){
} System.out.print(i + " ");
}
}
System.out.println();
}
} }

View File

@@ -1,29 +1,29 @@
package com.bayviewglen.zork.Entities; package com.bayviewglen.zork.Entities;
import com.bayviewglen.zork.Items.Item; import com.bayviewglen.zork.Items.Item;
import java.util.ArrayList; import java.util.ArrayList;
public class Player extends Entity{ public class Player extends Entity{
private ArrayList<Item> inventory = new ArrayList<Item>(); private ArrayList<Item> inventory = new ArrayList<Item>();
private final int INVENTORY_CAPACITY = 120; private final int INVENTORY_CAPACITY = 120;
private int currentInventoryWeight; private int currentInventoryWeight;
public Player() { public Player() {
super(); super();
} }
private boolean addToInventory(Item item){ public boolean addToInventory(Item item){
if(currentInventoryWeight + item.getWeight() < INVENTORY_CAPACITY){ if(currentInventoryWeight + item.getWeight() < INVENTORY_CAPACITY){
inventory.add(item); inventory.add(item);
System.out.println(item.getName() + " add"); System.out.println(item.getName() + " add");
return true; return true;
} }
return false; return false;
} }
private void removeFromInventory(Item item){ public void removeFromInventory(Item item){
inventory.remove(item); inventory.remove(item);
} }
} }

View File

@@ -1,207 +1,227 @@
package com.bayviewglen.zork; package com.bayviewglen.zork;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.util.HashMap; import java.lang.reflect.Constructor;
import java.util.Scanner; import java.util.HashMap;
import java.util.Scanner;
import com.bayviewglen.zork.Items.*;
import com.bayviewglen.zork.Items.*;
/**
* Class Game - the main class of the "Zork" game. /**
* * Class Game - the main class of the "Zork" game.
* Author: Michael Kolling Version: 1.1 Date: March 2000 *
* * Author: Michael Kolling Version: 1.1 Date: March 2000
* This class is the main class of the "Zork" application. Zork is a very *
* simple, text based adventure game. Users can walk around some scenery. That's * This class is the main class of the "Zork" application. Zork is a very
* all. It should really be extended to make it more interesting! * simple, text based adventure game. Users can walk around some scenery. That's
* * all. It should really be extended to make it more interesting!
* To play this game, create an instance of this class and call the "play" *
* routine. * To play this game, create an instance of this class and call the "play"
* * routine.
* This main class creates and initialises all the others: it creates all rooms, *
* creates the parser and starts the game. It also evaluates the commands that * This main class creates and initialises all the others: it creates all rooms,
* the parser returns. * creates the parser and starts the game. It also evaluates the commands that
*/ * the parser returns.
class Game { */
private Parser parser; class Game {
private Room currentRoom; private Parser parser;
// This is a MASTER object that contains all of the rooms and is easily private Room currentRoom;
// accessible. // This is a MASTER object that contains all of the rooms and is easily
// The key will be the name of the room -> no spaces (Use all caps and // accessible.
// underscore -> Great Room would have a key of GREAT_ROOM // The key will be the name of the room -> no spaces (Use all caps and
// In a hashmap keys are case sensitive. // underscore -> Great Room would have a key of GREAT_ROOM
// masterRoomMap.get("GREAT_ROOM") will return the Room Object that is the // In a hashmap keys are case sensitive.
// Great Room (assuming you have one). // masterRoomMap.get("GREAT_ROOM") will return the Room Object that is the
private HashMap<String, Room> masterRoomMap; // Great Room (assuming you have one).
private HashMap<Item, String> itemsInRooms = new HashMap<Item, String>(); private HashMap<String, Room> masterRoomMap;
//private HashMap<Item, String> itemsInRooms = new HashMap<Item, String>();
private void initRooms(String fileName) throws Exception {
itemsInRooms.put(new Candlestick(), "Candlestick"); private void initRooms(String fileName) throws Exception {
masterRoomMap = new HashMap<String, Room>(); //itemsInRooms.put(new Candlestick(), "Candlestick");
Scanner roomScanner; masterRoomMap = new HashMap<String, Room>();
try { Scanner roomScanner;
HashMap<String, HashMap<String, String>> exits = new HashMap<String, HashMap<String, String>>(); try {
roomScanner = new Scanner(new File(fileName)); HashMap<String, HashMap<String, String>> exits = new HashMap<String, HashMap<String, String>>();
while (roomScanner.hasNext()) { roomScanner = new Scanner(new File(fileName));
Room room = new Room(); while (roomScanner.hasNext()) {
// Read the Name Room room = new Room();
String roomName = roomScanner.nextLine(); // Read the Name
room.setRoomName(roomName.split(":")[1].trim()); String roomName = roomScanner.nextLine();
// Read the Description room.setRoomName(roomName.split(":")[1].trim());
String roomDescription = roomScanner.nextLine(); // Read the Description
room.setDescription(roomDescription.split(":")[1].replaceAll("<br>", "\n").trim()); String roomDescription = roomScanner.nextLine();
// Read the Exits room.setDescription(roomDescription.split(":")[1].replaceAll("<br>", "\n").trim());
String roomExits = roomScanner.nextLine(); // Read the Items
// An array of strings in the format E-RoomName String items = roomScanner.nextLine();
String[] rooms = roomExits.split(":")[1].split(","); try {
HashMap<String, String> temp = new HashMap<String, String>(); String[] itemArr = items.split(":")[1].split(",");
for (String s : rooms) { for(String s : itemArr) {
temp.put(s.split("-")[0].trim(), s.split("-")[1]); Class<?> clazz = Class.forName("com.bayviewglen.zork.Items." + s.trim());
} Constructor<?> ctor = clazz.getConstructor();
Item object = (Item) ctor.newInstance();
exits.put(roomName.substring(10).trim().toUpperCase().replaceAll(" ", "_"), temp); room.addItem(object);
}
// This puts the room we created (Without the exits in the }catch(Exception e) {
// masterMap) }
masterRoomMap.put(roomName.toUpperCase().substring(10).trim().replaceAll(" ", "_"), room);
// Read the Exits
// Now we better set the exits. String roomExits = roomScanner.nextLine();
} // An array of strings in the format E-RoomName
String[] rooms = roomExits.split(":")[1].split(",");
for (String key : masterRoomMap.keySet()) { HashMap<String, String> temp = new HashMap<String, String>();
Room roomTemp = masterRoomMap.get(key); for (String s : rooms) {
HashMap<String, String> tempExits = exits.get(key); temp.put(s.split("-")[0].trim(), s.split("-")[1]);
for (String s : tempExits.keySet()) { }
// s = direction
// value is the room. exits.put(roomName.substring(10).trim().toUpperCase().replaceAll(" ", "_"), temp);
String roomName2 = tempExits.get(s.trim()); // This puts the room we created (Without the exits in the
Room exitRoom = masterRoomMap.get(roomName2.toUpperCase().replaceAll(" ", "_")); // masterMap)
roomTemp.setExit(s.trim().charAt(0), exitRoom); masterRoomMap.put(roomName.toUpperCase().substring(10).trim().replaceAll(" ", "_"), room);
} // Now we better set the exits.
}
}
for (String key : masterRoomMap.keySet()) {
roomScanner.close(); Room roomTemp = masterRoomMap.get(key);
} catch (FileNotFoundException e) { HashMap<String, String> tempExits = exits.get(key);
e.printStackTrace(); for (String s : tempExits.keySet()) {
} // s = direction
} // value is the room.
/** String roomName2 = tempExits.get(s.trim());
* Create the game and initialise its internal map. Room exitRoom = masterRoomMap.get(roomName2.toUpperCase().replaceAll(" ", "_"));
*/ roomTemp.setExit(s.trim().charAt(0), exitRoom);
public Game() {
try { }
initRooms("data/Rooms.dat");
currentRoom = masterRoomMap.get("ROOM_1"); }
} catch (Exception e) {
// TODO Auto-generated catch block roomScanner.close();
e.printStackTrace(); } catch (FileNotFoundException e) {
} e.printStackTrace();
parser = new Parser(); }
} }
/** /**
* Main play routine. Loops until end of play. * Create the game and initialise its internal map.
*/ */
public void play() { public Game() {
printWelcome(); try {
// Enter the main command loop. Here we repeatedly read commands and initRooms("data/Rooms.dat");
// execute them until the game is over. currentRoom = masterRoomMap.get("ROOM_1");
} catch (Exception e) {
boolean finished = false; e.printStackTrace();
while (!finished) { }
Command command = parser.getCommand(); parser = new Parser();
finished = processCommand(command); }
}
System.out.println("Thank you for playing. Good bye."); /**
} * Main play routine. Loops until end of play.
*/
/** public void play() {
* Print out the opening message for the player. printWelcome();
*/ // Enter the main command loop. Here we repeatedly read commands and
private void printWelcome() { // execute them until the game is over.
System.out.println();
System.out.println("Welcome to Zork!"); boolean finished = false;
System.out.println("Zork is a new, incredibly boring adventure game, for now..."); while (!finished) {
System.out.println("Type 'help' if you need help."); Command command = parser.getCommand();
System.out.println(); finished = processCommand(command);
System.out.println(currentRoom.longDescription()); }
} System.out.println("Thank you for playing. Good bye.");
}
/**
* Given a command, process (that is: execute) the command. If this command /**
* ends the game, true is returned, otherwise false is returned. * Print out the opening message for the player.
*/ */
private boolean processCommand(Command command) { private void printWelcome() {
System.out.println();
if (command.isUnknown()) { System.out.println("Welcome to Zork!");
System.out.println("I don't know what you mean..."); System.out.println("Zork is a new, incredibly boring adventure game, for now...");
return false; System.out.println("Type 'help' if you need help.");
} System.out.println();
String commandWord = command.getCommandWord(); System.out.println(currentRoom.longDescription());
switch(commandWord) { }
case "go": case "n": case "s": case "e": case "w": case "north": case "south": case "west": case "east": case "up": case "down":
goRoom(command); /**
break; * Given a command, process (that is: execute) the command. If this command
case "help": * ends the game, true is returned, otherwise false is returned.
printHelp(); */
break; private boolean processCommand(Command command) {
case "jump":
System.out.println("Good Job!"); if (command.isUnknown()) {
break; System.out.println("I don't know what you mean...");
case "quit": return false;
return true; }
case "eat": String commandWord = command.getCommandWord();
System.out.println("Do you really think you should be eating at a time like this?"); switch(commandWord) {
break; case "go": case "n": case "s": case "e": case "w": case "north": case "south": case "west": case "east": case "up": case "down":
case "look": goRoom(command);
for (Item i : itemsInRooms.keySet()) { break;
System.out.print(i.getName() + " "); case "help":
} printHelp();
System.out.println(); break;
break; case "jump":
default: System.out.println("Good Job!");
return false; break;
} case "quit":
return false; return true;
} case "eat":
System.out.println("Do you really think you should be eating at a time like this?");
// implementations of user commands: break;
/** case "look":
* Print out some help information. Here we print some stupid, cryptic System.out.print("Items: ");
* message and a list of the command words. for(Item i : currentRoom.getItems()) {
*/ System.out.print(i.getName() + " ");
private void printHelp() { }
System.out.println("You are lost. You are alone. You wander"); System.out.println();
System.out.println("around at Monash Uni, Peninsula Campus."); /*
System.out.println(); for (Item i : itemsInRooms.keySet()) {
System.out.println("Your command words are:"); System.out.print(i.getName() + " ");
parser.showCommands(); }
} System.out.println();
*/
/** break;
* Try to go to one direction. If there is an exit, enter the new room, default:
* otherwise print an error message. return false;
*/ }
private void goRoom(Command command) { return false;
if (!command.hasDirection()) { }
// if there is no second word, we don't know where to go...
System.out.println("Go where?"); // implementations of user commands:
return; /**
} * Print out some help information. Here we print some stupid, cryptic
String direction = command.getDirection(); * message and a list of the command words.
// Try to leave current room. */
Room nextRoom = currentRoom.nextRoom(direction); private void printHelp() {
if (nextRoom == null) System.out.println("You are lost. You are alone. You wander");
System.out.println("There is no door!"); System.out.println("around at Monash Uni, Peninsula Campus.");
else { System.out.println();
currentRoom = nextRoom; System.out.println("Your command words are:");
System.out.println(currentRoom.longDescription()); parser.showCommands();
} }
}
/**
* Try to go to one direction. If there is an exit, enter the new room,
* otherwise print an error message.
*/
private void goRoom(Command command) {
if (!command.hasDirection()) {
// if there is no second word, we don't know where to go...
System.out.println("Go where?");
return;
}
String direction = command.getDirection();
// Try to leave current room.
Room nextRoom = currentRoom.nextRoom(direction);
if (nextRoom == null)
System.out.println("There is no door!");
else {
currentRoom = nextRoom;
System.out.println(currentRoom.longDescription());
}
}
} }

View File

@@ -1,78 +1,78 @@
package com.bayviewglen.zork; package com.bayviewglen.zork;
/* /*
* Author: Michael Kolling * Author: Michael Kolling
* Version: 1.0 * Version: 1.0
* Date: July 1999 * Date: July 1999
* *
* This class is part of Zork. Zork is a simple, text based adventure game. * This class is part of Zork. Zork is a simple, text based adventure game.
* *
* This parser reads user input and tries to interpret it as a "Zork" * This parser reads user input and tries to interpret it as a "Zork"
* command. Every time it is called it reads a line from the terminal and * command. Every time it is called it reads a line from the terminal and
* tries to interpret the line as a two word command. It returns the command * tries to interpret the line as a two word command. It returns the command
* as an object of class Command. * as an object of class Command.
* *
* The parser has a set of known command words. It checks user input against * The parser has a set of known command words. It checks user input against
* the known commands, and if the input is not one of the known commands, it * the known commands, and if the input is not one of the known commands, it
* returns a command object that is marked as an unknown command. * returns a command object that is marked as an unknown command.
*/ */
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import com.bayviewglen.zork.CommandWords; import com.bayviewglen.zork.CommandWords;
class Parser { class Parser {
private CommandWords commands; // holds all valid command words private CommandWords commands; // holds all valid command words
public Parser() { public Parser() {
commands = new CommandWords(); commands = new CommandWords();
} }
public Command getCommand() { public Command getCommand() {
String inputLine = ""; // will hold the full input line String inputLine = ""; // will hold the full input line
String verb = ""; String verb = "";
String direction = ""; String direction = "";
String item = ""; String item = "";
//String word2; //String word2;
ArrayList<String> words = new ArrayList<String>(); ArrayList<String> words = new ArrayList<String>();
ArrayList<String> otherWords = new ArrayList<String>(); ArrayList<String> otherWords = new ArrayList<String>();
System.out.print("> "); // print prompt System.out.print("> "); // print prompt
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try { try {
inputLine = reader.readLine(); inputLine = reader.readLine();
} catch (java.io.IOException exc) { } catch (java.io.IOException exc) {
System.out.println("There was an error during reading: " + exc.getMessage()); System.out.println("There was an error during reading: " + exc.getMessage());
} }
StringTokenizer tokenizer = new StringTokenizer(inputLine); StringTokenizer tokenizer = new StringTokenizer(inputLine.toLowerCase());
while(tokenizer.hasMoreTokens()) { while(tokenizer.hasMoreTokens()) {
words.add(tokenizer.nextToken()); words.add(tokenizer.nextToken());
} }
for(int i=0; i<words.size(); i++) { for(int i=0; i<words.size(); i++) {
if(CommandWords.isCommand(words.get(i))) { if(CommandWords.isCommand(words.get(i))) {
verb = words.get(i); verb = words.get(i);
if(CommandWords.isDirection(words.get(i))) { if(CommandWords.isDirection(words.get(i))) {
direction = words.get(i); direction = words.get(i);
} }
}else if(CommandWords.isItem(words.get(i))){ }else if(CommandWords.isItem(words.get(i))){
item = words.get(i); item = words.get(i);
} }
else { else {
otherWords.add(words.get(i)); otherWords.add(words.get(i));
} }
} }
//System.out.println(verb); //System.out.println(verb);
if (CommandWords.isCommand(verb)) if (CommandWords.isCommand(verb))
return new Command(verb, otherWords, direction, item); return new Command(verb, otherWords, direction, item);
else else
return new Command(null, otherWords, direction, item); return new Command(null, otherWords, direction, item);
} }
/** /**
* Print out a list of valid command words. * Print out a list of valid command words.
*/ */
public void showCommands() { public void showCommands() {
commands.showAll(); commands.showAll();
} }
} }

View File

@@ -1,144 +1,190 @@
package com.bayviewglen.zork; package com.bayviewglen.zork;
/* /*
* Class Room - a room in an adventure game. * Class Room - a room in an adventure game.
* *
* Author: Michael Kolling * Author: Michael Kolling
* Version: 1.1 * Version: 1.1
* Date: August 2000 * Date: August 2000
* *
* This class is part of Zork. Zork is a simple, text based adventure game. * This class is part of Zork. Zork is a simple, text based adventure game.
* *
* "Room" represents one location in the scenery of the game. It is * "Room" represents one location in the scenery of the game. It is
* connected to at most four other rooms via exits. The exits are labelled * connected to at most four other rooms via exits. The exits are labelled
* north, east, south, west. For each direction, the room stores a reference * north, east, south, west. For each direction, the room stores a reference
* to the neighbouring room, or null if there is no exit in that direction. * to the neighbouring room, or null if there is no exit in that direction.
*/ */
import java.util.Set; import java.util.Set;
import java.util.HashMap; import java.util.ArrayList;
import java.util.Iterator; import java.util.HashMap;
import java.util.Iterator;
class Room { import com.bayviewglen.zork.Items.*;
private String roomName;
private String description; class Room {
private HashMap<String, Room> exits; // stores exits of this room. private String roomName;
private String description;
/** private HashMap<String, Room> exits; // stores exits of this room.
* Create a room described "description". Initially, it has no exits. private ArrayList<Item> items;
* "description" is something like "a kitchen" or "an open court yard".
*/ /**
public Room(String description) { * Create a room described "description". Initially, it has no exits.
this.description = description; * "description" is something like "a kitchen" or "an open court yard".
exits = new HashMap<String, Room>(); */
} public Room(String description) {
this.description = description;
public Room() { exits = new HashMap<String, Room>();
// default constructor. items = new ArrayList<Item>();
roomName = "DEFAULT ROOM"; }
description = "DEFAULT DESCRIPTION";
exits = new HashMap<String, Room>(); public Room() {
} // default constructor.
roomName = "DEFAULT ROOM";
public void setExit(char direction, Room r) throws Exception { description = "DEFAULT DESCRIPTION";
String dir = ""; exits = new HashMap<String, Room>();
switch (direction) { items = new ArrayList<Item>();
case 'E': }
dir = "east";
break; public void setExit(char direction, Room r) throws Exception {
case 'W': String dir = "";
dir = "west"; switch (direction) {
break; case 'E':
case 'S': dir = "east";
dir = "south"; break;
break; case 'W':
case 'N': dir = "west";
dir = "north"; break;
break; case 'S':
case 'U': dir = "south";
dir = "up"; break;
break; case 'N':
case 'D': dir = "north";
dir = "down"; break;
break; case 'U':
default: dir = "up";
throw new Exception("Invalid Direction"); break;
case 'D':
} dir = "down";
break;
exits.put(dir, r); default:
} throw new Exception("Invalid Direction");
/** }
* Define the exits of this room. Every direction either leads to another
* room or is null (no exit there). exits.put(dir, r);
*/ }
public void setExits(Room north, Room east, Room south, Room west, Room up, Room down) {
if (north != null) /*
exits.put("north", north); * Add passed in item to item array list
if (east != null) */
exits.put("east", east); public void addItem(Item item) {
if (south != null) items.add(item);
exits.put("south", south); }
if (west != null)
exits.put("west", west); /*
if (up != null) * Remove first instance of item passed in
exits.put("up", up); * Return item if removed, otherwise return null
if (up != null) */
exits.put("down", down); public Item removeItem(Item item) {
for(int i=0; i<items.size(); i++) {
} if(item.equals(items.get(i))) {
items.remove(i);
/** return item;
* Return the description of the room (the one that was defined in the }
* constructor). }
*/ return null;
public String shortDescription() { }
return "Room: " + roomName + "\n\n" + description;
} /*
* Remove item at index
/** * Return item if removed, otherwise return null
* Return a long description of this room, on the form: You are in the */
* kitchen. Exits: north west public Item removeItem(int i) {
*/ if(i >= items.size())
public String longDescription() { return null;
Item temp = items.get(i);
return "Room: " + roomName + "\n\n" + description + "\n" + exitString(); items.remove(i);
} return temp;
}
/**
* Return a string describing the room's exits, for example "Exits: north public ArrayList<Item> getItems() {
* west ". return items;
*/ }
private String exitString() {
String returnString = "Exits:"; public Item getItem(int i) {
Set keys = exits.keySet(); return items.get(i);
for (Iterator iter = keys.iterator(); iter.hasNext();) }
returnString += " " + iter.next();
return returnString; /**
} * Define the exits of this room. Every direction either leads to another
* room or is null (no exit there).
/** */
* Return the room that is reached if we go from this room in direction public void setExits(Room north, Room east, Room south, Room west, Room up, Room down) {
* "direction". If there is no room in that direction, return null. if (north != null)
*/ exits.put("north", north);
public Room nextRoom(String direction) { if (east != null)
return (Room) exits.get(direction); exits.put("east", east);
} if (south != null)
exits.put("south", south);
public String getRoomName() { if (west != null)
return roomName; exits.put("west", west);
} if (up != null)
exits.put("up", up);
public void setRoomName(String roomName) { if (up != null)
this.roomName = roomName; exits.put("down", down);
}
}
public String getDescription() {
return description; /**
} * Return the description of the room (the one that was defined in the
* constructor).
public void setDescription(String description) { */
this.description = description; public String shortDescription() {
} return "Room: " + roomName + "\n\n" + description;
} }
/**
* Return a long description of this room, on the form: You are in the
* kitchen. Exits: north west
*/
public String longDescription() {
return "Room: " + roomName + "\n\n" + description + "\n" + exitString();
}
/**
* Return a string describing the room's exits, for example "Exits: north
* west ".
*/
private String exitString() {
String returnString = "Exits:";
Set keys = exits.keySet();
for (Iterator iter = keys.iterator(); iter.hasNext();)
returnString += " " + iter.next();
return returnString;
}
/**
* Return the room that is reached if we go from this room in direction
* "direction". If there is no room in that direction, return null.
*/
public Room nextRoom(String direction) {
return (Room) exits.get(direction);
}
public String getRoomName() {
return roomName;
}
public void setRoomName(String roomName) {
this.roomName = roomName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}