-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommandFactory.java
89 lines (80 loc) · 2.65 KB
/
CommandFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package bork;
import java.util.List;
import java.util.Arrays;
/**
* A singleton class whose main function is to parse commands and create a new
* command object of the correct type.
*
* @author Dr. Zeitz
*/
public class CommandFactory {
private static CommandFactory theInstance;
public static List<String> MOVEMENT_COMMANDS =
Arrays.asList("n","w","e","s","u","d" );
public static List<String> LIGHT_COMMANDS = Arrays.asList("on", "off");
/**
* A method that creates a CommandFactory instance or gets the instance if
* it already exists.
* @return the CommandFactory instance
*/
public static synchronized CommandFactory instance() {
if (theInstance == null) {
theInstance = new CommandFactory();
}
return theInstance;
}
/**
* Default CommandFactory constructor.
*/
private CommandFactory() {
}
/**
* Parses the string from the user and creates the correct Command object.
* @param command the command string entered by the user
* @return a new Command object of the correct type
*/
public Command parse(String command) {
try {
GameState.instance().reduceFuelOfActiveLightSources();
} catch (LightSource.NoActiveLightSourceException ex) {}
String parts[] = command.split(" ");
String verb = parts[0];
String noun = parts.length >= 2 ? parts[1] : "";
if (verb.equals("save")) {
return new SaveCommand(noun);
}
if (verb.equals("take")) {
return new TakeCommand(noun);
}
if (verb.equals("drop")) {
return new DropCommand(noun);
}
if (verb.equals("i") || verb.equals("inventory")) {
return new InventoryCommand();
}
if (MOVEMENT_COMMANDS.contains(verb)) {
return new MovementCommand(verb);
}
if (verb.equals("health")) {
return new HealthCommand();
}
if (verb.equals("score")) {
return new ScoreCommand();
}
if (verb.equals("attack") && command.contains("with") && (parts.length == 4))
{
return new AttackCommand(parts[3], parts[1]);
}
if (verb.equals("turn") && LIGHT_COMMANDS.contains(parts[2]) && (parts.length == 3)) {
return new ToggleLightCommand(parts[1], parts[2]);
}
if (parts.length == 2) {
return new ItemSpecificCommand(verb, noun);
}
if (verb.equals("look"))
{
return new LookCommand();
}
return new UnknownCommand(command);
}
}