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.

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