All files / src/shared/lib/helpers paint.ts

100% Statements 42/42
85.71% Branches 12/14
100% Functions 5/5
100% Lines 37/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 8383x         83x               103x 111x 127x 126x           83x                   6x 6x 6x 6x   6x 6x 6x 6x 6x   6x   6x 26x 26x 26x 26x   26x 5x 5x   26x       83x                 8x 8x 8x 8x 8x 32x 16x 16x 16x         86x  
import { floodFill } from "ts-flood-fill";
 
type SetValueFn<T> = (x: number, y: number, value: T) => void;
type InBoundsFn = (x: number, y: number) => boolean;
 
const paint = <T>(
  x: number,
  y: number,
  size: number,
  value: T,
  setValue: SetValueFn<T>,
  isInBounds: InBoundsFn,
) => {
  for (let xi = x; xi < x + size; xi++) {
    for (let yi = y; yi < y + size; yi++) {
      if (isInBounds(xi, yi)) {
        setValue(xi, yi, value);
      }
    }
  }
};
 
const paintLine = <T>(
  startX: number,
  startY: number,
  endX: number,
  endY: number,
  size: number,
  value: T,
  setValue: SetValueFn<T>,
  isInBounds: InBoundsFn,
) => {
  let x1 = startX;
  let y1 = startY;
  const x2 = endX;
  const y2 = endY;
 
  const dx = Math.abs(x2 - x1);
  const dy = Math.abs(y2 - y1);
  const sx = x1 < x2 ? 1 : -1;
  const sy = y1 < y2 ? 1 : -1;
  let err = dx - dy;
 
  paint(x1, y1, size, value, setValue, isInBounds);
 
  while (!(x1 === x2 && y1 === y2)) {
    const e2 = err << 1;
    Eif (e2 > -dy) {
      err -= dy;
      x1 += sx;
    }
    if (e2 < dx) {
      err += dx;
      y1 += sy;
    }
    paint(x1, y1, size, value, setValue, isInBounds);
  }
};
 
const paintMagic = <T>(
  bgWidth: number,
  tileLookup: number[],
  x: number,
  y: number,
  value: T,
  setValue: SetValueFn<T>,
  isInBounds: InBoundsFn,
) => {
  const tileindex = bgWidth * y + x;
  const targetTileID = tileLookup[tileindex];
  let x1 = x;
  let y1 = y;
  tileLookup.forEach((element, index) => {
    if (element === targetTileID) {
      x1 = index % bgWidth;
      y1 = (index / bgWidth) >> 0;
      paint(x1, y1, 1, value, setValue, isInBounds);
    }
  });
};
 
export { paint, paintLine, floodFill, paintMagic };