-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
117 lines (96 loc) · 2.41 KB
/
game.js
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const { Field } = require("./field");
// Import the text for the game.
const messages = require("./messages.js");
const gameMessage = messages.gameMessage;
const collisionMessage = messages.collisionMessage;
const promptSync = require("prompt-sync")({ sigint: true });
const prompt = (ask = "> ", value, opts) => promptSync(ask, value, opts);
class Game {
constructor() {
this.field = new Field();
}
play() {
this.displayHelp();
}
displayHelp() {
console.log(gameMessage["Help"]);
prompt();
// Return to game screen when user presses enter
this.updateGameDisplay();
}
updateGameDisplay() {
this.updateFieldDisplay();
const userInput = this.promptUser();
this.mapUserInputToState(userInput);
}
updateFieldDisplay() {
console.clear();
console.log(gameMessage["Title"]);
this.field.display();
}
promptUser() {
console.log(gameMessage["Prompt"]);
return prompt();
}
mapUserInputToState(userInput) {
const isMoveCommand = ["l", "r", "u", "d"].includes(userInput);
const isHelpCommand = userInput === "h";
const isExitCommand = userInput === "x";
if (isMoveCommand) {
this.move(userInput);
} else if (isHelpCommand) {
this.displayHelp();
} else if (isExitCommand) {
this.exitGame();
} else {
this.updateGameDisplay();
}
}
exitGame() {
console.clear();
console.log(gameMessage["Exit"]);
}
move(userInput) {
this.field.movePlayer(userInput);
this.checkForCollision();
}
checkForCollision() {
const collision = this.field.collision;
if (collision === "None") {
this.updateGameDisplay();
} else {
this.gameOver(collision);
}
}
gameOver(collision) {
this.updateFieldDisplay();
this.displayCollision(collision);
this.promptToPlayAgain();
}
displayCollision(collision) {
const message = collisionMessage[collision];
console.log(message);
console.log(gameMessage["Game Over"]);
}
promptToPlayAgain() {
const playAgain = prompt().toLowerCase();
const yes = playAgain === "y";
const no = playAgain === "n";
if (yes) {
this.restartGame();
} else if (no) {
this.exitGame();
} else {
this.gameOver();
}
}
restartGame() {
this.field = new Field();
this.updateGameDisplay();
}
}
module.exports.Game = Game;
if (require.main === module) {
const game = new Game();
game.play();
}