-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroom.js
220 lines (190 loc) · 5.72 KB
/
room.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
// Question model for the database
const Question = require("./models/question.model");
// shuffle function from the lodash module
// Runtime complexity O(n)
// Not an in place function
const shuffle = require("lodash.shuffle");
const TIMER = 10; // Temporarily hard coded
const TIME_TO_QUESTION = 3;
class Room {
/**
*
* @param {} roomSocket
* @param {Object} users
* @param {String} category
* @param {Integer} questionNumber
* @param {Object} languages
* {
* "from" : "en",
* "to" : "tr"
* }
*/
constructor(roomId, roomSocket, users, category, questionNumber, languages) {
this.roomId = roomId;
this.roomSocket = roomSocket;
/*
{
socket: user
}
*/
this.users = users;
this.category = category;
this.questionNumber = questionNumber;
this.choiceNumber = 4; // How many choices in a question
this.languages = languages;
// Create a map [[socket1, false], [socket2, false]]
this.isReady = new Map();
this.isAnswered = new Map();
this.scoreboard = new Map();
this.currentQuestion = 0; // Question index
this.timer = TIMER;
this.isActive = true;
this.users.forEach( (user, socket) => {
this.isReady.set(socket, false);
this.isAnswered.set(socket, false);
this.scoreboard.set(user, 0);
});
}
// Fetch the words and generate questions
init = async () => {
try {
this.words = await this.getWords();
// Choose the question words
this.questionOrder = shuffle(this.words);
// Start Game
this.startGame();
} catch (err) {
// Handle database errors
console.log(err)
}
}
// Fetch the words from database
getWords = async () => {
return Question.find({category: this.category}, `id ${this.languages.from} ${this.languages.to}`)
.then((words) => {
return words;
})
.catch((err) => {
console.log(err);
})
}
// Get the current question prompt
getCurrentPromt = () => {
return this.questionOrder[this.currentQuestion][this.languages.from];
}
// Generate 3 other choices
generateChoices = (question) => {
return shuffle([
question,
...shuffle(this.words.filter((word) => word !== question)).slice(0, this.choiceNumber - 1)
]).map((word) => ({
label: word[this.languages.to],
id: word._id
}));
}
// Generate the complete question
generateQuestion = () => {
return {
prompt: this.getCurrentPromt(),
choices: this.generateChoices(this.questionOrder[this.currentQuestion]),
'current-question' : this.currentQuestion
}
}
startGame = () => {
const usersArray = [];
this.users.forEach( (val, key) => usersArray.push(val.username));
this.timer = TIMER;
this.currentQuestion = 0;
console.log(`[START GAME] Game starting between ${usersArray[0]} and ${usersArray[1]}`);
this.roomSocket.emit("START GAME", {
roomId: this.roomId,
questionNumber: this.questionNumber,
users: usersArray,
timer: this.timer
});
}
// Set ready for a user
userReady = (user) => {
this.isReady.set(user, true);
}
// Checks if the game is ready to start
checkReady = () => {
return [...this.isReady.values()].every((state) => state);
}
// Send a question
sendQuestion = () => {
const question = this.generateQuestion();
this.roomSocket.emit("NEW QUESTION", {
roomId: this.roomId,
...question
});
console.log("[NEW QUESTION]", question);
this.isTimeUp = false;
this.timeout = setTimeout(this.timeUp, this.timer * 1000);
}
timeUp = () => {
this.isTimeUp = true;
this.checkAnswer();
}
checkAnswer = (socket, answer) => {
const correctAnswer = this.questionOrder[this.currentQuestion].id;
this.isAnswered.set(socket, true);
// Check if both users answered
if ([...this.isAnswered.values()].every((answered) => answered ) || this.isTimeUp) {
if (this.isTimeUp) {
console.log('[TIME UP]')
}
console.log(`[END QUESTION] Correct Answer: ${correctAnswer}`);
this.roomSocket.emit("END QUESTION", {
roomId: this.roomId,
'correct-answer' : correctAnswer,
'timeout': this.isTimeUp
});
this.users.forEach( (user, socket) => this.isAnswered.set(socket, false));
this.currentQuestion++;
this.scoreboard.set(this.users.get(socket), this.scoreboard.get(this.users.get(socket) + 1));
// FIXME: Bazen eğer cevabı iki kişi de zaman bitmeden verdiyse clear'lamıyor!
clearTimeout(this.timeout);
this.nextQuestion();
}
// console.log(this.users.get(socket).username);
}
nextQuestion = () => {
if (this.currentQuestion === this.questionNumber || !this.isActive) {
// END GAME
setTimeout(this.endGame, TIME_TO_QUESTION * 1000);
} else {
// NEXT QUESTION
setTimeout(this.sendQuestion, TIME_TO_QUESTION * 1000);
}
}
/*
SCOREBOARD
{
'kaan' : 5,
'sahircan' : 10
}
*/
endGame = (disconnectedSocket) => {
let winner;
let isDisconnected = false;
console.log("[END GAME]");
if (disconnectedSocket) {
const disconnectedUser = this.users[disconnectedSocket];
winner = Array.from(this.users.values()).filter(user => user !== disconnectedUser);
isDisconnected = true;
} else {
winner = [...this.scoreboard.entries()].reduce((a, e) => e[1] > a[1] ? e : a)[0];
}
this.roomSocket.emit("END GAME", {
roomId: this.roomId,
scoreboard : Object.fromEntries(this.scoreboard.entries()),
winner : winner,
isDisconnected : isDisconnected
});
this.currentQuestion = 0;
this.isActive = false;
clearTimeout(this.timeout);
}
}
module.exports = { Room }