not really known
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

491 lines
11 KiB

6 years ago
  1. /**
  2. * 1-27-18
  3. *
  4. * Main server file which handles users, rooms -- everythang
  5. */
  6. //eh?
  7. const serverUtils = require('./serverUtils.js');
  8. //used for the getting the word array
  9. const utils = require("./utils.js");
  10. //gets the trending data
  11. const trendingAPI = require("./trendsAPI.js");
  12. /**
  13. * Object used for storing rooms
  14. * @param capacityP -- the number of people that can be in room
  15. * @param pass -- the room password -- null if none
  16. * @param owner -- the person who is creating the room
  17. */
  18. var room = function(capacityP, pass, owner)
  19. {
  20. //max capacity of room -- default is 4 for now
  21. this.capacity = capacityP;
  22. //name of the room
  23. this.roomName = owner.name;
  24. //list of words used in the game
  25. //7 for now will change later to be room specific
  26. this.words = utils.getRandomWords(7);
  27. this.currentWord = this.words.pop();
  28. //list players -- so we can push requests to them
  29. this.users = [];
  30. //increments when rounds pass
  31. this.currentRound = 0;
  32. // the password of the room -- null if no password
  33. this.password = null;
  34. /**
  35. 1 = Waiting for users
  36. 2 = Word shown, Waiting for response from users
  37. 3 = Showing Result
  38. 4 = Game Over, Display Final Results
  39. */
  40. this.state = 1;
  41. /**
  42. * creates json to send in the 'roomUpdate' socket event
  43. *
  44. * {users: gameState: roundWinner: currentWord: }
  45. */
  46. this.generateRoomUpdate = function()
  47. {
  48. var result = new Object();
  49. result.users = [];
  50. this.users.forEach(function(u)
  51. {
  52. result.users.push(u.genJASON());
  53. });
  54. //sort the users based on score
  55. var countOuter = 0;
  56. var countInner = 0;
  57. var countSwap = 0;
  58. var swapped;
  59. do
  60. {
  61. countOuter++;
  62. swapped = false;
  63. for(var i = 0; i < result.users.length; i++)
  64. {
  65. countInner++;
  66. if(result.users[i].score && result.users[i + 1].score &&
  67. result.users[i].score > result.users[i + 1].score)
  68. {
  69. countSwap++;
  70. var temp = result.users[i];
  71. result.users[i] = result.users[j];
  72. result.users[j] = temp;
  73. swapped = true;
  74. }
  75. }
  76. } while(swapped);
  77. result.gameState = this.state;
  78. //sets round winner
  79. var rWinner = -1;
  80. for(var i = 0; i < this.users.length; i++)
  81. {
  82. if(rWinner < this.users[i].roundScore)
  83. {
  84. result.roundWinner = this.users[i].name;
  85. rWinner = this.users[i].roundScore;
  86. }
  87. }
  88. result.currentWord = this.currentWord;
  89. return result;
  90. }
  91. /**
  92. * grabs roomUpdate json and beams it to every user in the channel
  93. */
  94. this.sendRoomUpdate = function()
  95. {
  96. var message = this.generateRoomUpdate();
  97. this.users.forEach(function(u)
  98. {
  99. u.socket.emit('roomUpdate', message);
  100. console.log(message);
  101. });
  102. }
  103. /**
  104. * adds a user to a room
  105. * @param p
  106. * return 0 if they could join
  107. */
  108. this.addUser = function(player)
  109. {
  110. console.log("user added");
  111. //check if room is not full
  112. this.users.push(player);
  113. player.room = this;
  114. if(this.users.length == this.capacity)
  115. {
  116. this.state = 2;
  117. }
  118. console.log("rooms users");
  119. console.log(this.users);
  120. this.sendRoomUpdate();
  121. }
  122. this.addUser(owner);
  123. /**
  124. * Removes a specific user from the room and adjusts the size of the array
  125. * if the array is empty, the room closes
  126. * @param p
  127. */
  128. this.removeUser = function(p)
  129. {
  130. console.log("remove users fnc called");
  131. var temp = new Array();
  132. for(var i = 0; i < temp.length; i++)
  133. {
  134. if(p.name === this.users[i].name)
  135. {
  136. }
  137. else
  138. {
  139. temp.push(this.users[i]);
  140. }
  141. }
  142. this.users = temp;
  143. //if room is empty remove the room from rooms list
  144. if(this.users.length == 0)
  145. {
  146. delete rooms[this.roomName];
  147. }
  148. this.update();
  149. }
  150. /**
  151. * Whether or not a user can join this room -- checks for number of people are
  152. * already in the room and the password
  153. * @param p
  154. * @returns {boolean}
  155. */
  156. this.canJoin = function(p)
  157. {
  158. if(this.password == null)
  159. {
  160. return (this.users.length < this.capacity);
  161. }
  162. else
  163. {
  164. return (this.users.length < this.capacity) && (p === this.password);
  165. }
  166. }
  167. /**
  168. * starts new round for the room -- called once all the players have submitted
  169. */
  170. this.newRound = function()
  171. {
  172. if(this.words.length == 0)
  173. {
  174. this.state == 4;
  175. }
  176. else
  177. {
  178. this.currentRound++;
  179. this.users.forEach(function(u)
  180. {
  181. u.sumbission = '';
  182. });
  183. this.currentRound = this.words.pop();
  184. this.state = 2;
  185. }
  186. this.sendRoomUpdate();
  187. }
  188. //updates room variables
  189. this.update = function()
  190. {
  191. switch(this.state)
  192. {
  193. case 1: //waiting for users to join
  194. {
  195. if(this.users.length == this.capacity)
  196. {
  197. this.newRound();
  198. }
  199. break;
  200. }
  201. case 2: // waiting for responses
  202. {
  203. var flag = true;
  204. this.users.forEach(function(u)
  205. {
  206. if(u.sumbission === '')
  207. {
  208. flag = false;
  209. }
  210. });
  211. if(flag)
  212. {
  213. this.state =3;
  214. setTimeout(function() {
  215. this.newRound();
  216. }, 4000);
  217. }
  218. break;
  219. }
  220. case 3: // showing results -- time out fnc
  221. {
  222. console.log("error &&&&&&&&&&&&&&&&&&");
  223. break;
  224. }
  225. case 4: //game over display final result
  226. {
  227. break;
  228. }
  229. default:
  230. {
  231. console.log("You don goof up")
  232. }
  233. }
  234. this.sendRoomUpdate();
  235. }
  236. }
  237. var player = function(s)
  238. {
  239. //name of the user
  240. this.name = null;
  241. //players socket
  242. this.socket = s;
  243. //score of the player
  244. this.score = 0;
  245. //reference to the room -- might not need this
  246. this.room = null;
  247. //the word the user selected for current round
  248. this.sumbission = '';
  249. this.roundScore = 0;
  250. /**
  251. * generate the json object used in 'roomUpdate' socket io event
  252. *
  253. * return {name: score: word:}
  254. */
  255. this.genJASON = function()
  256. {
  257. var result = new Object();
  258. result.name = this.name;
  259. result.score = this.score;
  260. result.word = this.sumbission;
  261. }
  262. /**
  263. * data -- literally a string
  264. * @param data
  265. */
  266. this.selectWord = function(data)
  267. {
  268. this.sumbission = data;
  269. trendingAPI.getPopularity(data + " " + this.room.currentWord).then(function(result)
  270. {
  271. this.roundScore = result;
  272. this.score += result;
  273. console.log("api result for " + result);
  274. this.room.update();
  275. })
  276. }
  277. }
  278. /**
  279. * Generates json sent to user on 'sendRooms'
  280. *
  281. * return [{name: passwordBool: capacity: occupants: }]
  282. */
  283. var generateSendRoomsJSON = function()
  284. {
  285. var obj = new Object();
  286. obj.rooms = [];
  287. //rooms.forEach(function(r)
  288. Object.keys(rooms).forEach(function(key)
  289. {
  290. console.log("**************");
  291. console.log(key);
  292. if(rooms[key] != null)
  293. {
  294. var roomObj = new Object();
  295. roomObj.name = key;
  296. if(rooms[key].password == null)
  297. {
  298. roomObj.passwordBool = false;
  299. }
  300. else
  301. {
  302. roomObj.passwordBool = true;
  303. }
  304. roomObj.capacity = rooms[key].capacity;
  305. roomObj.occupants = rooms[key].users.length;
  306. obj.rooms.push(roomObj);
  307. }
  308. else
  309. {
  310. console.log("would not tough it with a 10ft pole");
  311. }
  312. });
  313. return obj;
  314. }
  315. //list of all players --accessed using names like a dic
  316. var players = {};
  317. //list of all the rooms
  318. var rooms = {};
  319. var app = require('express')();
  320. var http = require('http').Server(app);
  321. var io = require('socket.io')(http);
  322. const port = 3000;
  323. //Whenever someone connects this gets executed
  324. io.on('connection', function(socket)
  325. {
  326. var p = new player(socket);
  327. console.log('A user connected');
  328. /**
  329. *Register user nickname/handle (register) Client => Server
  330. */
  331. socket.on('register', function(data) {
  332. console.log("Register event called");
  333. console.log(data);
  334. console.log(" ");
  335. //checks for user name in use
  336. if(serverUtils.userAvailable(data, players))
  337. {
  338. p.name = data;
  339. players[data] = p;
  340. socket.emit('sendRooms', generateSendRoomsJSON());
  341. console.log("send rooms called");
  342. console.log(generateSendRoomsJSON());
  343. }
  344. else
  345. {
  346. socket.emit('registerFailed', 'User name taken');
  347. console.log("registration failed sent");
  348. }
  349. console.log(player);
  350. });
  351. /**
  352. *Create Room (createRoom) Client => Server
  353. * data {password: , capacity: }
  354. */
  355. socket.on('createRoom', function(data) {
  356. console.log("create room event called");
  357. console.log(data);
  358. console.log(" ");
  359. rooms[p.name] = new room(data.capacity, data.password, p);
  360. });
  361. /**
  362. * Room Selection (joinRoom) Client => Server
  363. * data {roomName: , password: }
  364. */
  365. socket.on('joinRoom', function(data) {
  366. console.log("join room event called");
  367. console.log(data);
  368. console.log(" ");
  369. console.log(rooms);
  370. if(rooms[data.roomName] != null && rooms[data.roomName].canJoin(data.password))
  371. {
  372. rooms[data.roomName].addUser(p);
  373. console.log("user joined room");
  374. }
  375. else
  376. {
  377. socket.emit('joinFailed', 'Failed connecting to room');
  378. }
  379. console.log(rooms);
  380. });
  381. /**
  382. * data -- literally a string
  383. */
  384. socket.on('submitWord', function(data) {
  385. console.log("submitWord called");
  386. console.log(data);
  387. console.log(" ");
  388. p.selectWord(data);
  389. });
  390. //Whenever someone disconnects
  391. socket.on('disconnect', function () {
  392. console.log('A user disconnected');
  393. if(rooms[p.name] != null)
  394. {
  395. rooms[p.name] = null;
  396. }
  397. //leave the room
  398. if(p.room != null)
  399. {
  400. p.room.removeUser(p);
  401. }
  402. //players[p.name] = null;
  403. delete players[p.name];
  404. });
  405. });
  406. http.listen(port, function() {
  407. console.log('listening on *:3000');
  408. });