Application Android et IOS pour l'amicale des élèves
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.

Piece.js 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import ShapeL from "./Shapes/ShapeL";
  2. import ShapeI from "./Shapes/ShapeI";
  3. import ShapeJ from "./Shapes/ShapeJ";
  4. import ShapeO from "./Shapes/ShapeO";
  5. import ShapeS from "./Shapes/ShapeS";
  6. import ShapeT from "./Shapes/ShapeT";
  7. import ShapeZ from "./Shapes/ShapeZ";
  8. export default class Piece {
  9. #shapes = [
  10. ShapeL,
  11. ShapeI,
  12. ShapeJ,
  13. ShapeO,
  14. ShapeS,
  15. ShapeT,
  16. ShapeZ,
  17. ];
  18. #currentShape: Object;
  19. constructor(colors: Object) {
  20. this.#currentShape = this.getRandomShape(colors);
  21. }
  22. getRandomShape(colors: Object) {
  23. return new this.#shapes[Math.floor(Math.random() * 7)](colors);
  24. }
  25. toGrid(grid: Array<Array<Object>>, isPreview: boolean) {
  26. const coord = this.#currentShape.getCellsCoordinates(!isPreview);
  27. for (let i = 0; i < coord.length; i++) {
  28. grid[coord[i].y][coord[i].x] = {
  29. color: this.#currentShape.getColor(),
  30. isEmpty: false,
  31. };
  32. }
  33. }
  34. isPositionValid(grid, width, height) {
  35. let isValid = true;
  36. const coord = this.#currentShape.getCellsCoordinates(true);
  37. for (let i = 0; i < coord.length; i++) {
  38. if (coord[i].x >= width
  39. || coord[i].x < 0
  40. || coord[i].y >= height
  41. || coord[i].y < 0
  42. || !grid[coord[i].y][coord[i].x].isEmpty) {
  43. isValid = false;
  44. break;
  45. }
  46. }
  47. return isValid;
  48. }
  49. tryMove(x: number, y: number, grid, width, height, freezeCallback: Function) {
  50. if (x > 1) x = 1; // Prevent moving from more than one tile
  51. if (x < -1) x = -1;
  52. if (y > 1) y = 1;
  53. if (y < -1) y = -1;
  54. if (x !== 0 && y !== 0) y = 0; // Prevent diagonal movement
  55. this.#currentShape.move(x, y);
  56. let isValid = this.isPositionValid(grid, width, height);
  57. if (!isValid && x !== 0)
  58. this.#currentShape.move(-x, 0);
  59. else if (!isValid && y !== 0) {
  60. this.#currentShape.move(0, -y);
  61. freezeCallback();
  62. } else
  63. return true;
  64. return false;
  65. }
  66. tryRotate(grid, width, height) {
  67. this.#currentShape.rotate(true);
  68. if (!this.isPositionValid(grid, width, height)) {
  69. this.#currentShape.rotate(false);
  70. return false;
  71. }
  72. return true;
  73. }
  74. getCoordinates() {
  75. return this.#currentShape.getCellsCoordinates(true);
  76. }
  77. }