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.

Structure.js 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import assets from "./assets.js";
  2. import Rect from "./Rect.js";
  3. import Vec2 from "./Vec2.js";
  4. import Texture from "./Texture.js";
  5. function findBounds(arr, bounds) {
  6. arr.forEach(e => {
  7. let right = (e.x + 1) * assets.tiles.tileWidth;
  8. let bottom = (e.y + 1) * assets.tiles.tileHeight;
  9. if (right > bounds.size.x)
  10. bounds.size.pixelX = right;
  11. if (bottom > bounds.size.y)
  12. bounds.size.pixelY = bottom;
  13. });
  14. }
  15. function rightOrBelow(r1, r2) {
  16. // r2 right of r1
  17. if (
  18. (r1.top === r2.top && r1.bottom == r2.bottom) &&
  19. (r1.right + 1 >= r2.left && r1.left <= r2.left))
  20. return true;
  21. // r2 below r1
  22. if (
  23. (r1.right === r2.right && r1.left == r2.left) &&
  24. (r1.bottom + 1 >= r2.top && r1.top <= r2.top))
  25. return true;
  26. return false;
  27. }
  28. function continuous(r1, r2) {
  29. return rightOrBelow(r1, r2) || rightOrBelow(r2, r1);
  30. }
  31. function flattened(arr, newArr = []) {
  32. arr.forEach(e => {
  33. if (e instanceof Array)
  34. flattened(e, newArr);
  35. else
  36. newArr.push(e);
  37. });
  38. return newArr;
  39. }
  40. export default class Structure {
  41. constructor(attrs, nestedArr) {
  42. this.texture = new Texture(assets.tiles, nestedArr);
  43. this.attrs = {
  44. wall: false,
  45. platform: false,
  46. }
  47. for (let a of attrs)
  48. this.setAttr(a);
  49. this.nestedArr = nestedArr;
  50. this.pos = new Vec2();
  51. this.bounds = new Rect(this.pos);
  52. }
  53. init() {
  54. var arr = flattened(this.nestedArr);
  55. findBounds(arr, this.bounds);
  56. }
  57. draw(ctx) {
  58. this.texture.draw(ctx, this.pos.pixelX, this.pos.pixelY);
  59. }
  60. setAttr(attr) {
  61. if (this.attrs[attr] == null)
  62. throw new Error("Invalid attribute:", attr);
  63. this.attrs[attr] = true;
  64. return this;
  65. }
  66. }