CS117-S18-AlharbiMohammed-master/.gitignore
*.class
*.ctxt
*.*~
doc
/.project
default.log
defaultlog.txt
CS117-S18-AlharbiMohammed-master/Command.javaCS117-S18-AlharbiMohammed-master/Command.javaimport java.util.ArrayList;
/**
* This class is part of the "Campus of Kings" application. "Campus of Kings" is a
* very simple, text based adventure game.
*
* 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
* (for example, if the command was "take map", then the two strings obviously
* are "take" and "map").
*
* 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
* the command word is <null>.
*
* If the command had only one word, then the second word is <null>.
*
* @author Maria Jump
* @version 2015.02.01
*/
publicclassCommand{
/** The command word for this command. */
privateString commandWord;
/** The rest of the line with all the spaces removed. */
privateArrayList<String> restOfLine;
/**
* Create a command object. First is supplied. The second word is assumed
* to be null.
*
* @param firstWord
* The first word of the command. Null if the command was not
* recognized.
*/
publicCommand(String firstWord){
commandWord = firstWord;
restOfLine =newArrayList<String>();
}
/**
* Create a command object. First and second word must be supplied, but
* either one (or both) can be null.
*
* @param firstWord
* The first word of the command. Null if the command was not
* recognized.
* @param rest
* The rest of the command.
*/
publicCommand(String firstWord,ArrayList<String> rest){
commandWord = firstWord;
restOfLine = rest;
}
/**
* Return the command word (the first word) of this command. If the command
* was not understood, the result is null.
*
* @return The command word.
*/
publicString getCommandWord(){
return commandWord;
}
/**
* Returns if this command was not understood.
*
* @return true if this command was not understood.
*/
publicboolean isUnknown(){
return(commandWord ==null);
}
/**
* Returns if this command has a second word.
*
* @return true if the command has a second word.
*/
publicboolean hasSecondWord(){
return restOfLine !=null;
}
/**
* Returns if this command has more words.
*
* @param index The index of the word needed.
* @return true if the command has a word at given index.
*/
publicboolean hasWord(int index){
return index >=0&& index < restOfLine.size();
}
/**
* Returns the word at the requested index in the command.
*
* @param index
* The index of word in the command that is being requested.
*
* @ret.
2. *
* If the command had only one word, then the second word is <
null>.
*
* @author Maria Jump
* @version 2015.02.01
*/
publicclassCommand{
/** The command word for this command. */
privateString commandWord;
/** The rest of the line with all the spaces removed. */
privateArrayList<String> restOfLine;
/**
* Create a command object. First is supplied. The second wo
rd is assumed
* to be null.
*
* @param firstWord
* The first word of the command. Null if the comman
d was not
* recognized.
*/
publicCommand(String firstWord){
commandWord = firstWord;
restOfLine =newArrayList<String>();
}
/**
* Create a command object. First and second word must be s
upplied, but
* either one (or both) can be null.
*
* @param firstWord
* The first word of the command. Null if the comman
3. d was not
* recognized.
* @param rest
* The rest of the command.
*/
publicCommand(String firstWord,ArrayList<String> rest){
commandWord = firstWord;
restOfLine = rest;
}
/**
* Return the command word (the first word) of this comman
d. If the command
* was not understood, the result is null.
*
* @return The command word.
*/
publicString getCommandWord(){
return commandWord;
}
/**
* Returns if this command was not understood.
*
* @return true if this command was not understood.
*/
publicboolean isUnknown(){
return(commandWord ==null);
}
/**
* Returns if this command has a second word.
*
* @return true if the command has a second word.
*/
publicboolean hasSecondWord(){
4. return restOfLine !=null;
}
/**
* Returns if this command has more words.
*
* @param index The index of the word needed.
* @return true if the command has a word at given index.
*/
publicboolean hasWord(int index){
return index >=0&& index < restOfLine.size();
}
/**
* Returns the word at the requested index in the command.
*
* @param index
* The index of word in the command that is being req
uested.
*
* @return A particular word in the command. Returns null if
there is no
* word corresponding to that requested index.
*
*/
publicString getWord(int index){
String result =null;
if(index >=0&& index < restOfLine.size()){
result = restOfLine.get(index);
}
return result;
}
/**
* Returns the second word of this command, if it exists.
5. *
* @return The second word of this command. Returns null if
there was no
* second word.
*/
publicString getRestOfLine(){
StringBuffer buffer =null;
if(restOfLine.size()!=0){
for(String word : restOfLine){
if(buffer ==null){
buffer =newStringBuffer();
buffer.append(word);
}
else{
buffer.append(" ");
buffer.append(word);
}
}
}
String result ="";
if(buffer !=null){
result += buffer.toString();
}
return result;
}
}
CS117-S18-AlharbiMohammed-
master/CommandWords.javaCS117-S18-AlharbiMohammed-
master/CommandWords.java/**
* This class is part of the "Campus of Kings" application. "Cam
pus of Kings" is a
* very simple, text based adventure game.
*
* This class holds an enumeration of all command words know
6. n to the game. It is
* used to recognize commands as they are typed in.
*
* @author Maria Jump
* @version 2015.02.01
*/
publicclassCommandWords{
/** A constant array that holds all valid command words. */
privatestaticString[] validCommands;
/**
* Static block to initialize the fields of CommandWords.
*/
static{
String[] tempCommands ={"go","quit","help"};
validCommands = tempCommands;
}
/**
* Check whether a given String is a valid command word.
*
* @param aString The string to determine whether it is a val
id command.
* @return true if a given string is a valid command, false if i
t isn't.
*/
publicstaticboolean isCommand(String aString){
boolean valid =false;
int index =0;
while(!valid && index < validCommands.length){
if(validCommands[index].equals(aString)){
valid =true;
}
index++;
}
7. // if we get here, the string was not found in the commands
return valid;
}
}
CS117-S18-AlharbiMohammed-master/Door.javaCS117-S18-
AlharbiMohammed-master/Door.java/**
* Class Door -
a door or portal between two Rooms in an adventure game.
*
* This class is part of the "Campus of Kings" application. "Cam
pus of Kings" is a
* very simple, text based adventure game.
*
* A "Door" represents a door or portal between two locations o
f the game.
* It stores a reference to the neighboring room and whether that
door
* or portal is locked. Doors are not locked by default.
*
* @author Maria Jump
* @version 2015.02.01
*/
publicclassDoor{
/** The room that this door leads to. */
privateRoom destination;
/** Whether this door is locked. */
privateboolean locked;
/**
* Constructor for the Door class.
* @param destination The room this door leads to
*/
publicDoor(Room destination){
8. this.destination = destination;
this.locked =false;
}
/**
* A getter for the room this door leads to.
* @return The room this door leads to
*/
publicRoom getDestination(){
return destination;
}
/**
* A getter for whether this door is locked.
* @return Whether this door is locked
*/
publicboolean isLocked(){
return locked;
}
/**
* A setter for whether this door is locked.
* @param locked Whether this door is locked.
*/
publicvoid setLocked(boolean locked){
this.locked = locked;
}
}
CS117-S18-AlharbiMohammed-master/Game.javaCS117-S18-
AlharbiMohammed-
master/Game.java//import java.util.HashMap;
/**
* This class is the main class of the "Campus of Kings" applica
9. tion.
* "Campus of Kings" is a very simple, text based adventure ga
me. Users can walk
* around some scenery. That's all. It should really be extended
to make it more
* interesting!
* This game class creates and initializes all the others: it create
s all rooms,
* creates the parser and starts the game. It also evaluates and e
xecutes the
* commands that the parser returns.
*
* @author Mohammed Alharbi
* @version 2018/1/24
*/
publicclassGame{
/** The world where the game takes place. */
privateWorld world;
//** stores the character controlled by the Player. */
//private Player Playing;
/** the total score. */
privateint score ;
/** the total number of turns. */
privateint turns;
/** This is an object for getting the room from the Player class.
*/
privatePlayer playerClass;
/**
* Create the game and initialize its internal map.
*/
publicGame(){
world =newWorld();
playerClass =newPlayer(world.getcurrentRoom("Bathroom
"));
score =0;
10. turns =0;
}
/**
* Main play routine. Loops until end of play.
*/
publicvoid play(){
printWelcome();
// Enter the main game loop. Here we repeatedly read commands
and
// execute them until the game is over.
boolean wantToQuit =false;
while(!wantToQuit){
Command command =Reader.getCommand();
wantToQuit = processCommand(command);
turns = turns +1;
}
printGoodbye();
}
///////////////////////////////////////////////////////////////////////////
// Helper methods for processing the commands
/**
* Given a command, process (that is: execute) the command.
*
* @param command
* The command to be processed.
* @return true If the command ends the game, false otherwis
e.
*/
privateboolean processCommand(Command command){
boolean wantToQuit =false;
11. if(command.isUnknown()){
Writer.println("I don't know what you mean...");
}else{
String commandWord = command.getCommandWord();
if(commandWord.equals("help")){
printHelp();
}elseif(commandWord.equals("go")){
goGame(command);
}elseif(commandWord.equals("quit")){
wantToQuit = quit(command);
}else{
Writer.println(commandWord +" is not implemented yet!");
}
}
return wantToQuit;
}
///////////////////////////////////////////////////////////////////////////
// Helper methods for implementing all of the commands.
// It helps if you organize these in alphabetical order.
/**
* Try to go to one direction. If there is an exit, enter the new
room,
* otherwise print an error message.
*
* @param command
* The command to be processed.
*/
privatevoid goGame(Command command){
if(!command.hasSecondWord()){
Writer.println("Go where?");
12. }else{
String direction = command.getRestOfLine();
Door doorway =null;
doorway = playerClass.getcurrentRoom().getDirection(d
irection);
if(doorway ==null){
Writer.println("There is no door!");
}else{
Room newRoom = doorway.getDestination();
playerClass.setcurrentRoom(newRoom);
score = score + newRoom.getPoints();
printLocationInformation ();
}
}
}
/**
* Print out the closing message for the player.
*/
privatevoid printGoodbye(){
Writer.println("I hope you weren't too bored here on the Campu
s of Kings!");
Writer.println("Thank you for playing. Good bye.");
Writer.println("You have earned"+" "+ score +"points in"+" "+ t
urns +" "+"turns.");
}
/**
* Prints out the current location and exits.
*/
privatevoid printLocationInformation(){
Writer.println(playerClass.getcurrentRoom()+" : ");
Writer.println("You are in "+ playerClass.getcurrentRoom());
Writer.print("Exits: ");
13. }
/**
* Print out some help information. Here we print some stupi
d, cryptic
* message and a list of the command words.
*/
privatevoid printHelp(){
Writer.println("You are lost. You are alone. You wander");
Writer.println("around at the university.");
Writer.println();
Writer.println("Your command words are:");
Writer.println("go quit help");
}
/**
* Print out the opening message for the player.
*/
privatevoid printWelcome(){
Room currentRoom = playerClass.getcurrentRoom();
Writer.println();
Writer.println("Welcome to the Campus of Kings!");
Writer.println("Campus of Kings is a new, incredibly boring ad
venture game.");
Writer.println("Type 'help' if you need help.");
printLocationInformation();
}
/**
* "Quit" was entered. Check the rest of the command to see
whether we
* really quit the game.
15. import javax.swing.JTextPane;
/**
* The sole purpose of this class is to start the game up. It does
this by
* creating an instance of the Game and calling it's play method.
*
* @author Maria Jump
* @version 2015.02.01
*/
publicclassMainextendsJFrameimplementsActionListener{
/** Generated unique serial unique id. */
privatestaticfinallong serialVersionUID =-
4610552759287004513L;
/** Starting dimension of the window. */
privatestaticfinalDimension WINDOW_DIMENSION;
/** The scroll pane so we can resize it when the window is resiz
ed. */
privateJScrollPane outputScrollPane;
/** The save log menu item. */
privateJMenuItem saveItem;
/** The exit menu item. */
privateJMenuItem exitItem;
/** The game instance. */
privateGame game;
/** Static block for initializing static fields. */
static{
WINDOW_DIMENSION =newDimension(500,500);
}
16. /** Default constructor. */
publicMain(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(newBorderLayout());
// Setting up the menu bar
JMenuBar menuBar =newJMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu =newJMenu("File");
menuBar.add(fileMenu);
saveItem =newJMenuItem("Save Log ...");
saveItem.addActionListener(this);
fileMenu.add(saveItem);
exitItem =newJMenuItem("Exit");
exitItem.addActionListener(this);
fileMenu.add(exitItem);
// Setting out the output area
JTextPane output =newJTextPane();
outputScrollPane =newJScrollPane(output);
Dimension outputSize =newDimension();
outputSize.setSize(WINDOW_DIMENSION.getWidth(), W
INDOW_DIMENSION.getHeight()-100);
outputScrollPane.setPreferredSize(outputSize);
// So that the scroll pane will resize when the window is resized
addComponentListener(newComponentAdapter(){
publicvoid componentResized(ComponentEvent e){
Dimension outputSize =newDimension();
outputSize.setSize(getContentPane().getWidth(), get
ContentPane().getHeight()-100);
outputScrollPane.setPreferredSize(outputSize);
}
});
add(BorderLayout.NORTH, outputScrollPane);
// Set up the Writer so that it can be used throughout the game.
Writer.setTextArea(output);
17. // Setting up the bottom panel for input
JPanel bottomPane =newJPanel();
bottomPane.setLayout(newBorderLayout());
JButton enterButton =newJButton("Enter");
JTextField commandField =newJTextField();
TextFieldStreamer streamer =newTextFieldStreamer(commandF
ield);
// maybe this next line should be done in the TextFieldStreamer
ctor
// but that would cause a "leak a this from the ctor" warning
commandField.addActionListener(streamer);
enterButton.addActionListener(streamer);
System.setIn(streamer);
bottomPane.add(BorderLayout.CENTER, commandField);
bottomPane.add(BorderLayout.EAST, enterButton);
add(BorderLayout.SOUTH, bottomPane);
setSize(WINDOW_DIMENSION);
setVisible(true);
commandField.requestFocus();
game =newGame();
game.play();
}
/**
* Default action listener.
*
* @param event
* The action event.
*/
18. @Override
publicvoid actionPerformed(ActionEvent event){
if(event.getSource()== saveItem){
Writer.copyDefaultLog();
}elseif(event.getSource()== exitItem){
System.exit(0);
}
}
/**
* The main method for the program.
*
* @param args
* The command line arguments.
*/
publicstaticvoid main(String[] args){
newMain();
}
/**
* Implementation of InputStream that uses the text from a JT
extField as the
* input buffer.
*
* @author Maria Jump
*/
privateclassTextFieldStreamerextendsInputStreamimplementsAc
tionListener{
/** The JTextField to use for input. */
privateJTextField textField;
/** The string of text that being passed as input. */
privateString text;
/** Used for checking if the available input has reached its end.
19. */
privateint position;
/**
* Default constructor for TextFieldStreamer.
*
* @param field
* JTextField component being used as input buffer
.
*/
publicTextFieldStreamer(JTextField field){
position =0;
text =null;
textField = field;
}
// gets
/**
* Invoked when an action occurs. In this case, prints the t
ext of the
* JTextField to StdOut as an error message to differentiat
e between
* user input and game output. Triggered every time that "
Enter" is
* pressed on the JTextField.
*
* Triggered every time that "Enter" is pressed on the textf
ield
*
* @param event
* ActionEvent passed by the component.
*/
@Override
publicvoid actionPerformed(ActionEvent event){
text = textField.getText()+System.getProperty("line.sep
arator");
20. position =0;
textField.setText("");
synchronized(this){
// maybe this should only notify() as multiple threads may
// be waiting for input and they would now race for input
this.notifyAll();
}
}
/**
* Reads the next byte of data from the input stream. The v
alue byte is
* returned as an <code>int</code> in the range <code>0<
/code> to
* <code>255</code>. If no byte is available because the e
nd of the
* stream has been reached, the value <code>-
1</code> is returned. This
* method blocks until input data is available, the end of th
e stream is
* detected, or an exception is thrown.
*
* <p>
* A subclass must provide an implementation of this meth
od.
*
* @return the next byte of data, or <code>-
1</code> if the end of the
* stream is reached.
* @exception IOException
* if an I/O error occurs.
*/
@Override
publicint read()throwsIOException{
int result =0xDEADBEEF;
// test if the available input has reached its end
21. // and the EOS should be returned
if(text !=null&& position == text.length()){
text =null;
// this is supposed to return -1 on "end of stream"
// but I'm having a hard time locating the constant
result = java.io.StreamTokenizer.TT_EOF;
}
if(result ==0xDEADBEEF){
// no input available, block until more is available because
// that's
// the behavior specified in the Javadocs.
while(text ==null|| position >= text.length()){
try{
// read() should block until new input is available.
synchronized(this){
this.wait();
}
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
// read an additional character, return it and increment the
// index.
result = text.charAt(position++);
}
return result;
}
}
}
CS117-S18-AlharbiMohammed-master/Player.javaCS117-S18-
AlharbiMohammed-master/Player.java
/**
* class Player.
* @author Mohammed Alharbi
22. * @version 2018.1.27
*/
publicclassPlayer{
/** field in the Player class to store the currentRoom.*/
privateRoom currentRoom;
/** constructor in the Player class.
* @param playPlayer for the room .
*/
publicPlayer(Room playPlayer){
currentRoom = playPlayer;
}
/** accessor for the current room the character.
* @return cerrentRoom
*/
publicRoom getcurrentRoom(){
return currentRoom;
}
/** a mutator for the current room the character.
* @param playing for the Room
*/
publicvoid setcurrentRoom(Room playing){
currentRoom = playing;
}
}
CS117-S18-AlharbiMohammed-master/README.md
Project: CampusOfKings-bad
Authors: Maria Jump
This project is a simple framework for an text adventure game.
In this version,
it has a few rooms and the ability for a player to walk between
these rooms.
That's all.
23. This version of the game contains some very bad class design. It
should NOT
be used as a basis for extending the project without fixing these
design
problems. It serves as an example to discuss good and bad
design.
We will fix the problems with this project through the next
couple of labs which
walk students through fixing bad design decisions and give
them an opportunity
to become familiar with the existing code.
CS117-S18-AlharbiMohammed-master/Reader.javaCS117-S18-
AlharbiMohammed-
master/Reader.javaimport java.util.ArrayList;
import java.util.Scanner;
/**
* This class is part of the "Campus of Kings" application. "Cam
pus of Kings" is a
* very simple, text based adventure game.
*
* This parser reads user input and tries to interpret it as an "Ad
venture"
* command. Every time it is called it reads a line from the term
inal and tries
* to interpret the line as a two word command. It returns the co
mmand as an
* object of class Command.
*
* The parser has a set of known command words. It checks user
input against the
24. * known commands, and if the input is not one of the known co
mmands, it returns
* a command object that is marked as an unknown command.
*
* @author Maria Jump
* @version 2017.12.18
*/
publicclassReader{
/** The source of command input. */
privatestaticScanner reader;
/**
* Create a parser to read from the terminal window.
*/
static{
reader =newScanner(System.in);
}
/**
* Returns the next command from the user.
* @return The next command from the user.
*/
publicstaticCommand getCommand(){
String inputLine;// will hold the full input line
String word1 =null;
ArrayList<String> restOfLine =null;
Writer.print("> ");// print prompt
inputLine = reader.nextLine().toLowerCase();
Writer.printInput(inputLine);
// Find up to two words on the line.
Scanner tokenizer =newScanner(inputLine);
if(tokenizer.hasNext()){
word1 = tokenizer.next();// get first word
25. if(tokenizer.hasNext()){
restOfLine =newArrayList<String>();
while(tokenizer.hasNext()){
restOfLine.add(tokenizer.next());
}
}
}
tokenizer.close();
// Now check whether this word is known. If so, create a comma
nd
// with it. If not, create a "null" command (for unknown comma
nd).
Command result =null;
if(CommandWords.isCommand(word1)){
result =newCommand(word1, restOfLine);
}
else{
result =newCommand(null, restOfLine);
}
return result;
}
/**
* Return the response to a question in all lower case.
*
* @return The response typed in by the user.
*/
publicstaticString getResponse(){
return getResponseKeepCase().toLowerCase();
}
/**
* Return the response to a question in the case used by the pl
ayer.
*
26. * @return The response typed in by the user.
*/
publicstaticString getResponseKeepCase(){
String response = reader.nextLine().trim();
Writer.printInput(response);
return response;
}
}
CS117-S18-AlharbiMohammed-master/Room.javaCS117-S18-
AlharbiMohammed-master/Room.javaimport java.util.HashMap;
/**
* Class Room - a room in an adventure game.
*
* This class is part of the "Campus of Kings" application. "Cam
pus of Kings" is a
* very simple, text based adventure game.
*
* A "Room" represents one location in the scenery of the game.
It is connected
* to other rooms via doors. The doors are labeled north, east, s
outh, west.
* For each direction, the room stores a reference to an instance
of door.
*
* @author Mohammed ALharbi
* @version 2018.1.26
*/
publicclassRoom{
/** Counter for the total number of rooms created in the world.
*/
privatestaticint counter;
/** The name of this room. Room names should be unique. */
privateString name;
/** The description of this room. */
27. privateString description;
/**earn poins */
privateint points;
/** directions hash map with directions keys and doors values *
/
privateHashMap<String,Door> directions =newHashMap<>();
/**
* Static initializer.
*/
static{
counter =0;
}
/**
* Create a room described "description". Initially, it has no e
xits.
* "description" is something like "a kitchen" or "an open cou
rt yard".
* @param name The room's name.
* @param description
* The room's description.
*/
publicRoom(String name,String description){
this.name = name;
this.description = description;
counter++;
}
/**
* Returns the name of this room.
*
* @return The name of this room.
*/
publicString getName(){
return name;
}
28. /**
* Returns the description of this room.
*
* @return The description of this room.
*/
publicString getDescription(){
return description;
}
/**
* Rerurns the door of this room.
* @return The door of this room
*/
publicDoor getDirection(String direction){
return directions.get(direction);
}
/**
* Rerutn the rooms that have been created int the world.
* @return the rooms that have been created int the world.
*/
publicstaticint getCounter(){
return counter;
}
/**
* @return getExit for getting thae direction.
* @param direction
* @return
*/
publicint getPoints(){
int point = points;
points =0;
return point;
}
29. /** Mutator for setting the points.
* @param newPoint
*/
publicvoid setPoints(int newPoints){
points = newPoints;
}
/**
* Set exit.
* @param direction
* @param neighbor
*/
publicvoid setDirection(String direction,Door neighbor){
directions.put(direction, neighbor);
}
/**
* Returns a string description including all the details of a R
oom.
*Exits : north east south west
* @return A string representing all the details of a Room.
*/
publicString toString(){
String roomInformation ="Exit";
roomInformation = getName()+" "+ getDescription();
for(String direction : directions.keySet()){
roomInformation = roomInformation +"Exit"+ direction
;
//roomInformation = "Name";
30. }
return roomInformation;
}
}
CS117-S18-AlharbiMohammed-master/World.javaCS117-S18-
AlharbiMohammed-master/World.javaimport java.util.HashMap;
/**
* This class represents the entire world that makes up the "Cam
pus of Kings"
* application. "Campus of Kings" is a very simple, text based a
dventure game.
* Users can walk around some scenery. That's all. It should real
ly be extended
* to make it more interesting!
*
* This world class creates the world where the game takes plac
e.
*
* @author mohammed alharbi
* @version 20/2/2018
*/
publicclassWorld{
/** The rooms in the world. */
privateHashMap<String,Room> rooms;
/**
* Constructor for the world.
*/
publicWorld(){
rooms =newHashMap<String,Room>();
createRooms();
31. }
/**
* This method takes care of creating all of the aspects of the
world for
* the "Campus of Kings" application.
*
* @param name
* The provided name of the room.
* @return The room associated with the provided name
*/
publicRoom getcurrentRoom(String name){
return rooms.get(name.toLowerCase());
}
/////////////////////////////////////////////////////////////////////////////////////
// Start of private helper methods
/**
* Helper method for recreating a Room. Ensure that the roo
m is created and
* installed in to the collection of Rooms.
*
* @param theRoom
* The room to add to the world.
*/
privatevoid addRoom(Room theRoom){
rooms.put(theRoom.getName().toLowerCase(), theRoom);
}
/**
* Helper method for creating doors between rooms.
*
* @param from The room where the door originated.
* @param direction The direction of the door in the from roo
m.
32. * @param to The room where the door goes.
*/
privatevoid createDoor(Room from,String direction,Room to){
Door door =newDoor(to);
from.setDirection(direction,door);
}
/**
* This method creates all of the individual places in this wor
ld and all
* the doors connecting them.
*/
privatevoid createRooms(){
// Creating all the rooms.
int pointScore =0;
Room bathroom =newRoom("Bathroom","there is teeth brush, s
hower place.");
Room kitchen =newRoom("Kitchen","there are two doors, one t
he way to go out of the house. The second door the way to the li
ving room..");
Room outOfTheHouse =newRoom("out Of The House","the way
outside the house to drive to university..");
outOfTheHouse.setPoints(10);
pointScore = pointScore +10;
Room car =newRoom("Car","inside the car, back bag, car key w
ith house key..");
car.setPoints(7);
pointScore = pointScore +7;
Room keepStreet =newRoom(" keep Street","the correct way.");
Room turnLeft =newRoom("Turn left","wrong way to go with it.
.");
Room endOfTheRoad =newRoom("End of the road","closed way
.");
Room gasStaion =newRoom("Gas Staion","the way to traffic sig
nal.");
33. Room trafficSignal =newRoom("Traffic signal","there are three
different ways.");
trafficSignal.setPoints(10);
pointScore = pointScore +10;
Room turnLeft2 =newRoom("Turn left2","maybe not the right w
ay.");
Room wrongWay =newRoom("Wrong way","it will take long ti
me to reach the goal.");
Room turnRight =newRoom("Turn right"," more traffic.");
Room closedWay =newRoom("Closed Way","no place to go.");
Room keepGoing =newRoom("KeepGoing","almost arrive to uni
versity.");
keepGoing.setPoints(10);
pointScore = pointScore +10;
Room parking =newRoom("Parking","there is a meter parking, 2
$ in Hour.");
parking.setPoints(17);
pointScore = pointScore +17;
Room library =newRoom("Library","some books, students, print
er, computers.");
Room campusCenter =newRoom("Campus Center","office for th
e activity, mailboxes, four floors");
Room hallCampus =newRoom("Hall Campus","the building for
men.");
Room hBuilding =newRoom("H Building","Five floors, elevator
, six classrooms");
Room square =newRoom("Square","the place in the middle of th
e university, and from there the player can go any building.");
square.setPoints(12);
pointScore = pointScore +12;
Room mCBuilding =newRoom("MCBuilding"," Classes, six floo
rs.");
Room aBuilding =newRoom("A Building",": the goal to reach th
e class, stairs, elevator, classroom.");
Room stairs =newRoom("Stairs","take the player until fourth flo
or.");
34. stairs.setPoints(18);
pointScore = pointScore +18;
Room elevator =newRoom("Elevator","take the player until four
th floor.");
Room floor2 =newRoom("2Floor","entry for classes");
Room classroom =newRoom("Classroom","one door, blackboard
, tables");
Room classroom201 =newRoom("Classroom201","you reach the
goal.");
classroom201.setPoints(30);
pointScore = pointScore +30;
Room classroom204 =newRoom("Classroom204","one door, stu
dents.");
Room classroom202 =newRoom("Classroom202","blackboard, t
able, students.");
// Adding all the rooms to the world.
this.addRoom(bathroom);
this.addRoom(kitchen);
this.addRoom(outOfTheHouse);
this.addRoom(car);
this.addRoom(keepStreet);
this.addRoom(turnLeft);
this.addRoom(endOfTheRoad);
this.addRoom(gasStaion);
this.addRoom(trafficSignal);
this.addRoom(turnLeft2);
this.addRoom(wrongWay);
this.addRoom(turnRight);
this.addRoom(closedWay);
this.addRoom(keepGoing);
this.addRoom(parking);
this.addRoom(library);
this.addRoom(campusCenter);
this.addRoom(hallCampus);
this.addRoom(hBuilding);
this.addRoom(square);
35. this.addRoom(mCBuilding);
this.addRoom(aBuilding);
this.addRoom(stairs);
this.addRoom(elevator);
this.addRoom(floor2);
this.addRoom(classroom);
this.addRoom(classroom201);
this.addRoom(classroom204);
this.addRoom(classroom202);
// Creating all the doors between the rooms.
this.createDoor(bathroom,"east",kitchen);
this.createDoor(kitchen,"west",bathroom);
this.createDoor(kitchen,"south", outOfTheHouse);
this.createDoor(outOfTheHouse,"north", kitchen);
this.createDoor(outOfTheHouse,"west",car);
this.createDoor(car,"east",outOfTheHouse);
this.createDoor(car,"south",keepStreet);
this.createDoor(keepStreet,"north",car);
this.createDoor(keepStreet,"west",turnLeft);
this.createDoor(turnLeft,"east",keepStreet);
this.createDoor(turnLeft,"south", endOfTheRoad);
this.createDoor(endOfTheRoad,"north",turnLeft);
this.createDoor(keepStreet,"south",gasStaion);
this.createDoor(gasStaion,"north",keepStreet);
this.createDoor(gasStaion,"east",trafficSignal);
this.createDoor(trafficSignal,"west", gasStaion);
this.createDoor(trafficSignal,"north",turnLeft2);
this.createDoor(turnLeft2,"south",trafficSignal);
38. import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
/**
* This class is a substitute for printing to standard out in our or
iginal text
* adventure game. It uses a simple console to display the messa
ges.
*
* @author Maria Jump
* @version 2016-12-18
*/
publicclassWriter{
/** System new line character. */
privatestaticfinalString NEW_LINE;
/** Name of the default log. */
privatestaticfinalString DEFAULT_LOG;
/** The text area that we will be writing to. */
privatestaticJTextPane textArea;
/** Static block. */
static{
NEW_LINE =System.getProperty("line.separator");
DEFAULT_LOG ="defaultlog.txt";
textArea =null;
restartLog();
}
39. /**
* Mutator for the text component.
*
* @param text
* The text component.
*/
publicstaticvoid setTextArea(JTextPane text){
textArea = text;
textArea.setEditable(false);
}
/**
* Print the user input in blue.
*
* @param input
* The text entered by the user.
*/
publicstaticvoid printInput(String input){
SimpleAttributeSet attributes =newSimpleAttributeSet();
StyleConstants.setForeground(attributes,Color.BLUE);
printWithAttributes(attributes, input + NEW_LINE);
}
/**
* Prints an empty line.
*/
publicstaticvoid println(){
standardPrint(NEW_LINE);
}
/**
* Prints out a single integer to a line.
*
* @param toPrint
* The integer to print.
*/
40. publicstaticvoid println(int toPrint){
String text =""+ toPrint + NEW_LINE;
standardPrint(text);
}
/**
* Prints out a single integer.
*
* @param toPrint
* The integer to print.
*/
publicstaticvoid print(int toPrint){
String text =""+ toPrint;
standardPrint(text);
}
/**
* Prints out a double to a line.
*
* @param toPrint
* The double to print.
*/
publicstaticvoid println(double toPrint){
String text =""+ toPrint + NEW_LINE;
standardPrint(text);
}
/**
* Prints out a double.
*
* @param toPrint
* The double to print.
*/
publicstaticvoid print(double toPrint){
String text =""+ toPrint;
standardPrint(text);
41. }
/**
* Prints out an object to a line.
*
* @param toPrint
* The object to print.
*/
publicstaticvoid println(Object toPrint){
String text =""+ toPrint + NEW_LINE;
standardPrint(text);
}
/**
* Prints out a object.
*
* @param toPrint
* The object to print.
*/
publicstaticvoid print(Object toPrint){
String text =""+ toPrint;
standardPrint(text);
}
/**
* Prints a string after word-
wrapping it to 80 characters if possible. Note
* that this fails to calculate correct widths if the string conta
ins tabs.
* Ends with a line return.
*
* @param toPrint
* The String to print.
*/
publicstaticvoid println(String toPrint){
String text = toPrint + NEW_LINE;
42. standardPrint(text);
}
/**
* Prints a string after word-
wrapping it to 80 characters if possible. Note
* that this fails to calculate correct widths if the string conta
ins tabs.
*
* @param toPrint
* The String to print.
*/
publicstaticvoid print(String toPrint){
standardPrint(toPrint);
}
/**
* Helper method for standard printing.
*
* @param toPrint
* The String to print.
*/
privatestaticvoid standardPrint(String toPrint){
SimpleAttributeSet attributes =newSimpleAttributeSet();
printWithAttributes(attributes, toPrint);
}
/**
* Helper method printing with attributes.
*
* @param attributes
* A set of attributes to use when printing.
* @param toPrint
* The String to print.
* @throws IllegalStateException
* If the text area has not been set and we are trying t
43. o print
* to it.
*/
privatestaticvoid printWithAttributes(SimpleAttributeSet attribu
tes,String toPrint)throwsIllegalStateException{
if(textArea ==null){
thrownewIllegalStateException("Need to set the text area before
printing to it.");
}
try{
Document document = textArea.getDocument();
document.insertString(document.getLength(), toPrint, at
tributes);
textArea.setCaretPosition(document.getLength());
BufferedWriter log =newBufferedWriter(newFileWriter(DEFAU
LT_LOG,true));
log.write(toPrint);
log.close();
}catch(BadLocationException ex){
System.err.println("ERROR: Should never get this ["+ toPrint +
"]");
System.exit(2);
}catch(IOException ex){
System.err.println("ERROR printing to default log (see instruct
or for help)");
System.exit(1);
}
}
/**
* Restart the default log.
*/
publicstaticvoid restartLog(){
try{
BufferedWriter log =newBufferedWriter(newFileWriter(DEFAU
LT_LOG,false));
44. log.close();
}catch(IOException ex){
System.err.println("ERROR resetting the default log (see instru
ctor for help)");
System.exit(1);
}
}
/**
* Copy the default log.
*/
publicstaticvoid copyDefaultLog(){
Scanner input =null;
BufferedWriter output =null;
try{
JFileChooser chooser =newJFileChooser();
chooser.setCurrentDirectory(newFile("."));
int result = chooser.showOpenDialog(null);
if(result ==JFileChooser.APPROVE_OPTION){
input =newScanner(newFile(DEFAULT_LOG));
output =newBufferedWriter(newFileWriter(chooser.g
etSelectedFile(),false));
while(input.hasNextLine()){
String line = input.nextLine();
output.write(line + NEW_LINE);
}
output.close();
input.close();
}
}catch(FileNotFoundException exception){
System.err.println("ERROR: default log file cannot be found");
System.exit(3);
}catch(IOException exception){
System.err.println("ERROR: file for copy cannot be written to")
;
System.exit(4);
45. }
}
}
CS117-S18-AlharbiMohammed-master/defaultlog.txt
Welcome to the Campus of Kings!
Campus of Kings is a new, incredibly boring adventure game.
Type 'help' if you need help.
Bathroom there is teeth brush, shower place.Exiteast :
You are in Bathroom there is teeth brush, shower place.Exiteast
Exits: > go east
Kitchen there are two doors, one the way to go out of the house.
The second door the way to the living room..ExitsouthExitwest :
You are in Kitchen there are two doors, one the way to go out of
the house. The second door the way to the living
room..ExitsouthExitwest
Exits: > go south
out Of The House the way outside the house to drive to
university..ExitnorthExitwest :
You are in out Of The House the way outside the house to drive
to university..ExitnorthExitwest
Exits: > go west
Car inside the car, back bag, car key with house
key..ExiteastExitsouth :
You are in Car inside the car, back bag, car key with house
key..ExiteastExitsouth
Exits: > go south
keep Street the correct way.ExitsouthExitnorthExitwest :
You are in keep Street the correct
way.ExitsouthExitnorthExitwest
Exits: > go east
There is no door!
> go west
Turn left wrong way to go with it..ExiteastExitsouth :
46. You are in Turn left wrong way to go with it..ExiteastExitsouth
Exits: > go east
keep Street the correct way.ExitsouthExitnorthExitwest :
You are in keep Street the correct
way.ExitsouthExitnorthExitwest
Exits: > go east
There is no door!
> go west
Turn left wrong way to go with it..ExiteastExitsouth :
You are in Turn left wrong way to go with it..ExiteastExitsouth
Exits: > go south
End of the road closed way.Exitnorth :
You are in End of the road closed way.Exitnorth
Exits: > go north
Turn left wrong way to go with it..ExiteastExitsouth :
You are in Turn left wrong way to go with it..ExiteastExitsouth
Exits: > go west
There is no door!
> go east
keep Street the correct way.ExitsouthExitnorthExitwest :
You are in keep Street the correct
way.ExitsouthExitnorthExitwest
Exits: > go east
There is no door!
> go east
There is no door!
> go south
Gas Staion the way to traffic signal.ExiteastExitnorth :
You are in Gas Staion the way to traffic
signal.ExiteastExitnorth
Exits: > go east
Traffic signal there are three different
ways.ExiteastExitsouthExitnorthExitwest :
You are in Traffic signal there are three different
ways.ExiteastExitsouthExitnorthExitwest
Exits: > go east
47. KeepGoing almost arrive to university.ExiteastExitwest :
You are in KeepGoing almost arrive to
university.ExiteastExitwest
Exits: > go east
Parking there is a meter parking, 2$ in
Hour.ExitsouthwestExitsouthExitwest :
You are in Parking there is a meter parking, 2$ in
Hour.ExitsouthwestExitsouthExitwest
Exits: > go south
Square the place in the middle of the university, and from there
the player can go any
building.ExiteastExitsouthExitnorthExitwestExitsoutheast :
You are in Square the place in the middle of the university, and
from there the player can go any
building.ExiteastExitsouthExitnorthExitwestExitsoutheast
Exits: > go south
A Building : the goal to reach the class, stairs, elevator,
classroom.ExitsouthwestExitnorthExitwest :
You are in A Building : the goal to reach the class, stairs,
elevator, classroom.ExitsouthwestExitnorthExitwest
Exits: > go south
There is no door!
> go north
Square the place in the middle of the university, and from there
the player can go any
building.ExiteastExitsouthExitnorthExitwestExitsoutheast :
You are in Square the place in the middle of the university, and
from there the player can go any
building.ExiteastExitsouthExitnorthExitwestExitsoutheast
Exits: > go east
Hall Campus the building for men.Exitwest :
You are in Hall Campus the building for men.Exitwest
Exits: > go weat
There is no door!
> go north
There is no door!
48. > go south
There is no door!
> go west
Square the place in the middle of the university, and from there
the player can go any
building.ExiteastExitsouthExitnorthExitwestExitsoutheast :
You are in Square the place in the middle of the university, and
from there the player can go any
building.ExiteastExitsouthExitnorthExitwestExitsoutheast
Exits: > go south
A Building : the goal to reach the class, stairs, elevator,
classroom.ExitsouthwestExitnorthExitwest :
You are in A Building : the goal to reach the class, stairs,
elevator, classroom.ExitsouthwestExitnorthExitwest
Exits: > go south
There is no door!
> go east
There is no door!
> go west
Stairs take the player until fourth floor.ExiteastExitsouth :
You are in Stairs take the player until fourth
floor.ExiteastExitsouth
Exits: > go west
There is no door!
> go east
A Building : the goal to reach the class, stairs, elevator,
classroom.ExitsouthwestExitnorthExitwest :
You are in A Building : the goal to reach the class, stairs,
elevator, classroom.ExitsouthwestExitnorthExitwest
Exits: > go west
Stairs take the player until fourth floor.ExiteastExitsouth :
You are in Stairs take the player until fourth
floor.ExiteastExitsouth
Exits: > go south
2Floor entry for classesExiteastExitsouthExitnorthExitsoutheast
:
49. You are in 2Floor entry for
classesExiteastExitsouthExitnorthExitsoutheast
Exits: > go southeast
Classroom201 you reach the goal.Exitnorthwest :
You are in Classroom201 you reach the goal.Exitnorthwest
Exits: > quit
I hope you weren't too bored here on the Campus of Kings!
Thank you for playing. Good bye.
You have earned 114points in 38 turns.
CS117-S18-AlharbiMohammed-master/documents/GWT.txt
///////////////////////////////////////////////////////////////////////////////
// Original commands from the game (alphabetical)
GO Scenario #1: No direction specified
GIVEN :
WHEN : "go" is entered
THEN : appropriate message is displayed (which direction?)
GO Scenario #2: No exit exists
GIVEN : there is no exit in the given direction
WHEN : "go direction" is entered
THEN : appropriate message is displayed (no door)
GO Scenario #3: Exit exists
GIVEN : there is an exit in the given direction
WHEN : "go direction" is entered
THEN : player's current room is changed to the room in the
given direction
and : the current room's points are added to the player's
score
and : player's current location is displayed
HELP Scenario #1:
GIVEN :
50. WHEN : "help" is entered
THEN : available commands are displayed
SCORE Scenario #1:
GIVEN :
WHEN : "score" is entered
THEN : player's current score is displayed
TURNS Scenario #1:
GIVEN :
WHEN : "turns" is entered
THEN : current number of turns is displayed to the screen
QUIT Scenario #1:
GIVEN :
WHEN : "quit" is entered
THEN : appropriate message is displayed (thanks for
playing)
and : program quits
///////////////////////////////////////////////////////////////////////////////
// Commands added in Stage 2 (alphabetical)
BACK Scenario #1: no previous room
GIVEN : there is no previous room
WHEN : "back" is entered
THEN : appropriate message is displayed (cannot go back)
BACK Scenario #2: there is a previous room
GIVEN : there is a previous room
WHEN : "back" is entered
THEN : player's current location is changed to the previous
location
and : player's current location is displayed
51. LOOK Scenario #1:
GIVEN :
WHEN : "look" is entered
THEN : player's current location is displayed
STATUS Scenario #1:
GIVEN :
WHEN : "status" is entered
THEN : current number of turns is displayed
and : player's current score is displayed
and : player's current location is displayed
///////////////////////////////////////////////////////////////////////////////
// Commands added in Stage 3 (alphabetical)
DROP Scenario #1: No item specified
GIVEN :
WHEN : "drop" is entered
THEN : appropriate message is displayed (which item?)
DROP Scenario #2: Player does not have the specified item
GIVEN : player does not have the specified item
WHEN : "drop item" is entered
THEN : appropriate message is displayed (you don't have it)
DROP Scenario #3: Player has the specified item
GIVEN : player has the specified item
WHEN : "drop item" is entered
THEN : "item" is removed from the player's inventory
and : "item" is added to the current room
and : appropriate message is displayed (you dropped the
item)
52. EXAMINE Scenario #1: No item specified
GIVEN :
WHEN : "examine" is entered
THEN : appropriate message is displayed (which item?)
EXAMINE Scenario #2: Specified item does not exist
GIVEN : specified item is not in the room
and : specified item is not in player's inventory
WHEN : "examine item" is entered
THEN : appropriate message is displayed (no such item)
EXAMINE Scenario #3: Specified item does exist
GIVEN : specified item is in the room or in the player's
inventory
WHEN : "examine item" is entered
THEN : complete description of the item is displayed
including the item's name, description and (optionally) the
weight.
INVENTORY Scenario #1:
GIVEN :
WHEN : "inventory" is entered
THEN : a list of the items in the players inventory is
displayed
TAKE Scenario #1: no item specified
GIVEN :
WHEN : "take" is entered
THEN : appropriate message is displayed (take what?)
53. TAKE Scenario #2: specified item does not exist
GIVEN : specified item is not in the current room
WHEN : "take item" is entered
THEN : appropriate message is displayed (no such item)
TAKE Scenario #3: specified item is too heavy to lift
GIVEN : specified item is in the current room
and : specified item by itself exceeds maximum carrying
weight
WHEN : "take item" is entered
THEN : appropriate message is displayed (too heavy to lift)
TAKE Scenario #4: specified item makes inventory too heavy
GIVEN : specified item is in the current room
and : adding specified item to inventory weight exceeds
maximum carrying weight
WHEN : "take item" is entered
THEN : appropriate message is displayed (carrying too much)
TAKE Scenario #5: specified item is taken
GIVEN : specified item is in the current room
and : adding specified item to inventory weight does not
exceed maximum carrying weight
WHEN : "take item" is entered
THEN : item is removed from the current room
and : item is added to the player's inventory
and : appropriate message is displayed (you took the item)
///////////////////////////////////////////////////////////////////////////////
// Commands added in Stage 4 (alphabetical)
GO Scenario #4: Door is locked
54. GIVEN : there is an exit in the given direction
and : that exit is locked
WHEN : "go direction" is entered
THEN : appropriate message is displayed (door is locked)
LOCK Scenario #1: No direction specified
GIVEN :
WHEN : "lock" is entered
THEN : appropriate message is displayed (lock what?)
LOCK Scenario #2: No Door
GIVEN : there is no door in that direction
WHEN : "lock direction" is entered
THEN : appropriate message is displayed (no door)
LOCK Scenario #3: Door is locked
GIVEN : door in "direction" is locked
WHEN : "lock direction" is entered
THEN : appropriate message is displayed (door is already
locked)
LOCK Scenario #4: Door cannot be locked
GIVEN : door in "direction" has no associated key
WHEN : "lock direction" is entered
THEN : appropriate message is displayed (door cannot be
locked)
LOCK Scenario #5: Door can be locked
GIVEN : door in "direction" is unlocked
and : door in "direction" can be locked
WHEN : "lock direction" is entered
THEN : user is prompted for key
LOCK Scenario #6: Player does not have the key
55. GIVEN : player does not have specific key in inventory
WHEN : "lock direction" had been entered
and : user has been prompted for specific key
THEN : appropriate message is displayed (you do not have it)
LOCK Scenario #7: Incorrect key specified
GIVEN : player's inventory has the specific key
and : specified key is not the correct key
WHEN : "lock direction" had been entered
and : user has been prompted for specific key
THEN : appropriate message is displayed (wrong key)
LOCK Scenario #8: Correct key specified
GIVEN : player's inventory has the specific key
and : specified key is the correct key
WHEN : "lock direction" had been entered
and : user has been prompted for specific key
THEN : door in "direction" is locked
and : appropriate message is displayed (you locked it)
PACK Scenario #1: No item specified
GIVEN :
WHEN : "pack" is entered
THEN : appropriate message is displayed (pack what?)
PACK Scenario #2: Item is not available
GIVEN : item is NOT in the current room
and : item is NOT in the players inventory
WHEN : "pack item" is entered
THEN : appropriate message is displayed (you don't have it)
PACK Scenario #3: Item is too heavy
56. GIVEN : item is in the current room
and : item is heavier than player's carrying capacity
WHEN : "pack item" is entered
THEN : appropriate message is displayed (too heavy)
PACK Scenario #4: Item is available
GIVEN : item is in the current room
or : item is in the player's inventory
and : there are no weight problems
WHEN : "pack item" is entered
THEN : user is prompted for the container to put it in
PACK Scenario #5: Container is not available
GIVEN : container is NOT in the current room
and : container is NOT in the player's inventory
WHEN : "pack item" had been entered
and : user has been prompted for the container
THEN : appropriate message is displayed (you don't see the
container)
PACK Scenario #6: Container is NOT a container
GIVEN : container is in the current room
or : container is in the player's inventory
and : container is not really a container
WHEN : "pack item" had been entered
and : user has been prompted for the container
THEN : appropriate message is displayed (that's not a
container)
PACK Scenario #7: Container is a container, but item too heavy
GIVEN : item is in the current room
and : container is in the player's inventory
and : item would put player over their inventory weight limit
WHEN : "pack item" had been entered
and : user has been prompted for the container
THEN : appropriate message is displayed (carrying too much)
57. PACK Scenario #8: Packing is possible
GIVEN : container is in the current room
or : container is in the player's inventory
and : container is really a container
and : there are no weight problems
WHEN : "pack item" had been entered
and : user has been prompted for the container
THEN : item is removed from the current room
or : item is removed from the player's inventory
and : item is added to the container
and : appropriate message is displayed (you packed it)
UNLOCK Scenario #1: No direction specified
GIVEN :
WHEN : "unlock" is entered
THEN : appropriate message is displayed (unlock what?)
UNLOCK Scenario #2: No door in that direction
GIVEN : there is no door in the "direction"
WHEN : "unlock direction" is entered
THEN : appropriate message is displayed (there is no door)
UNLOCK Scenario #3: Direction is specified and is not locked
GIVEN : there is a door in the "direction"
and : door in "direction" is NOT locked
WHEN : "unlock direction" is entered
THEN : appropriate message is displayed (door is not locked)
UNLOCK Scenario #4: Direction is specified and is locked
GIVEN : there is a door in the "direction"
and : door in "direction" is locked
58. WHEN : "unlock direction" is entered
THEN : user is prompted for key
UNLOCK Scenario #5: Player missing specified key
GIVEN : player's inventory does NOT have the specific key
WHEN : "unlock direction" had been entered
and : user has been prompted for specific key
THEN : appropriate message is displayed (you don't have it)
UNLOCK Scenario #6: Incorrect key
GIVEN : player's inventory has the specific key
and : specified key is incorrect item
WHEN : "unlock direction" had been entered
and : user has been prompted for specific key
THEN : appropriate message is displayed (that doesn't fit)
UNLOCK Scenario #7: Correct key
GIVEN : player's inventory has the specific key
and : specified key is the correct object
WHEN : "unlock direction" had been entered
and : user has been prompted for specific key
THEN : door in "direction" is unlocked
and : appropriate message is displayed (you unlocked it)
UNPACK Scenario #1: No container specified
GIVEN :
WHEN : "unpack" is entered
THEN : appropriate message is displayed (unpack what?)
UNPACK Scenario #2: Specified container is not in the current
room
GIVEN : specified container is NOT in the current room
59. and : specified container is NOT in the players inventory
WHEN : "unpack container" is entered
THEN : appropriate message is displayed (you don't see it)
UNPACK Scenario #3: Specified item is not a container
GIVEN : specified container is in the current room
or : specified container is in the player's inventory
and : specified container is NOT a container
WHEN : "unpack container" is entered
THEN : appropriate message is displayed (that's not a
container)
UNPACK Scenario #4: Container is OK
GIVEN : specified container is in the current room
or : specified container is in the player's inventory
and : specified container is a container
WHEN : "unpack container" is entered
THEN : user is prompted for an item to unpack
UNPACK Scenario #5: Item is NOT in container
GIVEN : item to unpack is NOT in the container
WHEN : "unpack container" had been entered
and : user has been prompted for the item to unpack
THEN : appropriate message is displayed (you don't find it)
UNPACK Scenario #6: Item is in container but too heavy
GIVEN : item to unpack is in the container
and : container was in the current room
and : item would make the player exceed his weight limit
WHEN : "unpack container" had been entered
and : user has been prompted for the item to unpack
THEN : appropriate message is displayed (you are already
carrying too much)
UNPACK Scenario #7: Item can be unpacked
GIVEN : item to unpack is in the container
60. and : there is no weight problem
WHEN : "unpack container" had been entered
and : user has been prompted for the item to unpack
THEN : item to unpack is removed from the container
and : item to unpack is added to the player's inventory
and : appropriate message is displayed (you unpack it)
CS117-S18-AlharbiMohammed-master/documents/Game name
copy.docx
Game name: Go to class
-The goal to reach the classroom201 in building A.
-there are 28 rooms until to reach the class.
- the player will lose if he goes to wrong direction and have to
bake one room to start again.
-some of the rooms have three ways, two ways, and one way.
-Player will see different ways in each room after leaving the
house.
-Items: car key, back bag, coffee.
Bathroom: there is teeth brush, shower place.
Kitchen: there are two doors, one the way to go out of the
house. The second door the way to the living room.
Out of the house: the way outside the house to drive to
university.
Car: inside the car, back bag, car key with house key.
Keep street: the correct way.
Turn left: wrong way to go with it.
End of the road: closed way.
Gas Station: the way to traffic signal.
Traffic signal: there are three different ways.
Park: maybe not the right way.
61. Wrong way: it will take long time to reach the goal.
Turn right: more traffic.
Closed way: no place to go.
Walk path: almost arrive to university.
Parking: there is a meter parking, 2$ in Hour.
Library: some books, students, printer, computers.
Campus center: office for the activity, mailboxes, four floors.
Hall campus: the building for men.
H building: Five floors, elevator, six classrooms.
Square: the place in the middle of the university, and from
there the player can go any building.
A building: the goal to reach the class, stairs, elevator,
classroom.
Stairs: take the player until fourth floor.
Elevator: take the player until fourth floor
Floor2:the pathway to the classes
Classroom: one door, blackboard, tables.
Classroom201: you reach the goal.
Classroom204:one door, students.
Classroom202: blackboard, table, students.
-Optional to earn points.
1- get a coffee.
2-snack.
3-cheek the email if the class might be canceled.
- Player need to pick up his laptop to the class.
-it will be two player, and they can carry their back bag,
cellphone, embrella.
CS117-S18-AlharbiMohammed-master/documents/Game.xml
5VxLc6M4EP41OW6KlwAfZ7KzM4edqqnKYWeOxJZtNtjyAs5j
f/2KgDDqlhNFFqDK5pAybczj6+6vu6WWrsKb3dPXMjtsv7MV
64. Player: Unspecified.
Weight limit: Unspecified.
The World : Enough rooms with some detail.
Scoring: Not specified.
Additional Stuff: Unusual features of your game.
1. Not specified.
2.
3.
TODO: As you elaborate on things, you will probably need to
find a
few more things like this.
CS117-S18-AlharbiMohammed-master/package.bluej
#BlueJ package file
dependency1.from=Reader
dependency1.to=Command
dependency1.type=UsesDependency
dependency10.from=Game
dependency10.to=World
dependency10.type=UsesDependency
dependency11.from=Game
dependency11.to=Room
dependency11.type=UsesDependency
dependency12.from=Game
dependency12.to=Command
dependency12.type=UsesDependency
69. In order to specify the commands that will be available in our
game and how the game will respond to each
command, we will use a technique from software engineering. It
is becoming more and more common in
industry to use behavior driven development (BDD) techniques
to specify how a program should behave.
The goal of behavior driven development is to develop a clear
understanding of how software behaves. It also
has the added bonus of enumerating what to test.
BDD specifies the behavior of software using scenarios and
uses a particular format. To make this
concrete, let’s look at an example:
QUIT Scenario #1:
GIVEN :
WHEN : "quit" is entered
THEN : appropriate message is displayed (thanks for playing)
and : program quits
The first thing to note is that the scenario is given a description
(“QUIT Scenario #1”) that is short enough
that it can be used to refer to when discussing the behaviors of
the command. Each scenario consists of
three parts:
• Given describes the initial context of the behavior: what is
required for this behavior to be applicable.
This part often consists of several short statements connected
with and or or. If the behavior is always
applicable, like it is for QUIT, this will be empty.
70. • When describes what event occurs that causes the behavior to
be triggered. In the case of our game,
this will almost always be some command typed at the prompt
by the user. (You can see why we think
it is a good way to describe commands in our game.)
• Then describes what happens in the game as a result of the
trigger described above. This part often
consists of several short statements connected with and or or.
Since every scenario consists of all three parts, these are often
referred to as GWTs. We will be writing
GWTs to help us specify the behavior of each of the commands
in the game. In the beginning, we will
provide GWTs for your commands. In the end, you will be
writing them yourself.
2 Exploring GWTs
To make this clearer, let us specify the other two commands
that are already implemented in our game.
With each one, run the game and see if the behavior matches
what is described:
HELP Scenario #1:
GIVEN :
WHEN : "help" is entered
THEN : available commands are displayed
Name CS117 Project Stage 02: Commands – Page 2
71. Here’s one for the “go” command:
GO Scenario #3: Exit exists
GIVEN : there is an exit in the given direction
WHEN : "go direction" is entered
THEN : player’s current room is changed to the room in the
given direction
and : the current room’s points are added to the player’s score
and : player’s current location is displayed
Notice that in this scenario the command word is followed by a
second word. We used a generic term for
the direction in the command that was issued. Many of our
commands will require multiple words. If the
player had just entered “go” without a direction, we would have
a different scenario:
GO Scenario #1: No direction specified
GIVEN :
WHEN : "go" is entered
THEN : appropriate message is displayed (which direction?)
Furthermore, if the player asks to go in a direction where there
is no exit:
GO Scenario #2: No exit exists
GIVEN : there is no exit in the given direction
72. WHEN : "go direction" is entered
THEN : appropriate message is displayed (no door)
Now the “go” command is fully specified and we can move on.
3 Implementation
The next thing we are going to do is to learn how to add
commands to your project.
3.1 Adding Your First Command
Let’s look at what it would take to add a new command to our
game: the look command. The purpose of
look is merely to print out the description of the room and exits
again. Let’s start by writing a GWT for it:
LOOK Scenario #1:
GIVEN :
WHEN : "look" is entered
THEN : player’s current location is displayed
Since look is a single word command that always succeeds, this
should be the only scenario we need.
To get started implementing look, identify all the locations in
the code that will need to be changed in
order to add a look command. How many are there?
In order to add a look command to your game you need to do
the following:
73. 1. Add look as a new command word by adding it to the array of
known words in the validCommands
array in the CommandWords class. Execute the game and type
the command look. What happens?
Name CS117 Project Stage 02: Commands – Page 3
2. Implement an action for the look command by adding a
private method in the Game class with the
following signature. For now, this method should simply call
the printLocationInformation method.
We will keep its implementation separate so that we can
enhance its functionality later.
1 /∗ ∗
2 ∗ P r i n t s o u t t h e l o c a t i o n i n f o r m a t i o n .
3 ∗ /
4 private void look()
3. Add a case for the look command in the processCommand
method of the Game class that calls the
method you wrote in part (2).
4. Test your game and be sure that your new command is
complete. One good way to do this
is go to back through all of the GTWs that have already been
specified and tested and make sure that
they all work. When you are sure that it is, commit and push
your changes.
3.2 Removing Implicit Coupling
In one of the early labs, you were asked to make improvements
to your text adventure game making it
74. possible to add additional directions of movement. The changes
you made fixed an example of explicit
coupling. The coupling was obvious because of the public fields
in the Room class. This code base also has an
even worse form of coupling: implicit coupling. Implicit
coupling is a situation when one class depends on
the internal information of another, but this dependence is not
immediately obvious. In our current game,
we notice this when we test the getting help scenario. Do you
notice that it does not include our newly
added look command? We want to fix this now.
Since the CommandWords class is responsible for the command
words, it should also be responsible for
generating a String containing all the command words that we
can then use the Game class. Let’s do this
now.
1. Add the following method to the CommandWords class:
1 /∗ ∗
2 ∗ R e t u r n s a l i s t o f t h e a v a i l a b l e commands , o f
t h e f o r m :
3 ∗ Your command w o r d s a r e :
4 ∗ l o o k g o q u i t h e l p
5 ∗
6 ∗ @ r e t u r n A s t r i n g c o n t a i n i n g t h e l i s t o f a v
a i l a b l e commands .
7 ∗ /
8 public static String getCommandString ()
2. In the Game class, when the user asks for help, we should use
this new method as part of providing
that help.
3.3 Removing String Comparison
75. To further enhance our project, we would like to remove some
of the string comparisons that our game
is currently doing. String comparisons are very inefficient and
tend to be error-prone as many beginning
(and advanced) programmers forget that they cannot use == to
compare strings. In order to do this we
need to change the CommandWords class where the valid list of
commands is stored, and the Game class
Name CS117 Project Stage 02: Commands – Page 4
where the processCommand method explicitly compares each
command word. We are going to do this using
enumerations.
Start by adding an enumeration to the project called
CommandEnum. Your enumeration should include
values for each valid command. Include a field for the text (in
all lower case) that would be entered by the
person playing the game.
Great! Now let’s refactor the game to use this new enumeration:
1. Change the implementation of validCommands from an array
of string to define valid commands to a
map between strings and CommandEnum objects. This will
make it easy to convert the command typed by
a user into its corresponding enumerated type value. You should
put the commands into the HashMap
in the static initializer of the CommandWords class. HINT: You
can do this without CommandWords
knowing what the commands are.
76. 2. Modify any methods that were using the array to now use the
map. Use the compiler to help you
identify every place that the validCommands is used.
3. Add a method to the CommandWords class which will
convert a String into a CommandEnum object. It
should have the following signature:
1 /∗ ∗
2 ∗ C o n v e r t s a S t r i n g i n t o a CommandEnum o b j e c
t .
3 ∗
4 ∗ @param t h e S t r i n g The S t r i n g c o n t a i n i n g t h
e command word .
5 ∗ @ r e t u r n The CommandEnum o b j e c t r e p r e s e n t i
n g t h e command , o r n u l l i f
t h e command d o e s n o t e x i s t .
6 ∗ /
7 public static CommandEnum getCommand(String theString)
4. Change the implementation of Command so that the
“command word” is now a CommandEnum object
instead of a String. You should change the commandWord field,
the constructors, and the accessor.
5. In the Reader class, we need to change the implementation of
the getCommand method in the Reader
to use the CommandEnum instead of a String. Be careful here
because word1 is what was entered on the
command line and must remain a String. (HINT: Didn’t you
write a method that converts a String
into a CommandEnum? You have the opportunity to simplify
some code here too.)
6. Modify the processCommand method of Game to use a switch
77. command instead of if-else statements.
When you are done, test your program to be sure that it works
the same as it did before you started
(HINT: the GWTs can help here) and then commit and push
your changes. When you do this, make
sure that the new CommandEnum.java file gets added to the
repository.
3.4 Adding More Commands
All this refactoring has left us in a great place for adding
additional commands. We have started you off by
providing GWTs that fully specify the behavior each command
in a text file in your “documents” folder.1
Implement each of the following commands using the provided
GWTs:
1Notice that this is a text file, not a Word document. You can
open this file up using gedit on the school machines. Notepad++
is a powerful text editor for Windows which you can download
and install for free from https://notepad-plus-plus.org/.
Name CS117 Project Stage 02: Commands – Page 5
Command Description
status Prints out current state of the game including the player’s
score, the number of turns that
the player has used so far, and the complete description of the
current room.
back Takes the player into the previous room he/she was in. To
78. keep it simple, your back
command only has to remember the last place the player was,
not the entire path the player
took through the game. Be sure to think about what happens if
the player enters ’back’
more than once or before moving for the first time. HINT: Why
not update the previous
room whenever the current room is updated?
4 Finishing
When you are ready double check that you have been using
good style (HINT: use Checkstyle to help you)
and that all the code you have implemented is properly
documented. Be sure that all of your changes are
commited and pushed to Github.
Instead of uploading an archive of your project, you will be
uploading a commit marker called an secure
hash algorithm (SHA). Every commit in GitHub has a SHA
marker attached to it. When you are happy
with your submission, commit and push your changes to
GitHub. Go to the GitHub website and check to
make sure your last commit has made it to the server. Now copy
the commit link by right-clicking on the
“Latest commit” and selecting “Copy Link Location” (see
figure):
Once you have copied the link, go to the submission page on
Moodle and paste it into the sub-
mission text area. The link that you get will read something
like: https://github.com/kings-cs/
CS117-S16-
JumpMaria/commit/2076ab47397891666d11a2474208f24e73fe5
76d. Don’t forget to “Submit
Assignment”.