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.

501 lines
11 KiB

  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. console.log("room update called");
  100. u.socket.emit('roomUpdate', message);
  101. console.log(message);
  102. });
  103. }
  104. /**
  105. * adds a user to a room
  106. * @param p
  107. * return 0 if they could join
  108. */
  109. this.addUser = function(player)
  110. {
  111. console.log("user added");
  112. //check if room is not full
  113. this.users.push(player);
  114. player.room = this;
  115. if(this.users.length == this.capacity)
  116. {
  117. this.state = 2;
  118. }
  119. console.log("rooms users");
  120. console.log(this.users);
  121. this.sendRoomUpdate();
  122. }
  123. this.addUser(owner);
  124. /**
  125. * Removes a specific user from the room and adjusts the size of the array
  126. * if the array is empty, the room closes
  127. * @param p
  128. */
  129. this.removeUser = function(p)
  130. {
  131. console.log("remove users fnc called");
  132. var temp = new Array();
  133. for(var i = 0; i < temp.length; i++)
  134. {
  135. if(p.name === this.users[i].name)
  136. {
  137. }
  138. else
  139. {
  140. temp.push(this.users[i]);
  141. }
  142. }
  143. this.users = temp;
  144. //if room is empty remove the room from rooms list
  145. if(this.users.length == 0)
  146. {
  147. delete rooms[this.roomName];
  148. }
  149. this.update();
  150. }
  151. /**
  152. * Whether or not a user can join this room -- checks for number of people are
  153. * already in the room and the password
  154. * @param p
  155. * @returns {boolean}
  156. */
  157. this.canJoin = function(p)
  158. {
  159. if(this.password == null)
  160. {
  161. return (this.users.length < this.capacity);
  162. }
  163. else
  164. {
  165. return (this.users.length < this.capacity) && (p === this.password);
  166. }
  167. }
  168. /**
  169. * starts new round for the room -- called once all the players have submitted
  170. */
  171. this.newRound = function()
  172. {
  173. if(this.words.length == 0)
  174. {
  175. this.state == 4;
  176. }
  177. else
  178. {
  179. this.currentRound++;
  180. this.users.forEach(function(u)
  181. {
  182. u.sumbission = '';
  183. });
  184. this.currentRound = this.words.pop();
  185. this.state = 2;
  186. }
  187. this.sendRoomUpdate();
  188. }
  189. //updates room variables
  190. this.update = function()
  191. {
  192. switch(this.state)
  193. {
  194. case 1: //waiting for users to join
  195. {
  196. if(this.users.length == this.capacity)
  197. {
  198. this.newRound();
  199. }
  200. break;
  201. }
  202. case 2: // waiting for responses
  203. {
  204. var flag = true;
  205. this.users.forEach(function(u)
  206. {
  207. if(u.sumbission === '')
  208. {
  209. flag = false;
  210. }
  211. });
  212. if(flag)
  213. {
  214. this.state =3;
  215. setTimeout(function() {
  216. this.newRound();
  217. }, 4000);
  218. }
  219. break;
  220. }
  221. case 3: // showing results -- time out fnc
  222. {
  223. console.log("error &&&&&&&&&&&&&&&&&&");
  224. break;
  225. }
  226. case 4: //game over display final result
  227. {
  228. break;
  229. }
  230. default:
  231. {
  232. console.log("You don goof up")
  233. }
  234. }
  235. this.sendRoomUpdate();
  236. }
  237. }
  238. var player = function(s)
  239. {
  240. //name of the user
  241. this.name = null;
  242. //players socket
  243. this.socket = s;
  244. //score of the player
  245. this.score = 0;
  246. //reference to the room -- might not need this
  247. this.room = null;
  248. //the word the user selected for current round
  249. this.sumbission = '';
  250. this.roundScore = 0;
  251. /**
  252. * generate the json object used in 'roomUpdate' socket io event
  253. *
  254. * return {name: score: word:}
  255. */
  256. this.genJASON = function()
  257. {
  258. var result = new Object();
  259. result.name = this.name;
  260. result.score = this.score;
  261. result.word = this.sumbission;
  262. return result;
  263. }
  264. /**
  265. * data -- literally a string
  266. * @param data
  267. */
  268. this.selectWord = function(data)
  269. {
  270. this.sumbission = data;
  271. trendingAPI.getPopularity(data + " " + this.room.currentWord).then(function(result)
  272. {
  273. this.roundScore = result;
  274. this.score += result;
  275. console.log("api result for " + result);
  276. this.room.update();
  277. })
  278. }
  279. }
  280. /**
  281. * Generates json sent to user on 'sendRooms'
  282. *
  283. * return [{name: passwordBool: capacity: occupants: }]
  284. */
  285. var generateSendRoomsJSON = function()
  286. {
  287. var obj = new Object();
  288. obj.rooms = [];
  289. //rooms.forEach(function(r)
  290. Object.keys(rooms).forEach(function(key)
  291. {
  292. console.log("**************");
  293. console.log(key);
  294. if(rooms[key] != null)
  295. {
  296. var roomObj = new Object();
  297. roomObj.name = key;
  298. if(rooms[key].password == null)
  299. {
  300. roomObj.passwordBool = false;
  301. }
  302. else
  303. {
  304. roomObj.passwordBool = true;
  305. }
  306. roomObj.capacity = rooms[key].capacity;
  307. roomObj.occupants = rooms[key].users.length;
  308. obj.rooms.push(roomObj);
  309. }
  310. else
  311. {
  312. console.log("would not tough it with a 10ft pole");
  313. }
  314. });
  315. return obj;
  316. }
  317. //list of all players --accessed using names like a dic
  318. var players = {};
  319. //list of all the rooms
  320. var rooms = {};
  321. var app = require('express')();
  322. var http = require('http').Server(app);
  323. var io = require('socket.io')(http);
  324. const port = 3000;
  325. app.get('/', function(req, res)
  326. {
  327. console.log("err");
  328. res.sendfile('index.html');
  329. });
  330. //Whenever someone connects this gets executed
  331. io.on('connection', function(socket)
  332. {
  333. var p = new player(socket);
  334. console.log('A user connected');
  335. /**
  336. *Register user nickname/handle (register) Client => Server
  337. */
  338. socket.on('register', function(data) {
  339. console.log("Register event called");
  340. console.log(data);
  341. console.log(" ");
  342. //checks for user name in use
  343. if(serverUtils.userAvailable(data, players))
  344. {
  345. p.name = data;
  346. players[data] = p;
  347. socket.emit('sendRooms', generateSendRoomsJSON());
  348. console.log("send rooms called");
  349. console.log(generateSendRoomsJSON());
  350. }
  351. else
  352. {
  353. socket.emit('registerFailed', 'User name taken');
  354. console.log("registration failed sent");
  355. }
  356. console.log(player);
  357. });
  358. /**
  359. *Create Room (createRoom) Client => Server
  360. * data {password: , capacity: }
  361. */
  362. socket.on('createRoom', function(data) {
  363. console.log("create room event called");
  364. console.log(data);
  365. console.log(" ");
  366. rooms[p.name] = new room(data.capacity, data.password, p);
  367. });
  368. /**
  369. * Room Selection (joinRoom) Client => Server
  370. * data {roomName: , password: }
  371. */
  372. socket.on('joinRoom', function(data) {
  373. console.log("join room event called");
  374. console.log(data);
  375. console.log(" ");
  376. console.log(rooms);
  377. if(rooms[data.roomName] != null && rooms[data.roomName].canJoin(data.password))
  378. {
  379. rooms[data.roomName].addUser(p);
  380. console.log("user joined room");
  381. }
  382. else
  383. {
  384. socket.emit('joinFailed', 'Failed connecting to room');
  385. }
  386. console.log(rooms);
  387. });
  388. /**
  389. * data -- literally a string
  390. */
  391. socket.on('submitWord', function(data) {
  392. console.log("submitWord called");
  393. console.log(data);
  394. console.log(" ");
  395. p.selectWord(data);
  396. });
  397. //Whenever someone disconnects
  398. socket.on('disconnect', function () {
  399. console.log('A user disconnected');
  400. if(rooms[p.name] != null)
  401. {
  402. rooms[p.name] = null;
  403. }
  404. //leave the room
  405. if(p.room != null)
  406. {
  407. p.room.removeUser(p);
  408. }
  409. //players[p.name] = null;
  410. delete players[p.name];
  411. });
  412. });
  413. http.listen(port, function() {
  414. console.log('listening on *:3000');
  415. });