online-duel-sync.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. const fs = require('fs');
  2. export default function OnlineDuelSync(
  3. ioServer,
  4. mariadbConnector,
  5. gameId,
  6. firstPlayer
  7. ) {
  8. let io = ioServer;
  9. let mdb = mariadbConnector;
  10. let players = new Map();
  11. players.set(firstPlayer.playerName, firstPlayer);
  12. let loadGameData = function() {
  13. let gameDetails = {};
  14. try {
  15. gameDetails = mdb.getGameById(gameId);
  16. } catch (err) {
  17. console.log('Error retreiving game : ', err.message);
  18. }
  19. return gameDetails;
  20. };
  21. let chat = function(name, message) {
  22. io.to(gameId).emit('message', {
  23. from: name,
  24. text: message
  25. });
  26. };
  27. firstPlayer
  28. .getSocket()
  29. .join(gameId, () => {
  30. chat(
  31. firstPlayer.playerName,
  32. firstPlayer.playerName +
  33. ' has entered the game, waiting for second player...'
  34. );
  35. })
  36. .emit('update-game-data', loadGameData().game_data)
  37. .on('chat', message => {
  38. chat(firstPlayer.playerName, message);
  39. });
  40. let addPlayer = function(player) {
  41. let res = true;
  42. if (players.size === 1) {
  43. if (players.has(player.playerName)) {
  44. console.log(
  45. 'ERROR : this player is already there ! ',
  46. player.playerName
  47. );
  48. return false;
  49. }
  50. players.set(player.playerName, player);
  51. player
  52. .getSocket()
  53. .join(gameId, () => {
  54. chat(player.playerName, player.playerName + ' has entered the game');
  55. })
  56. .emit('update-game-data', loadGameData().game_data)
  57. .on('chat', message => {
  58. chat(player.playerName, message);
  59. });
  60. } else {
  61. console.log(
  62. 'Already 2 players, weird :' +
  63. player.playerName +
  64. ' was trying to join : ',
  65. players
  66. );
  67. res = false;
  68. }
  69. return res;
  70. };
  71. let playerLeft = function(player, disconnected) {
  72. let playerLeaving = players.get(player.playerName);
  73. if (playerLeaving) {
  74. if (!disconnected) {
  75. playerLeaving.getSocket().leave(gameId);
  76. }
  77. chat(player.playerName, player.playerName + ' has left the game');
  78. players.delete(player.playerName);
  79. }
  80. };
  81. let hasPlayers = function() {
  82. return players.size > 0;
  83. };
  84. return {
  85. addPlayer,
  86. playerLeft,
  87. hasPlayers
  88. };
  89. }