index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // const location = window.location;
  2. let gameBaseUrl = location.protocol + '//' + window.location.hostname + (location.port.length > 0 ? ':' + location.port : "") + location.pathname;
  3. if (!gameBaseUrl.endsWith("/")) {
  4. gameBaseUrl += "/";
  5. }
  6. gameBaseUrl += "game/";
  7. function getStats() {
  8. fetch("/stats")
  9. .then(r => r.json())
  10. .then(stats => {
  11. document.getElementById('stats').innerHTML = "On going games: " + stats.current + "/" + stats.max;
  12. document.getElementById("game-ttl").innerHTML = stats.ttl;
  13. if (stats.current >= stats.max) {
  14. document.getElementById("new-game-container").innerHTML = 'Server at max capacity, try again later';
  15. }
  16. })
  17. }
  18. getStats();
  19. setInterval(getStats, 5 * 1000)
  20. async function waitForGame(url) {
  21. document.getElementById("new-game-url").innerHTML = "Waiting for game to be ready...";
  22. const stats = await fetch(url+'stats')
  23. .then(r => r.json())
  24. .catch(e => console.log("Couldn't reach "+url));
  25. if (stats && stats.lastActivity) {
  26. let link = url;
  27. link = "<p>Share this link to the other players (the trailing / must be here):</p><a href=\"" + link + "\">" + link + "</a>";
  28. document.getElementById("new-game-url").innerHTML = link;
  29. getStats();
  30. } else {
  31. setTimeout(() => waitForGame(url), 1000);
  32. }
  33. }
  34. function createNewGame() {
  35. fetch("/new-game")
  36. .then(r => r.text())
  37. .then(t => {
  38. document.getElementById("new-game").remove();
  39. let gameUrl = gameBaseUrl + t + "/";
  40. waitForGame(gameUrl);
  41. })
  42. }
  43. document.getElementById("new-game").onclick = createNewGame;