import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
/**
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game.
*
* This parser reads user input and tries to interpret it as an "Adventure"
* 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
* as an object of class Command.
*
* 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
* returns a command object that is marked as an unknown command.
*
* @author Michael Kölling and David J. Barnes
* @version 2016.02.29
* @author Charles Cusack (added ability to use file as input)
* @version 4/10/2024
*/
public class Parser
{
private CommandWords commands; // holds all valid command words
private Scanner reader; // source of command input
private boolean isFileInput=false; // reading from a file?
/**
* Create a parser to read from the terminal window.
*/
public Parser()
{
commands = new CommandWords();
reader = new Scanner(System.in);
}
/**
* Create a parser from a file.
*/
public Parser(String filename) {
commands = new CommandWords();
try {
reader = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
System.out.println("Cannot find the file "+filename);
System.out.println("Reverting to use the command line for input.");
reader = new Scanner(System.in);
} catch (IOException e) {
System.out.println("Error with File I/O:");
e.printStackTrace();
System.out.println("Reverting to use the command line for input.");
reader = new Scanner(System.in);
}
isFileInput=true;
}
/**
* @return true if the input is from a file and false if it is from std.in.
*/
public boolean usingFile() {
return isFileInput;
}
/**
* @return The next command from the user.
*/
public Command getCommand()
{
String inputLine; // will hold the full input line
System.out.print("> "); // print prompt
inputLine = reader.nextLine();
return parseLine(inputLine);
}
/**
* Parse a single line of input.
*/
public Command parseLine(String line) {
if(line==null || line.length()<1) {
return new Command(null,null);
}
String word1 = null;
String word2 = null;
String[] parts = line.split("#");
if(parts.length<1) {
return new Command(null,null);
}
String[] words = parts[0].trim().split(" ");
if(words.length<1) {
return new Command(null,null);
} else if(words.length==1) {
return new Command(words[0],null);
} else {
return new Command(words[0],words[1]);
}
}
/**
* Print out a list of valid command words.
*/
public void showCommands()
{
System.out.println(commands.getCommandList());
}
}