randomFree.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. const server = require('http').createServer();
  2. const io = require('../sockets');
  3. const nsp = io.of('/randomFree');
  4. const crypto = require('crypto-js');
  5. const cryptoSHA256= crypto.SHA256;
  6. const GameMachine= require('../../game').GameMachine;
  7. let Users = require('../../database').Repositories.Users;
  8. class randomFree {
  9. constructor() {
  10. const updateLobby = () => {
  11. io.clients((err, clients) => {
  12. io.emit('lobbySize', clients.length);
  13. nsp.emit('lobbySize', clients.length);
  14. });
  15. }
  16. const chatMsg = (msg) => {
  17. msg.time = new Date().toISOString();
  18. io.to('chat').emit('newChatMsg', msg);
  19. nsp.to('chat').emit('newChatMsg', msg);
  20. }
  21. nsp.on('connection', (socket) => {
  22. //console.log('Someone connected');
  23. socket.join('chat');
  24. socket.on('chatMsg', chatMsg);
  25. socket.emit('test');
  26. //socket.on('disconnect', informOpponent);
  27. this.userInGame(socket).then((flag) => {
  28. if(!flag){
  29. socket.join('queue');
  30. console.log("Matching!");
  31. this.match();
  32. } else {
  33. this.setupSocket(socket, flag.currentGame.channel);
  34. }
  35. });
  36. });
  37. // is always called
  38. io.on('connection', (socket) => {
  39. this.userInGame(socket);
  40. socket.on('disconnect', updateLobby);
  41. socket.join('chat');
  42. socket.on('chatMsg', chatMsg);
  43. updateLobby();
  44. });
  45. }
  46. userInGame(socket) {
  47. let token = socket.request._query['token'];
  48. return Users.getUser(token)
  49. .then((user) => {
  50. if(user.currentGame !== null && user.currentGame !== undefined) {
  51. console.log("Game in progress... Sending details...")
  52. socket.emit('gameInProgress', user.currentGame);
  53. return user;
  54. }
  55. return false;
  56. });
  57. }
  58. match() {
  59. nsp.in('queue').clients((error, clients) => {
  60. if (error) throw error;
  61. if(clients.length > 1) {
  62. let p1 = nsp.sockets[clients[0]];
  63. let p2 = nsp.sockets[clients[1]];
  64. p1.emit('test');
  65. p2.emit('test');
  66. const channel = clients[0] + clients[1];
  67. console.log(channel);
  68. let token1 = p1.request._query['token'];
  69. let token2 = p2.request._query['token'];
  70. // maybe i need to change to username
  71. let matchInfo = this.joinGame(token1, token2, channel);
  72. const saveUser = (user, state) => {
  73. user.currentGame = state;
  74. Users.save(user);
  75. };
  76. // fix this shit!
  77. // Main parameters : p1,p2(sockets) -> matchInfo -> channel
  78. // Split function for each Socket -> Keep channel on matchInfo!
  79. //
  80. this.saveUser(token1, matchInfo.playerOneState)
  81. .then(() => this.saveUser(token1, matchInfo.playerTwoState))
  82. .then(() => nsp.in(channel).clients((err, clients) => {
  83. console.log('Channel: ' + channel);
  84. console.log(clients);
  85. console.log("Joining Game");
  86. this.setupSocket(p1, channel);
  87. this.setupSocket(p2, channel);
  88. p1.emit('joinGame', matchInfo.playerOneState);
  89. p2.emit('joinGame', matchInfo.playerTwoState);
  90. }));
  91. }
  92. nsp.in('queue').clients((err, clients) => {
  93. console.log('Queue');
  94. console.log(clients);
  95. io.emit('queueSize', clients.length);
  96. nsp.emit('queueSize', clients.length);
  97. });
  98. });
  99. }
  100. saveUser(token, currentGame) {
  101. return Users.getUser(token).then((user) => saveUser(user, currentGame));
  102. }
  103. setupSocket(socket, channel) {
  104. socket.on('broadcast', (data) => this.broadcast(data, channel));
  105. socket.on('abandon', (data) => this.abandon(data, channel));
  106. socket.on('gameOver', (data) => this.gameOver(data, channel));
  107. socket.on('dispute', (data) => this.dispute(data, channel));
  108. socket.leave('queue', this.errorHandler);
  109. socket.join(channel, this.errorHandler);
  110. }
  111. abandon(data, channel) {
  112. // implement abandon
  113. }
  114. broadcast(data, channel) {
  115. data.timestamp = new Date().getTime();
  116. nsp.in(channel).emit('move', data);
  117. }
  118. dispute(data, channel) {
  119. let result;
  120. // result. gameService.dispute(data);
  121. //may change to 'disputeResult'
  122. nsp.in(channel).emit('result', result);
  123. }
  124. gameOver(data, channel) {
  125. // TODO this should be emitted ONLY if all 9 moves have been played
  126. // TODO verify move stack (compare with hashed cards)
  127. console.log("[---!!!---]GameOver is called!!! ");
  128. let gameMachine = new GameMachine(data.setup);
  129. let winner = gameMachine.runMatch(data.stack.moves);
  130. console.log("[!!!!--->]Winner is " + winner);
  131. nsp.in(channel).emit('winner', winner);
  132. }
  133. errorHandler(e) {
  134. if(e)throw e;
  135. return 0;
  136. };
  137. joinGame(playerOne, playerTwo, channel){
  138. let playerOneCards = this.createRandomCards();
  139. let playerTwoCards = this.createRandomCards();
  140. let setup = this.createSetupArray(playerOne, playerTwo, playerOneCards, playerTwoCards);
  141. let playerOneState = {cards: playerOneCards, setup: setup, channel};
  142. let playerTwoState = {cards: playerTwoCards, setup: setup, channel};
  143. return {playerOneState, playerTwoState};
  144. }
  145. createSetupArray(playerOne, playerTwo, playerOneCards, playerTwoCards){
  146. let id = [
  147. playerOne,
  148. playerTwo
  149. ];
  150. let cards = [
  151. playerOneCards.hashedCardsArray,
  152. playerTwoCards.hashedCardsArray
  153. ];
  154. let setup = {id, cards };
  155. return setup;
  156. }
  157. createRandomCards(){
  158. let playerCardsArray = [];
  159. let saltArray = [];
  160. let hashedCardsArray= [];
  161. for (let i =0; i<5; i++){
  162. let playerCard = Math.floor((Math.random()*100 ) % 100 );
  163. let salt = crypto.lib.WordArray.random(128 / 8).toString();
  164. let hashedCard = cryptoSHA256(playerCard.toString() + salt);
  165. playerCardsArray.push(playerCard);
  166. saltArray.push(salt);
  167. hashedCardsArray.push(hashedCard.toString());
  168. }
  169. return {playerCardsArray, saltArray, hashedCardsArray};
  170. }
  171. }
  172. module.exports = new randomFree();