-
Notifications
You must be signed in to change notification settings - Fork 2
/
game.js
227 lines (211 loc) · 6.8 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
const games = {};
const moment = require("moment");
const { v4: uuidv4 } = require("uuid");
const { getTriviaQuestions } = require("./services");
const { shuffle } = require("./helpers");
const createGame = async (id) => {
let questions = [];
try {
const data = await getTriviaQuestions(5);
questions = await data.map((question) => {
const options = [...question.incorrect_answers, question.correct_answer];
shuffle(options);
const optionObjArray = options.map((opt, index) => {
return {
id: index + 1,
payload: opt,
};
});
return {
id: uuidv4(),
payload: question.question,
answerID: optionObjArray.find(
(opt) => opt.payload === question.correct_answer
).id,
options: optionObjArray,
};
});
// Parse data
} catch (err) {
console.log(err);
throw new Error(err.message || "Get trivia questions failed");
}
games[id] = {
status: "pending",
players: [],
questionRoundStatus: "not-started",
currentQuestionNo: 1,
questions: questions,
};
};
const addPlayer = ({ id, name, room }) => {
if (games[room] !== undefined) {
games[room].players.push({
id,
name,
isReady: false,
answers: {},
score: 0,
});
}
return { error: "Game not found" };
};
const disconnectPlayer = ({ id, room }) => {
if (games[room] !== undefined) {
const newPlayerList = [...games[room].players];
const existingPlayer = games[room].players.findIndex(
(player) => player.id === id
);
if (existingPlayer !== -1) {
newPlayerList.splice(existingPlayer, 1);
games[room].players = newPlayerList;
}
return { error: "Player not found" };
}
return { error: "Game not found" };
};
// Game loop that controls the flow & updating of game state
const gameLoop = async (
{ room },
updateLeaderboardEmitter,
updateGameStateEmitter
) => {
const roundStartTransitionDuration = 5000; // in milliseconds
const roundEndTransitionDuration = 8000; // in milliseconds
const roundDuration = 10000; // in milliseconds
let currentQuestion = games[room].currentQuestionNo;
const questions = games[room].questions;
updateGameStatus(room, "started");
while (currentQuestion <= games[room].questions.length) {
updateQuestionRoundStatus(room, "pending");
games[room].duration = roundStartTransitionDuration;
updateGameStateEmitter(games[room], room);
await new Promise((resolve) =>
setTimeout(resolve, roundStartTransitionDuration)
);
updateQuestionRoundStatus(room, "started");
// TODO: Socket Emit event to update game state, sending game status & question and options
games[room].duration = roundDuration;
const momentRoundStarted = moment().format();
updateGameStateEmitter(games[room], room);
await new Promise((resolve) => setTimeout(resolve, roundDuration));
updateQuestionRoundStatus(room, "ended");
// Update player scores
const newPlayersList = [...games[room].players];
games[room].players = newPlayersList.map((player) => {
const currentQuestionID = questions[currentQuestion - 1].id;
const playerAnswer = player.answers[currentQuestionID];
if (playerAnswer !== undefined) {
if (playerAnswer.answerID === questions[currentQuestion - 1].answerID) {
// Score Calculation
const maxPoints = 1000;
const responseTime = moment(playerAnswer.answeredAt).diff(
moment(momentRoundStarted),
"seconds"
);
const responseRatio = responseTime / (roundDuration / 1000);
const score = (1 - responseRatio / 2) * maxPoints;
return {
...player,
score: player.score + Math.round(score),
};
}
}
return player;
});
updateLeaderboardEmitter(games[room].players, room);
// TODO: Socket Emit event to update game state, sending game status, correct answer & updated leaderboard
games[room].duration = roundEndTransitionDuration;
updateGameStateEmitter(games[room], room);
await new Promise((resolve) =>
setTimeout(resolve, roundEndTransitionDuration)
);
// if (currentQuestion < games[room].questions.length) {
// updateQuestionRoundStatus(room, "pending");
// // TODO: Socket Emit event to update game state
// updateGameStateEmitter(games[room], room);
// }
currentQuestion += 1;
games[room].currentQuestionNo = currentQuestion;
}
updateGameStatus(room, "ended");
// TODO: Socket Emit event to update game state
updateGameStateEmitter(games[room], room);
// TODO: Remove game room since game has ended
delete games[room];
};
const updateGameStatus = (room, newStatus) => {
if (games[room] !== undefined) {
games[room].status = newStatus;
}
};
const updateQuestionRoundStatus = (room, newQuestionRoundStatus) => {
if (games[room] !== undefined) {
games[room].questionRoundStatus = newQuestionRoundStatus;
}
};
const updatePlayerReadyStatus = ({ id, name, room }) => {
if (games[room] !== undefined) {
const newPlayersList = [...games[room].players];
const existingUser = newPlayersList.findIndex((user) => user.id === id);
if (existingUser !== -1) {
newPlayersList[existingUser] = {
...newPlayersList[existingUser],
isReady: true,
};
games[room].players = newPlayersList;
// Check if all players in game room are ready
const notReadyUser = games[room].players.find(
(user) => user.isReady === false
);
if (notReadyUser === undefined) {
// Set game status to started
updateGameStatus(room, "started");
updateQuestionRoundStatus(room, "pending");
}
return { game: games[room] };
}
return { error: "Player id not found" };
}
return { error: "Game not found" };
};
const updatePlayerAnswer = ({
id,
name,
room,
questionID,
answerID,
momentAnswered,
}) => {
// TODO: Add validation for questionID to check if answer submitted is for current question
if (games[room] !== undefined) {
const newPlayersList = [...games[room].players];
const existingUser = newPlayersList.findIndex((user) => user.id === id);
if (existingUser !== -1) {
newPlayersList[existingUser].answers[questionID] = {
answerID,
answeredAt: momentAnswered,
};
games[room].players = newPlayersList;
return { game: games[room] };
}
return { error: "Player id not found" };
}
return { error: "Game not found" };
};
const getGameByID = (id) => {
if (games[id] !== undefined) {
return { game: games[id] };
}
return { error: "Game not found" };
};
const removeEndedGame = () => {};
module.exports = {
createGame,
addPlayer,
disconnectPlayer,
updatePlayerReadyStatus,
updatePlayerAnswer,
getGameByID,
gameLoop,
};