lib/pairs-list.js

  1. /**
  2. *@classdesc Controler of paired items.
  3. * @class
  4. */
  5. export class MemoryPairsList extends Array {
  6. /**
  7. * Apply visual changes on paired elements.
  8. * @param {HTMLCanvasElement} canvas Set a pair as found.
  9. */
  10. checkMark(canvas) {
  11. const ctx = canvas.getContext('2d');
  12. const w = canvas.offsetWidth;
  13. const h = canvas.offsetHeight;
  14. const img = this.getImage(canvas);
  15. ctx.clearRect(0, 0, w, h);
  16. ctx.globalAlpha = 0.25;
  17. ctx.drawImage(
  18. img,
  19. 0,
  20. 0,
  21. parseInt(img.width),
  22. parseInt(img.height),
  23. 0,
  24. 0,
  25. w,
  26. h
  27. );
  28. ctx.globalAlpha = 1;
  29. ctx.save();
  30. }
  31. /**
  32. *
  33. * @param {HTMLCanvasElement} canvas Canvas element to be checked.
  34. * @return {boolean} If given canvas has already a known pair.
  35. */
  36. hasPair(canvas) {
  37. const self = this;
  38. let hasPair = false;
  39. self.forEach((c) => {
  40. if (c[0] === canvas) {
  41. hasPair = true;
  42. }
  43. if (c[1] === canvas) {
  44. hasPair = true;
  45. }
  46. });
  47. return hasPair;
  48. }
  49. /**
  50. *
  51. * @param {Array} state Holds info object for both open cards.
  52. * @return {boolean} Are both canvas in given state pair or not.
  53. */
  54. arePairs(state) {
  55. const one = state[0];
  56. const two = state[1];
  57. const self = this;
  58. let matches = false;
  59. self.forEach((c) => {
  60. if (c[0] === one || c[1] === one) {
  61. if (c[0] === two || c[1] === two) {
  62. matches = true;
  63. this.checkMark(one);
  64. this.checkMark(two);
  65. }
  66. }
  67. });
  68. return matches;
  69. }
  70. /**
  71. * find image of given canvas.
  72. * @param {HTMLCanvasElement} canvas image of the given canvas.
  73. * @return {HTMLImageElement} Image for the given canvas.
  74. */
  75. getImage(canvas) {
  76. let img;
  77. this.forEach((c) => {
  78. if (c[0] === canvas || c[1] === canvas) {
  79. img = c[2];
  80. }
  81. });
  82. return img;
  83. }
  84. }