-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameEngine.java
More file actions
98 lines (83 loc) · 3 KB
/
GameEngine.java
File metadata and controls
98 lines (83 loc) · 3 KB
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
90
91
92
93
94
95
96
97
98
import java.util.Scanner;
public class GameEngine {
// ATTRIBUTES
private final Scanner scanner;
private final String user;
private Game game;
// CONSTRUCTOR
public GameEngine(String user, Scanner scanner) {
this.user = user;
this.scanner = scanner;
}
// GETTERS AND SETTERS
public Scanner getScanner() { return scanner; }
public String getUser() { return user; }
public Game getGame() { return game; }
public void setGame(Game game) { this.game = game; }
// OPERATIONS
public Game chooseGame() {
System.out.println("===================================================\n");
System.out.println("MAIN MENU:");
System.out.println(" 1. GAME: Memory (1 Player)");
System.out.println(" 2. GAME: Connect Four (2 Players)");
System.out.println(" 3. Logout");
System.out.println(" 4. Quit Program\n");
int chosenGame = this.parseGameInput(1,4);
switch (chosenGame) {
case 3:
return null;
case 4:
this.quitProgram();
return null; // if correct, should never run
default:
System.out.println("\n===================================================\n");
this.getGameInstance(chosenGame);
}
return this.getGame();
}
public void runGame() {
this.getGame().gameLoop(this.getScanner());
}
public void quitProgram() {
System.out.println("\n===================================================");
System.out.println("\nGoodbye!\n");
System.out.println("Program shutting down...!\n");
this.getScanner().close();
System.exit(0);
}
// HELPER FUNCTIONS
private void getGameInstance(int gameNum) {
if (this.getGame() != null) {
this.setGame(null);
}
switch (gameNum) {
case 1:
this.setGame(Memory.getInstance());
break;
case 2:
this.setGame(ConnectFour.getInstance());
break;
}
}
private String getUserInput(String prompt) {
System.out.print(">> " + prompt);
return this.getScanner().nextLine();
}
private int parseGameInput(int minChoices, int maxChoices) {
int inputNum = -1;
boolean isValidInput = false;
do {
String chosenGame = getUserInput("Choose an option: ");
try {
inputNum = Integer.parseInt(chosenGame);
isValidInput = inputNum <= maxChoices && inputNum >= minChoices;
if (!isValidInput) {
System.out.println("ERROR: Please enter a number between " + minChoices + " and " + maxChoices + ".");
}
} catch (NumberFormatException e) {
System.out.println("ERROR: Invalid input. Please enter a valid number.");
}
} while (!isValidInput);
return inputNum;
}
}