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