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.

538 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. 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. //sqlStuff.dumpRoom(this);
  229. break;
  230. }
  231. default:
  232. {
  233. console.log("You don goof up")
  234. }
  235. }
  236. this.sendRoomUpdate();
  237. }
  238. this.addUser(owner);
  239. }
  240. var player = function(s)
  241. {
  242. //name of the user
  243. this.name = null;
  244. //players socket
  245. this.socket = s;
  246. //score of the player
  247. this.score = 0;
  248. //reference to the room -- might not need this
  249. this.room = null;
  250. //the word the user selected for current round
  251. this.sumbission = '';
  252. this.roundScore = 0;
  253. //logs the user data so we can record it to data base at end of round
  254. this.log = [];
  255. /**
  256. * generate the json object used in 'roomUpdate' socket io event
  257. *
  258. * return {name: score: word:}
  259. */
  260. this.genJASON = function()
  261. {
  262. var result = new Object();
  263. result.name = this.name;
  264. result.score = this.score;
  265. result.word = this.sumbission;
  266. return result;
  267. }
  268. /**
  269. * data -- literally a string
  270. * @param data
  271. */
  272. this.selectWord = function(data)
  273. {
  274. this.sumbission = data;
  275. var w = data + " " + this.room.currentWord;
  276. trendingAPI.getPopularity(w).then(function(result)
  277. {
  278. var obj = new Object();
  279. obj.word = w;
  280. obj.score = result;
  281. this.log.push(obj);
  282. this.roundScore = result;
  283. this.score += result;
  284. console.log("api result for " + result);
  285. this.room.update();
  286. })
  287. }
  288. }
  289. /**
  290. * Generates json sent to user on 'sendRooms'
  291. *
  292. * return [{name: passwordBool: capacity: occupants: }]
  293. */
  294. var generateSendRoomsJSON = function()
  295. {
  296. var obj = new Object();
  297. obj.rooms = [];
  298. //rooms.forEach(function(r)
  299. Object.keys(rooms).forEach(function(key)
  300. {
  301. console.log("**************");
  302. console.log(key);
  303. if(rooms[key] != null)
  304. {
  305. var roomObj = new Object();
  306. roomObj.name = key;
  307. if(rooms[key].password == null)
  308. {
  309. roomObj.passwordBool = false;
  310. }
  311. else
  312. {
  313. roomObj.passwordBool = true;
  314. }
  315. roomObj.capacity = rooms[key].capacity;
  316. roomObj.occupants = rooms[key].users.length;
  317. obj.rooms.push(roomObj);
  318. }
  319. else
  320. {
  321. console.log("would not tough it with a 10ft pole");
  322. }
  323. });
  324. return obj;
  325. }
  326. //list of all players --accessed using names like a dic
  327. var players = {};
  328. //list of all the rooms
  329. var rooms = {};
  330. var app = require('express')();
  331. var http = require('http').Server(app);
  332. var io = require('socket.io')(http);
  333. const port = 3000;
  334. app.get('/', function(req, res)
  335. {
  336. console.log("err");
  337. res.sendfile('index.html');
  338. });
  339. //Whenever someone connects this gets executed
  340. io.on('connection', function(socket)
  341. {
  342. var p = new player(socket);
  343. console.log('A user connected');
  344. /**
  345. *Register user nickname/handle (register) Client => Server
  346. */
  347. socket.on('register', function(data)
  348. {
  349. console.log("Register event called");
  350. console.log(data);
  351. console.log(" ");
  352. //checks for user name in use
  353. //if(serverUtils.userAvailable(data, players))
  354. if(!(data in players))
  355. {
  356. p.name = data;
  357. players[data] = p;
  358. socket.emit('sendRooms', generateSendRoomsJSON());
  359. console.log("send rooms called");
  360. console.log(generateSendRoomsJSON());
  361. }
  362. else
  363. {
  364. socket.emit('registerFailed', 'User name taken');
  365. console.log("registration failed sent");
  366. }
  367. console.log(player);
  368. });
  369. /**
  370. *Create Room (createRoom) Client => Server
  371. * data {password: , capacity: }
  372. */
  373. socket.on('createRoom', function(data)
  374. {
  375. console.log("create room event called");
  376. console.log(data);
  377. console.log(" ");
  378. rooms[p.name] = new room(data.capacity, data.password, p);
  379. //sends updated room list to all users not in a room
  380. var dd = generateSendRoomsJSON();
  381. Object.keys(players).forEach(function(key)
  382. {
  383. if(players[key] != null)
  384. {
  385. if(players[key].room == null)
  386. {
  387. players[key].socket.emit('sendRooms', dd);
  388. }
  389. }
  390. else
  391. {
  392. console.log("player was null Bad!");
  393. }
  394. });
  395. });
  396. /**
  397. * Room Selection (joinRoom) Client => Server
  398. * data {roomName: , password: }
  399. */
  400. socket.on('joinRoom', function(data)
  401. {
  402. console.log("join room event called");
  403. console.log(data);
  404. console.log(" ");
  405. console.log(rooms);
  406. if(rooms[data.roomName] != null && rooms[data.roomName].canJoin(data.password))
  407. {
  408. rooms[data.roomName].addUser(p);
  409. console.log("user joined room");
  410. }
  411. else
  412. {
  413. socket.emit('joinFailed', 'Failed connecting to room');
  414. }
  415. console.log(rooms);
  416. });
  417. /**
  418. * data -- literally a string
  419. */
  420. socket.on('submitWord', function(data)
  421. {
  422. console.log("submitWord called");
  423. console.log(data);
  424. console.log(" ");
  425. p.selectWord(data);
  426. });
  427. //Whenever someone disconnects
  428. socket.on('disconnect', function ()
  429. {
  430. console.log('A user disconnected');
  431. if(rooms[p.name] != null)
  432. {
  433. rooms[p.name] = null;
  434. }
  435. //leave the room
  436. if(p.room != null)
  437. {
  438. p.room.removeUser(p);
  439. }
  440. //players[p.name] = null;
  441. delete players[p.name];
  442. });
  443. });
  444. http.listen(port, function()
  445. {
  446. console.log('listening on *:3000');
  447. });