C'est le jeu des tubes de couleur dans les pubs la
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.

game.js 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. class Game {
  2. #colorsBank = ['black','silver','gray','maroon','red','purple','fuchsia','green','lime','olive','yellow','navy','blue','teal','aqua'];
  3. constructor(nbTubes, tubeLevel)
  4. {
  5. this.tubes = [];
  6. this.selectedTube = null;
  7. for (let i = 0; i < nbTubes; i++)
  8. {
  9. this.tubes.push(new Tube(tubeLevel));
  10. }
  11. this.initializeColorTubes(tubeLevel);
  12. }
  13. /* The goal is to have each tube filled with its own color. Thus, there
  14. is (tubes minus one) different colors divided in (tubeLevel) layers
  15. mixed in the tubes.
  16. One tube is empty to allow movement.
  17. */
  18. initializeColorTubes(tubeLevel)
  19. {
  20. let nbTubes = this.tubes.length - 1;
  21. let allColors = [];
  22. for (let i = 0; i < nbTubes; i++)
  23. {
  24. let coloridx = i % this.#colorsBank.length;
  25. for (let times = 0; times < tubeLevel-1; times++)
  26. {
  27. allColors.push(this.#colorsBank[coloridx]);
  28. }
  29. }
  30. for (let i = allColors.length - 1; i > 0; i--) {
  31. let j = Math.floor(Math.random() * (i + 1));
  32. let temp = allColors[i];
  33. allColors[i] = allColors[j];
  34. allColors[j] = temp;
  35. }
  36. for (let index = 0; index < allColors.length; index++)
  37. {
  38. let tubeIndex = Math.floor(index/(tubeLevel-1));
  39. this.tubes[tubeIndex].addColorLayer(allColors[index]);
  40. }
  41. }
  42. selectTube(tubeId)
  43. {
  44. let newSelectedTube = this.tubes[tubeId];
  45. if (this.selectedTube == newSelectedTube)
  46. this.selectedTube = null;
  47. else if (this.canPourInto(this.selectedTube, newSelectedTube))
  48. this.pourColorInto(this.selectedTube, newSelectedTube);
  49. else if (!newSelectedTube.isEmpty())
  50. this.selectedTube = newSelectedTube;
  51. }
  52. canPourInto(sourceTube, targetTube)
  53. {
  54. return sourceTube != null && targetTube != null
  55. && sourceTube != targetTube
  56. && (targetTube.isEmpty() || sourceTube.peekTopColor() == targetTube.peekTopColor())
  57. && !targetTube.isFull();
  58. }
  59. pourColorInto(sourceTube, targetTube)
  60. {
  61. while (this.canPourInto(sourceTube, targetTube))
  62. {
  63. targetTube.addColorLayer(sourceTube.removeColorLayer());
  64. }
  65. this.checkTubeCompletion(sourceTube);
  66. this.checkTubeCompletion(targetTube);
  67. }
  68. checkTubeCompletion(tube)
  69. {
  70. if (tube.isComplete())
  71. {
  72. let tubeIndex = this.tubes.indexOf(tube);
  73. this.tubes.splice(tubeIndex, 1);
  74. if (this.selectedTube == tube) this.selectedTube = null;
  75. }
  76. }
  77. }