63 lines
2.0 KiB
Java
63 lines
2.0 KiB
Java
package de.szut.zuul;
|
|
|
|
import org.java_websocket.WebSocket;
|
|
import java.util.Scanner;
|
|
|
|
/**
|
|
* 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
|
|
*/
|
|
public class Parser
|
|
{
|
|
private CommandWords commands; // holds all valid command words
|
|
|
|
/**
|
|
* Create a parser to read from the terminal window.
|
|
*/
|
|
public Parser()
|
|
{
|
|
commands = new CommandWords();
|
|
}
|
|
|
|
/**
|
|
* @return The next command from the user.
|
|
*/
|
|
public Command getCommand(String inputLine, WebSocket conn)
|
|
{
|
|
if (inputLine == null || inputLine.trim().isEmpty()) {
|
|
// Falls die Eingabe leer oder null ist, eine ungültige Eingabe zurückgeben
|
|
return new Command(null, null);
|
|
}
|
|
|
|
// Entferne führende und nachfolgende Leerzeichen und teile die Eingabe in Wörter
|
|
String[] words = inputLine.trim().split("\\s+");
|
|
|
|
String word1 = words[0]; // Das erste Wort
|
|
String word2 = words.length > 1 ? words[1] : null; // Das zweite Wort, falls vorhanden
|
|
|
|
// Jetzt prüfen, ob das erste Wort ein gültiger Befehl ist.
|
|
if (commands.isCommand(word1)) {
|
|
return new Command(word1, word2);
|
|
} else {
|
|
// Wenn der Befehl ungültig ist, ein null-Command zurückgeben
|
|
return new Command(null, word2);
|
|
}
|
|
}
|
|
public String showCommands()
|
|
{
|
|
return commands.showAll();
|
|
}
|
|
}
|