Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
              
            
!

CSS

              
                
              
            
!

JS

              
                console.clear();

class Tile {
  x = 0;
  y = 0;
  w = 0;
  subtiles = [];

  constructor(x = 0, y = 0, t = 0, w = 1) {
    this.x = x * w;
    this.y = y * w;
    this.w = w * 0.5;
    this.subtiles = t
      .toString(2)
      .padStart(4, '0')
      .split('')
      .map(s => parseInt(s));
  }
  
  static compare(t0, t1, dir) {
    const SIDES = ['01', '13', '23', '02'];
    t0 = typeof t0 === 'number'
      ? t0.toString(2).padStart(4, '0')
      : t0.subtiles;
    return (
      t0[SIDES[dir][0]] == t1.subtiles[SIDES[(dir + 2) % 4][0]] &&
      t0[SIDES[dir][1]] == t1.subtiles[SIDES[(dir + 2) % 4][1]]
    );
  }
  
  static getCandidates(top, right, bottom, left) {
    return new Array(16)
      .fill()
      .map((_, i) => i)
      .filter(t => {
        return (
          (   top == null || Tile.compare(t, top, 0)) &&
          ( right == null || Tile.compare(t, right, 1)) &&
          (bottom == null || Tile.compare(t, bottom, 2)) &&
          (  left == null || Tile.compare(t, left, 3))
        );
      });
  }
  
  draw(c) {
    c.save();
      c.translate(this.x, this.y);
      c.scale(this.w, this.w);
      this.subtiles.forEach((t, i) => {
        c.fillStyle = t ? 'black' : 'white';
        c.fillRect(
          i % 2,
          Math.floor(i / 2),
          1, 1
        );
      });
      
      for (let i = 0; i < 4; i++) {
        const
          OFF_X = 0.5 * (i % 2 ? 1 : -1), 
          OFF_Y = 0.5 * (Math.floor(i / 2) ? 1 : -1);
        c.beginPath();
          c.moveTo(1, 1);
          c.lineTo(1 + OFF_X, 1);
          c.lineTo(1, 1 + OFF_Y);
        c.fill();
      };
    
    c.restore();
  }
}


function init() {
  const
    TILE_W = 16,
    GRID_W = Math.ceil(
      Math.max(window.innerWidth, window.innerHeight) /
      TILE_W
    ),
    [CAN, CTX] = addCanvas({ center: false }),
    TILES = new Array2d(GRID_W);

  forEachXY(
    (x, y, i) => {
      TILES.push(new Tile(
        x, y,
        Math.rand(
          Tile.getCandidates(
            y > 0 ? TILES[y - 1][x] : null,
            null,
            null,
            x > 0 ? TILES[y][x - 1] : null
          )
        ),
        TILE_W
      ));
    },
   GRID_W, GRID_W
  );
  TILES.forEach(t => t.draw(CTX));
  
  setTimeout(() => init(), 1500);
}

function forEachXY(
  cb,
  toX, toY,
  fromX = 0, fromY = 0,
  incX = 1, incY = 1,
  rowW
) {
  rowW = rowW || Math.abs(toY - fromY);
  if (toX - fromX * incX < 0) {
    incX *= -1;
  }
  if (toY - fromY * incY < 0) {
    incX *= -1;
  }
  for (let y = fromY; y < toY; y += incY) {
    for (let x = fromX; x < toX; x += incX) {
      cb(x, y, x + y*rowW);
    } 
  }
}


//
// Boilerplate
//

Math.rand = (min = 0, max = 1, int) => {
  let r = Math.random();

  if (typeof min === 'object') {
    return min[Math.floor(min.length * r)];
  }
  if (typeof max == 'boolean') {
    int = max;
    max = min;
    min = 0;
  } else if (typeof max === 'undefined') {
    max = min;
    min = 0;
  }

  r = Math.min(min, max) + r*Math.abs(max - min);
  return int ? Math.floor(r) : r;
};
(function extendCanvas() {  
  window.addCanvas = function(options) {
  options = {
    position: options?.position || 'fixed',
    width:  typeof options?.width  !== 'undefined' ? options.width  : window.innerWidth,
    height: typeof options?.height !== 'undefined' ? options.height : window.innerHeight,
    center: typeof options?.center !== 'undefined' ? options.center : true,
    square: typeof options?.square !== 'undefined' ? options.square : false
  };
  const
    CAN = document.createElement('canvas'),
    CTX = CAN.getContext('2d'),
    MIN_W = Math.min(window.innerWidth, window.innerHeight);
  CAN.width = options.square ? MIN_W : options.width;
  CAN.height = options.square ? MIN_W : options.height;
  if (options.position !== 'none') {
    CAN.style.position = options.position;
    if (options.position === 'fixed') {
      CAN.style.inset = 0;
    }
    document.body.appendChild(CAN);
  }
  if (options.center) {
    CTX.translate(CAN.width * 0.5, CAN.height * 0.5);
  }
  return [
    CAN, CTX,
    CAN.width * (options.center ? 0.5 : 1),
    CAN.height * (options.center ? 0.5 : 1)
  ];
}
  /**
  addDraggablePoints(canvas, points: { x, y }, offsetX: number, offsetY: number)
  Adds event listeners to canvas, which changes values of points when dragged
*/
Object.defineProperty(
  HTMLCanvasElement.prototype,
  'addDraggablePoints', {
    value: function() {
      const sqrRad = 200;
      let dragP = null;

      can.addEventListener('mousedown', e => {
        let d = ps.find(p => 
          Math.dist(p.x, p.y, e.clientX - offX, e.clientY - offY, true) < sqrRad
        );
        if (d) {
          dragP = d;
        }
      });

      can.addEventListener('mousemove', e => {
        if (dragP) {
          dragP.x = e.clientX - offX;
          dragP.y = e.clientY - offY;
        } else {
          CAN.style.cursor = ps.some(p => Math.dist(
            p.x, p.y,
            e.clientX - offX, e.clientY - offY,
            true
          ) < sqrRad) ? 'pointer' : 'default';
        }
      });

      can.addEventListener('mouseup', () => dragP = null);
      can.addEventListener('mouseleave', () => dragP = null);
    }
  }
);

/**
  context.clear()
  Clears whole canvas
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'clear', {
    value: function() {
      this.save();
      this.resetTransform();
      this.clearRect(0, 0, this.canvas.width, this.canvas.height);
      this.restore();
    }
  });
/**
  context.setStyle(color: string)
  Sets both fillStyle and strokeStyle
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'setStyle', {
    value: function(style) {
      this.strokeStyle = style;
      this.fillStyle = style;
    }
  });
/**
  context.circle(x, y, r)
  Adds circle to path
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'circle', {
    value: function(x, y, r) {
      this.moveTo(x + r , y);
      this.arc(x, y, r, 0, Math.TAU);
    }
  });
/**
  context.strokeCircle(x, y, r)
  Begins and strokes circle path
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'strokeCircle', {
    value: function(x, y, r) {
      this.beginPath();
      this.arc(x, y, r, 0, Math.TAU);
      this.stroke();
    }
  });
/**
  context.fillCircle(x, y, r)
  Begins and fills circle path
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'fillCircle', {
    value: function(x, y, r) {
      this.beginPath();
      this.arc(x, y, r, 0, Math.TAU);
      this.fill();
    }
  });
/**
  context.strokeCircle(x, y, r, angStart, angEnd, antiClockwise = false)
  Begins and strokes arc path
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'strokeArc', {
    value: function(x, y, r, a0, a1, dir) {
      this.beginPath();
      this.arc(x, y, r, a0, a1, dir);
      this.stroke();
    }
  });
/**
  context.strokeRect(x, y, w, h)
  Begins and strokes rectangle path
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'strokeRect', {
    value: function(x, y, w, h) {
      this.beginPath();
      this.rect(x, y, w, h);
      this.stroke();
    }
  });
/**
  context.strokePath(...points: {x, y} | [x, y] | {x, y}[] | [x, y][])
  Strokes path from given points
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'strokePath', {
    value: function() {
      this.beginPath();
      Array.from(arguments)
        .flat()
        .map(a => Math.arrToXY(a))
        .forEach(a => this.lineTo(a.x, a.y));
      this.stroke();
    }
  });
/**
  context.strokeShape(...points: {x, y} | [x, y] | {x, y}[] | [x, y][])
  Closes and strokes path from given points
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'strokeShape', {
    value: function() {
      this.beginPath();
      Array.from(arguments)
        .flat()
        .map(a => Math.arrToXY(a))
        .forEach(a => this.lineTo(a.x, a.y));
      this.closePath();
      this.stroke();
    }
  });
/**
  context.strokeShape(...points: {x, y} | [x, y] | {x, y}[] | [x, y][])
  Closes and fills path from given points
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'fillShape', {
    value: function() {
      this.beginPath();
      Array.from(arguments)
        .map(a => Math.arrToXY(a))
        .forEach(a => this.lineTo(a.x, a.y));
      this.stroke();
    }
  });
/**
  context.polygon(x, y, r, s: number, ang, v: number, antiClockwise = false)
  Adds regular polygon of s sides to path
  If v is given, only draw v of s sides
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'polygon', {
    value: function(x, y, r, s, a = 0, v, antiClock) {
      v = v ? Math.min(v, s) : s;
      if (s < 1 || v < 1) {
        return;
      } else if (Math.TAU * r < s) {
        this.setStyle('red');
        this.circle(x, y, r);
      }
      const DA = (Math.TAU / s) * (antiClock ? -1 : 1);
      for (let i = 0; i <= v; i++) {
        this.lineTo(
          x + Math.cos(a) * r,
          y + Math.sin(a) * r
        );
        a += DA;
      }
    }
  });
/**
  context.strokePolygon(x, y, r, s: number, ang, v: number, antiClockwise = false)
  Begins and strokes regular polygon of s sides
  If v is given, only draw v of s sides
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'strokePolygon', {
    value: function() {
      this.beginPath();
        this.polygon(...arguments);
      this.stroke();
    }
  });
/**
  context.fillPolygon(x, y, r, s: number, ang, v: number, antiClockwise = false)
  Begins and fill regular polygon of s sides
  If v is given, only draw v of s sides
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'fillPolygon', {
    value: function() {
      this.beginPath();
        this.polygon(...arguments);
      this.fill();
    }
  });
/**
  context.arrowHead(x, y, ang, width = 20, align: 'top' | 'center' | 'bottom', caret: boolean)
  Adds arrow head to path
  If caret, base of arrow head is not drawn
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'arrowHead', {
    value: function(x, y, a, w = 20, align, caret) {
      this.save();
        this.translate(x, y);
        this.rotate(a);
        if (align === 'center') {
          this.translate(w * 0.5, 0);
        } else if (align === 'bottom') {
          this.translate(w * 0.75, 0);
        }
        this.moveTo(w * -0.75, w * -0.5);
        this.lineTo(0, 0);
        this.lineTo(w * -0.75, w * 0.5);
        if (!caret) {
          this.lineTo(w * -0.75, w * -0.5);
        }
      this.restore();
    }
  });
/**
  context.strokeArrowHead(x, y, ang, width = 20, align: 'top' | 'center' | 'bottom', caret: boolean)
  Begins and strokes arrow head
  If caret, base of arrow head is not drawn
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'strokeArrowHead', {
    value: function(x, y, a, w, align, caret) {
      this.beginPath();
      this.arrowHead(x, y, a, w, align, caret);
      if (!caret) {
        this.closePath();
      }
      this.stroke();
    }
  });
/**
  context.fillArrowHead(x, y, ang, width = 20, align: 'top' | 'center' | 'bottom')
  Begins and fills arrow head
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'fillArrowHead', {
    value: function(x, y, a, w, align) {
      this.beginPath();
      this.arrowHead(x, y, a, w, align);
      this.fill();
    }
  });
/**
  context.fillTextOutline(text, x, y, color = '#fff8', width = 8)
  Draws the outline of text
*/
Object.defineProperty(
  CanvasRenderingContext2D.prototype,
  'fillTextOutline', {
    value: function(text, x, y, c = '#fff8', w = 8) {
      CTX.save();
        CTX.strokeStyle = c;
        CTX.lineWidth = w;
        CTX.lineJoin = 'bevel';
        CTX.strokeText(text, x, y);
      CTX.restore();
      CTX.fillText(text, x, y);
    }
  });
})();
class Array2d extends Array {
  width;

  constructor() {
    super();
    let args = Array.from(arguments);
    this.width = args.shift() || 1;
    if (args.length) {
      this.push(...args);
    }
  }

  push() {
    if (this.length === 0) {
      this._newRow();
    }
    return this[this.length - 1].push(...arguments);
  }

  pop() {
    return this[this.length - 1]?.pop();
  }

  unshift() {
    if (this.length === 0) {
      this._newRow();
    }
    return this[0].unshift(...arguments);
  }

  shift() {
    return this[0]?.shift();
  }

  getItem(x, y, wrap = false) {
    if (wrap) {
      x %= this.width;
      y %= this.length;
    }
    const ROW = super[y];
    return ROW ? ROW[x] : undefined;
  }

  // absolute: index as if every row is filled
  getIndex(i, xOff = 0, yOff = 0, absolute = false, wrap = false) {
    let [x, y] = this.getPosition(i, absolute);
    x += xOff;
    y += yOff;
    if (wrap) {
      x %= this.width;
      y %= this.length;
    }
    const ROW = super[y];
    return ROW ? ROW[x] : undefined;
  }

  getPosition(i, absolute = false) {
    if (absolute) {
      return [
        i % this.width,
        Math.floor(i / this.width)
      ];
    }
    let count = 0;
    for (let y = 0; y < this.length; y++) {
      count += super[y].length;
      if (i < count) {
        return [count - i, y];
      }
    }
  }

  toString() {
    return this.map(a => a.join('  ')).join('\n');
  }
  
  forEach(cb) {
    let i = 0;
    super.forEach((row, y) => row.forEach((item, x) => cb(item, x, y, i++)));
  }

  _newRow() {
    const ROW = new Array2dRow(this);
    super.push(ROW);
    return ROW;
  }
}
class Array2dRow extends Array {
  _parent;

  constructor() {
    super();
    let args = Array.from(arguments);
    this._parent = args.shift();
    this.push(...args);
  }

  push() {
    let row = this;
    Array
      .from(arguments)
      .forEach(el => {
        if (row.length === this._parent.width) {
          row = this._parent._newRow();
        }
        row._push(el);
      });
    return row.length;
  }

  pop() {
    if (this.length === 1) {
      this._parent.splice(this._parent.findIndex(a => a === this), 1);
    }
    return super.pop();
  }

  unshift() {
    let nextRow = this._parent[
      this._parent.findIndex(a => a === this) + 1
    ];
    Array
      .from(arguments)
      .reverse()
      .forEach(el => {
        this._unshift(el);
        if (this.length > this._parent.width) {
          if (!nextRow) {
            nextRow = this._parent._newRow();
          }
          nextRow.unshift(super.pop());
        }
      });
    return this.length;
  }

  shift() {
    if (this.length === 1) {
      this._parent.splice(this._parent.findIndex(a => a === this), 1);
    }
    return super.shift();
  }

  _push() {
    super.push(...arguments);
  }

  _unshift() {
    super.unshift(...arguments);
  }
}
init();
              
            
!
999px

Console