Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. // Node >= v2 required
  2. const util = require('util');
  3.  
  4. const TOP = 0;
  5. const RIGHT = 1;
  6. const BOTTOM = 2;
  7. const LEFT = 3;
  8.  
  9. const SIDES = [TOP, RIGHT, BOTTOM, LEFT];
  10.  
  11. const TAB = 'tab';
  12. const HOLE = 'hole';
  13. const FLAT = 'flat';
  14.  
  15. function randomType() {
  16. return Math.floor(Math.random() * 2) > 0 ? TAB : HOLE;
  17. }
  18.  
  19. class Piece {
  20. constructor(x, y, sides) {
  21. this.x = x;
  22. this.y = y;
  23. this.sides = sides;
  24. }
  25.  
  26. getOppositeSide(side) {
  27. const sidePair = {
  28. [TOP]: BOTTOM,
  29. [RIGHT]: LEFT,
  30. [BOTTOM]: TOP,
  31. [LEFT]: RIGHT,
  32. };
  33.  
  34. const oppositeSide = sidePair[side];
  35.  
  36. return this.sides[oppositeSide];
  37. }
  38. }
  39.  
  40. class Puzzle {
  41. constructor(width, height) {
  42. this.width = width;
  43. this.height = height;
  44. this.matrix = this.createMatrix();
  45.  
  46. this.fillMatrix();
  47. }
  48.  
  49. createMatrix() {
  50. const matrix = [];
  51.  
  52. while (matrix.length < this.height) {
  53. matrix.push([]);
  54. }
  55.  
  56. return matrix;
  57. }
  58.  
  59. getAdjacentPieces(x, y) {
  60. const rowAbove = this.matrix[y - 1];
  61. const rowBelow = this.matrix[y + 1];
  62.  
  63. return [
  64. rowAbove && rowAbove[x], // top
  65. this.matrix[y][x + 1], // right
  66. rowBelow && rowBelow[x], // bottom
  67. this.matrix[y][x - 1], // left
  68. ];
  69. }
  70.  
  71. isEdge(x, y, side) {
  72. const tests = {
  73. [TOP]: (x, y) => y === 0,
  74. [RIGHT]: (x, y) => x === this.width - 1,
  75. [BOTTOM]: (x, y) => y === this.height - 1,
  76. [LEFT]: (x, y) => x === 0,
  77. };
  78.  
  79. return tests[side](x, y);
  80. }
  81.  
  82. assignSide(neighbors, side, axis) {
  83. const isEdge = this.isEdge(...axis, side);
  84.  
  85. if (isEdge) {
  86. return FLAT;
  87. }
  88.  
  89. const adjacentPiece = neighbors[side];
  90.  
  91. if (!adjacentPiece) {
  92. return randomType();
  93. }
  94.  
  95. if (adjacentPiece.getOppositeSide(side) === TAB) {
  96. return HOLE;
  97. }
  98.  
  99. return TAB;
  100. }
  101.  
  102. fillMatrix() {
  103. this.matrix.forEach((row, yIndex) => {
  104. while (row.length < this.width) {
  105. const xIndex = row.length;
  106. const axis = [xIndex, yIndex];
  107.  
  108. const adjacentPieces = this.getAdjacentPieces(...axis);
  109. const sides = SIDES.map(side => this.assignSide(adjacentPieces, side, axis));
  110.  
  111. row.push(new Piece(xIndex, yIndex, sides));
  112. }
  113. });
  114. }
  115. }
  116.  
  117. const puzzle = new Puzzle(4, 4);
  118. console.log(util.inspect(puzzle.matrix, false, null, true));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement