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

              
                <canvas id="background"></canvas>
    <canvas id="players"></canvas>
              
            
!

CSS

              
                
body {
  background-color: black;
}
canvas {
  border: 15px gray groove;
  padding: 5px;
  position: absolute;
}

#background {
  z-index: 0;
}

#players {
  z-index: 1;
}
              
            
!

JS

              
                
const CANVAS_HEIGHT = 600;
const CANVAS_WIDTH = 600;
const WHITE_LEVEL = 0.48;
const BLACK = 0;
const WHITE = 1;
const COLORS = {
  [BLACK]: "black",
  [WHITE]: "white",
};
const PIXEL_RATIO = 5;
const MATRIX_DIMENSIONS = {
  height: CANVAS_HEIGHT / PIXEL_RATIO,
  width: CANVAS_WIDTH / PIXEL_RATIO,
};
const canvas = document.querySelector("#background");
const playersCanvas = document.querySelector("#players");
canvas.height = playersCanvas.height = CANVAS_HEIGHT;
canvas.width = playersCanvas.width = CANVAS_WIDTH;

function generateWhiteNoise(size, whiteLevel = 0.6) {
  return new Array(size)
    .fill(0)
    .map(() => (Math.random() >= whiteLevel ? BLACK : WHITE));
}

function calculatePixelValueByNeighbors(rowIndex, pixelIndex, matrix) {
  let sum = 0;
  for (let y = -1; y < 2; y++) {
    for (let x = -1; x < 2; x++) {
      if (
        !matrix[rowIndex + y] ||
        !matrix[rowIndex + y][pixelIndex + x]
      ) {
        sum -= 1;
      } else {
        sum += 1;
      }
    }
  }
  return sum > 0 ? WHITE : BLACK;
}

function copyMatrix(matrix) {
  return JSON.parse(JSON.stringify(matrix));
}

function cellularAutomaton(matrix) {
  const tmpMatrix = copyMatrix(matrix);
  tmpMatrix.forEach((row, rowIndex) => {
    row.forEach((pixel, pixelIndex) => {
      tmpMatrix[rowIndex][pixelIndex] = calculatePixelValueByNeighbors(
        rowIndex,
        pixelIndex,
        matrix
      );
    });
  });
  return tmpMatrix;
}

function areMatricesDifferent(matrixA, matrixB) {
  return JSON.stringify(matrixA) != JSON.stringify(matrixB);
}

function generateBackgroundPaths(matrix) {
  const wallsPath = new Path2D();
  const roadsPath = new Path2D();
  const mazePaths = {
    wallsPath,
    roadsPath,
  };

  matrix.forEach((pixelsRow, rowIndex) => {
    const y = rowIndex * PIXEL_RATIO;
    pixelsRow.forEach((pixel, pixelIndex) => {
      const x = pixelIndex * PIXEL_RATIO;
      const currPath = pixel === BLACK ? roadsPath : wallsPath;
      currPath.rect(x, y, PIXEL_RATIO, PIXEL_RATIO);
    });
  });

  return mazePaths;
}

function drawBackground(mazePaths) {
  const ctx = canvas.getContext("2d");
  ctx.clearRect(0, 0, CANVAS_HEIGHT, CANVAS_WIDTH);
  ctx.fillStyle = COLORS[BLACK];
  ctx.fill(mazePaths.roadsPath);

  ctx.fillStyle = COLORS[WHITE];
  ctx.fill(mazePaths.wallsPath);

  return mazePaths;
}

function generateBackground() {
  const matrices = {
    last: null,
    current: null,
  };

  matrices.current = new Array(MATRIX_DIMENSIONS.height)
    .fill(0)
    .map(() => {
    return generateWhiteNoise(MATRIX_DIMENSIONS.width, WHITE_LEVEL);
  });

  let count = 0;
  const ITERATIONS_LIMIT = 100;
  while (
    areMatricesDifferent(matrices.current, matrices.last) ||
    count > ITERATIONS_LIMIT
  ) {
    matrices.last = matrices.current;
    matrices.current = cellularAutomaton(matrices.last);
  }

  const backgroundPaths = generateBackgroundPaths(matrices.current);
  return drawBackground(backgroundPaths);
}

function isCircleInPath(circleData = { radius: 5, x: 5, y: 5 }, path) {
  const ctx = document.createElement("canvas").getContext("2d");
  const radius = circleData.radius;
  for (
    let x = circleData.x - radius;
    x <= circleData.x + 2 * radius;
    x += radius
  ) {
    for (
      let y = circleData.y - radius;
      y <= circleData.y + 2 * radius;
      y += radius
    ) {
      if (ctx.isPointInPath(path, x, y)) return true;
    }
  }
  return false;
}

function findAStartingPoint(wallsPaths, radius) {
  let x, y;
  let count = 0;
  do {
    count++;
    x = Math.floor(Math.random() * CANVAS_WIDTH);
    y = Math.floor(Math.random() * CANVAS_HEIGHT);
  } while (isCircleInPath({ radius, x, y }, wallsPaths) && count < 100);

  return { x, y };
}

function start(canvas, radius = 10) {
  const mazesPaths = generateBackground();
  const { x, y } = findAStartingPoint(mazesPaths.wallsPath, radius);
  renderPlayer(canvas, {currX: x, currY: y, playerRadius: radius}, mazesPaths.wallsPath);
}

function renderPlayer(canvas, {currX, currY, playerRadius}, wallsPath) {
  let radius = playerRadius, x = currX, y = currY;
  if (spaceClicked) {
    radius = 2;
  }
  const ctx = canvas.getContext("2d");
  if (clickedKey) {
    if (clickedKey.includes('Down') || clickedKey.includes('Up')) {
      y = currY + KEYBOARD_KEYS[clickedKey] * PIXEL_RATIO / 2;
    } else {
      x = currX + KEYBOARD_KEYS[clickedKey] * PIXEL_RATIO / 2;
    }
  }

  if (y - radius < 0 || y + radius >= CANVAS_HEIGHT || x - radius < 0 || x + radius >= CANVAS_WIDTH || isCircleInPath({radius, x, y}, wallsPath)) {
    x = currX;
    y = currY;
  } else {
    const playerPath = new Path2D();
    playerPath.arc(x, y, radius, 0, 2 * Math.PI);
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    ctx.fillStyle = "blue";
    ctx.fill(playerPath);
  }

  requestAnimationFrame(() => renderPlayer(canvas, {currX: x, currY: y, playerRadius}, wallsPath));
}

const KEYBOARD_KEYS = {
  'ArrowUp': -1,
  'ArrowDown': 1,
  'ArrowLeft': -1,
  'ArrowRight': 1
};

let clickedKey;
let spaceClicked = false;

start(playersCanvas, 10);

document.addEventListener('keydown', (event) => {
  if (event.key === ' ') return spaceClicked = true;

  if (Object.keys(KEYBOARD_KEYS).includes(event.key)) {
    clickedKey = event.key;
  }
});

document.addEventListener('keyup', (event) => {
  if (event.key === ' ') return spaceClicked = false;

  if (clickedKey === event.key) {
    clickedKey = null;
  }
});
              
            
!
999px

Console