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.

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