forked from ericterpstra/anagrammatix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagxgame.js
279 lines (235 loc) · 8.57 KB
/
agxgame.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
var io;
var gameSocket;
/**
* This function is called by index.js to initialize a new game instance.
*
* @param sio The Socket.IO library
* @param socket The socket object for the connected client.
*/
exports.initGame = function(sio, socket){
io = sio;
gameSocket = socket;
gameSocket.emit('connected', { message: "You are connected!" });
// Host Events
gameSocket.on('hostCreateNewGame', hostCreateNewGame);
gameSocket.on('hostRoomFull', hostPrepareGame);
gameSocket.on('hostCountdownFinished', hostStartGame);
gameSocket.on('hostNextRound', hostNextRound);
// Player Events
gameSocket.on('playerJoinGame', playerJoinGame);
gameSocket.on('playerAnswer', playerAnswer);
gameSocket.on('playerRestart', playerRestart);
}
/* *******************************
* *
* HOST FUNCTIONS *
* *
******************************* */
/**
* The 'START' button was clicked and 'hostCreateNewGame' event occurred.
*/
function hostCreateNewGame() {
// Create a unique Socket.IO Room
var thisGameId = ( Math.random() * 100000 ) | 0;
// Return the Room ID (gameId) and the socket ID (mySocketId) to the browser client
this.emit('newGameCreated', {gameId: thisGameId, mySocketId: this.id});
// Join the Room and wait for the players
this.join(thisGameId.toString());
};
/*
* Two players have joined. Alert the host!
* @param gameId The game ID / room ID
*/
function hostPrepareGame(gameId) {
var sock = this;
var data = {
mySocketId : sock.id,
gameId : gameId
};
//console.log("All Players Present. Preparing game...");
io.sockets.in(data.gameId).emit('beginNewGame', data);
}
/*
* The Countdown has finished, and the game begins!
* @param gameId The game ID / room ID
*/
function hostStartGame(gameId) {
console.log('Game Started.');
sendWord(0,gameId);
};
/**
* A player answered correctly. Time for the next word.
* @param data Sent from the client. Contains the current round and gameId (room)
*/
function hostNextRound(data) {
if(data.round < wordPool.length ){
// Send a new set of words back to the host and players.
sendWord(data.round, data.gameId);
} else {
// If the current round exceeds the number of words, send the 'gameOver' event.
io.sockets.in(data.gameId).emit('gameOver',data);
}
}
/* *****************************
* *
* PLAYER FUNCTIONS *
* *
***************************** */
/**
* A player clicked the 'START GAME' button.
* Attempt to connect them to the room that matches
* the gameId entered by the player.
* @param data Contains data entered via player's input - playerName and gameId.
*/
function playerJoinGame(data) {
//console.log('Player ' + data.playerName + 'attempting to join game: ' + data.gameId );
// A reference to the player's Socket.IO socket object
var sock = this;
// Look up the room ID in the Socket.IO manager object.
var room = gameSocket.manager.rooms["/" + data.gameId];
// If the room exists...
if( room != undefined ){
// attach the socket id to the data object.
data.mySocketId = sock.id;
// Join the room
sock.join(data.gameId);
//console.log('Player ' + data.playerName + ' joining game: ' + data.gameId );
// Emit an event notifying the clients that the player has joined the room.
io.sockets.in(data.gameId).emit('playerJoinedRoom', data);
} else {
// Otherwise, send an error message back to the player.
this.emit('error',{message: "This room does not exist."} );
}
}
/**
* A player has tapped a word in the word list.
* @param data gameId
*/
function playerAnswer(data) {
// console.log('Player ID: ' + data.playerId + ' answered a question with: ' + data.answer);
// The player's answer is attached to the data object. \
// Emit an event with the answer so it can be checked by the 'Host'
io.sockets.in(data.gameId).emit('hostCheckAnswer', data);
}
/**
* The game is over, and a player has clicked a button to restart the game.
* @param data
*/
function playerRestart(data) {
// console.log('Player: ' + data.playerName + ' ready for new game.');
// Emit the player's data back to the clients in the game room.
data.playerId = this.id;
io.sockets.in(data.gameId).emit('playerJoinedRoom',data);
}
/* *************************
* *
* GAME LOGIC *
* *
************************* */
/**
* Get a word for the host, and a list of words for the player.
*
* @param wordPoolIndex
* @param gameId The room identifier
*/
function sendWord(wordPoolIndex, gameId) {
var data = getWordData(wordPoolIndex);
io.sockets.in(data.gameId).emit('newWordData', data);
}
/**
* This function does all the work of getting a new words from the pile
* and organizing the data to be sent back to the clients.
*
* @param i The index of the wordPool.
* @returns {{round: *, word: *, answer: *, list: Array}}
*/
function getWordData(i){
// Randomize the order of the available words.
// The first element in the randomized array will be displayed on the host screen.
// The second element will be hidden in a list of decoys as the correct answer
var words = shuffle(wordPool[i].words);
// Randomize the order of the decoy words and choose the first 5
var decoys = shuffle(wordPool[i].decoys).slice(0,5);
// Pick a random spot in the decoy list to put the correct answer
var rnd = Math.floor(Math.random() * 5);
decoys.splice(rnd, 0, words[1]);
// Package the words into a single object.
var wordData = {
round: i,
word : words[0], // Displayed Word
answer : words[1], // Correct Answer
list : decoys // Word list for player (decoys and answer)
};
return wordData;
}
/*
* Javascript implementation of Fisher-Yates shuffle algorithm
* http://stackoverflow.com/questions/2450954/how-to-randomize-a-javascript-array
*/
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
/**
* Each element in the array provides data for a single round in the game.
*
* In each round, two random "words" are chosen as the host word and the correct answer.
* Five random "decoys" are chosen to make up the list displayed to the player.
* The correct answer is randomly inserted into the list of chosen decoys.
*
* @type {Array}
*/
var wordPool = [
{
"words" : [ "sale","seal","ales","leas" ],
"decoys" : [ "lead","lamp","seed","eels","lean","cels","lyse","sloe","tels","self" ]
},
{
"words" : [ "item","time","mite","emit" ],
"decoys" : [ "neat","team","omit","tame","mate","idem","mile","lime","tire","exit" ]
},
{
"words" : [ "spat","past","pats","taps" ],
"decoys" : [ "pots","laps","step","lets","pint","atop","tapa","rapt","swap","yaps" ]
},
{
"words" : [ "nest","sent","nets","tens" ],
"decoys" : [ "tend","went","lent","teen","neat","ante","tone","newt","vent","elan" ]
},
{
"words" : [ "pale","leap","plea","peal" ],
"decoys" : [ "sale","pail","play","lips","slip","pile","pleb","pled","help","lope" ]
},
{
"words" : [ "races","cares","scare","acres" ],
"decoys" : [ "crass","scary","seeds","score","screw","cager","clear","recap","trace","cadre" ]
},
{
"words" : [ "bowel","elbow","below","beowl" ],
"decoys" : [ "bowed","bower","robed","probe","roble","bowls","blows","brawl","bylaw","ebola" ]
},
{
"words" : [ "dates","stead","sated","adset" ],
"decoys" : [ "seats","diety","seeds","today","sited","dotes","tides","duets","deist","diets" ]
},
{
"words" : [ "spear","parse","reaps","pares" ],
"decoys" : [ "ramps","tarps","strep","spore","repos","peris","strap","perms","ropes","super" ]
},
{
"words" : [ "stone","tones","steno","onset" ],
"decoys" : [ "snout","tongs","stent","tense","terns","santo","stony","toons","snort","stint" ]
}
]