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.

553 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. // var obj = new Object();
  290. // obj.word = w;
  291. // obj.score = result;
  292. // this.log.push(obj);
  293. console.log("api result for " + result + w);
  294. resolve(result);
  295. })
  296. });
  297. }
  298. }
  299. /**
  300. * Generates json sent to user on 'sendRooms'
  301. *
  302. * return [{name: passwordBool: capacity: occupants: }]
  303. */
  304. var generateSendRoomsJSON = function()
  305. {
  306. var obj = new Object();
  307. obj.rooms = [];
  308. //rooms.forEach(function(r)
  309. Object.keys(rooms).forEach(function(key)
  310. {
  311. console.log("**************");
  312. console.log(key);
  313. if(rooms[key] != null)
  314. {
  315. var roomObj = new Object();
  316. roomObj.name = key;
  317. if(rooms[key].password == null)
  318. {
  319. roomObj.passwordBool = false;
  320. }
  321. else
  322. {
  323. roomObj.passwordBool = true;
  324. }
  325. roomObj.capacity = rooms[key].capacity;
  326. roomObj.occupants = rooms[key].users.length;
  327. obj.rooms.push(roomObj);
  328. }
  329. else
  330. {
  331. console.log("would not tough it with a 10ft pole");
  332. }
  333. });
  334. return obj;
  335. }
  336. //list of all players --accessed using names like a dic
  337. var players = {};
  338. //list of all the rooms
  339. var rooms = {};
  340. var app = require('express')();
  341. var http = require('http').Server(app);
  342. var io = require('socket.io')(http);
  343. const port = 3000;
  344. app.get('/', function(req, res)
  345. {
  346. console.log("err");
  347. res.sendfile('index.html');
  348. });
  349. //Whenever someone connects this gets executed
  350. io.on('connection', function(socket)
  351. {
  352. var p = new player(socket);
  353. console.log('A user connected');
  354. /**
  355. *Register user nickname/handle (register) Client => Server
  356. */
  357. socket.on('register', function(data)
  358. {
  359. console.log(data + " registered");
  360. //checks for user name in use
  361. //if(serverUtils.userAvailable(data, players))
  362. if(!(data in players))
  363. {
  364. p.name = data;
  365. players[data] = p;
  366. socket.emit('sendRooms', generateSendRoomsJSON());
  367. console.log("send rooms called");
  368. //console.log(generateSendRoomsJSON());
  369. }
  370. else
  371. {
  372. socket.emit('registerFailed', 'User name taken');
  373. console.log("registration failed sent");
  374. }
  375. //console.log(player);
  376. });
  377. /**
  378. *Create Room (createRoom) Client => Server
  379. * data {password: , capacity: }
  380. */
  381. socket.on('createRoom', function(data)
  382. {
  383. console.log(data + "create room");
  384. // console.log(data);
  385. // console.log(" ");
  386. rooms[p.name] = new room(data.capacity, data.password, p);
  387. //sends updated room list to all users not in a room
  388. var dd = generateSendRoomsJSON();
  389. Object.keys(players).forEach(function(key)
  390. {
  391. if(players[key] != null)
  392. {
  393. if(players[key].room == null)
  394. {
  395. players[key].socket.emit('sendRooms', dd);
  396. }
  397. }
  398. else
  399. {
  400. console.log("player was null Bad!");
  401. }
  402. });
  403. });
  404. /**
  405. * Room Selection (joinRoom) Client => Server
  406. * data {roomName: , password: }
  407. */
  408. socket.on('joinRoom', function(data)
  409. {
  410. console.log(p.name + " joined room " + data.name);
  411. if(rooms[data.roomName] != null && rooms[data.roomName].canJoin(data.password))
  412. {
  413. p.room = rooms[data.roomName];
  414. rooms[data.roomName].addUser(p);
  415. console.log("user joined room");
  416. }
  417. else
  418. {
  419. socket.emit('joinFailed', 'Failed connecting to room');
  420. }
  421. //console.log(rooms);
  422. });
  423. /**
  424. * data -- literally a string
  425. */
  426. socket.on('submitWord', function(data)
  427. {
  428. console.log("submitWord called");
  429. p.selectWord(data).then(function(score)
  430. {
  431. p.roundScore = score;
  432. p.score += score;
  433. p.submission = data;
  434. p.room.update();
  435. })
  436. });
  437. //Whenever someone disconnects
  438. socket.on('disconnect', function ()
  439. {
  440. console.log('A user disconnected');
  441. if(rooms[p.name] != null)
  442. {
  443. rooms[p.name] = null;
  444. }
  445. //leave the room
  446. if(p.room != null)
  447. {
  448. p.room.removeUser(p);
  449. }
  450. //players[p.name] = null;
  451. delete players[p.name];
  452. });
  453. });
  454. http.listen(port, function()
  455. {
  456. console.log('listening on *:3000');
  457. });