C'est le jeu des tubes de couleur dans les pubs la
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

game.js 2.3KB

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