Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

Behavior

Save Automatically?

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

              
                body, html {
  margin: 0;
  height: 100%;
  width: 100%;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ccc;
}
              
            
!

JS

              
                const { Engine, Render, Runner, World, Bodies, Body, Events } = Matter;

class Maze {
  constructor(mazeElement, blocks, width, height) {
    this.mazeElement = mazeElement;
    this.blocks = blocks;
    this.width = width;
    this.height = height;
    this.unitLength = this.width / this.blocks;

    this.setup();
  }

  // Setup the world, engine & renderer
  setup() {
    this.engine = Engine.create();
    this.world = this.engine.world;
    this.world.gravity.y = 0;
    this.render = Render.create({
      element: this.mazeElement,
      engine: this.engine,
      options: {
        wireframes: false,
        width: this.width,
        height: this.height
      }
    });

    Render.run(this.render);
    Runner.run(Runner.create(), this.engine);

    this.updateMaze();
  }

  // Init maze
  updateMaze() {
    this.createMazeBoundaries();
    this.createMazeGrid();
    this.createWalls();
    this.createGoal();
    this.createBall();
  }

  // Create the grid system
  createMazeGrid() {
    this.grid = Array(this.blocks)
      .fill(null)
      .map(() => Array(this.blocks).fill(false));
    this.verticals = Array(this.blocks)
      .fill(null)
      .map(() => Array(this.blocks - 1).fill(false));
    this.horizontals = Array(this.blocks - 1)
      .fill(null)
      .map(() => Array(this.blocks).fill(false));

    // Beginning of algorythm
    this.goToNextCell(
      Math.floor(Math.random() * this.blocks),
      Math.floor(Math.random() * this.blocks)
    );
  }

  // Create boundaries of the maze
  createMazeBoundaries() {
    // Boundaries
    const boundaries = [
      // Top wall
      Bodies.rectangle(this.width / 2, 0, this.width, 2, { isStatic: true }),
      // Bottom wall
      Bodies.rectangle(this.width / 2, this.height, this.width, 2, {
        isStatic: true
      }),
      // Left wall
      Bodies.rectangle(0, this.height / 2, 2, this.height, { isStatic: true }),
      // Right wall
      Bodies.rectangle(this.width, this.height / 2, 2, this.height, {
        isStatic: true
      })
    ];

    World.add(this.world, boundaries);
  }

  // Create all walls
  createWalls() {
    this.horizontals.forEach((row, rowIndex) => {
      row.forEach((isOpen, columnIndex) => {
        this.createWall(isOpen, {
          xPos: columnIndex * this.unitLength + this.unitLength / 2,
          yPos: rowIndex * this.unitLength + this.unitLength,
          width: this.unitLength,
          height: 5
        });
      });
    });

    this.verticals.forEach((column, columnIndex) => {
      column.forEach((isOpen, rowIndex) => {
        this.createWall(isOpen, {
          xPos: columnIndex * this.unitLength + this.unitLength,
          yPos: rowIndex * this.unitLength + this.unitLength / 2,
          width: 5,
          height: this.unitLength
        });
      });
    });
  }

  createWall(isOpen, wallProperties) {
    if (isOpen) {
      return;
    }

    const { xPos, yPos, width, height } = wallProperties;

    const wall = Bodies.rectangle(xPos, yPos, width, height, {
      label: "wall",
      isStatic: true,
      render: {
        fillStyle: "#0B486B"
      }
    });

    World.add(this.world, wall);
  }

  // Create end goal
  createGoal() {
    this.goal = Bodies.rectangle(
      this.width - this.unitLength / 2,
      this.height - this.unitLength / 2,
      this.unitLength * 0.7,
      this.unitLength * 0.7,
      {
        label: "goal",
        isStatic: true,
        render: {
          fillStyle: "#CFF09E"
        }
      }
    );
    World.add(this.world, this.goal);
  }

  // Create ball
  createBall() {
    this.ball = Bodies.circle(
      this.unitLength / 2,
      this.unitLength / 2,
      this.unitLength / 4,
      {
        label: "ball"
      }
    );

    World.add(this.world, this.ball);

    this.addMovementToBall();
    this.addCollision();
  }

  addMovementToBall() {
    document.addEventListener("keydown", event => {
      const { x, y } = this.ball.velocity;

      switch (event.keyCode) {
        case 87:
        case 38:
          Body.setVelocity(this.ball, { x, y: y - 5 });
          break;

        case 68:
        case 39:
          Body.setVelocity(this.ball, { x: x + 5, y });
          break;

        case 83:
        case 40:
          Body.setVelocity(this.ball, { x, y: y + 5 });
          break;

        case 65:
        case 37:
          Body.setVelocity(this.ball, { x: x - 5, y });
          break;
      }
    });
  }

  addCollision() {
    Events.on(this.engine, "collisionStart", event => {
      event.pairs.forEach(collision => {
        const labels = ["ball", "goal"];

        if (
          labels.includes(collision.bodyA.label) &&
          labels.includes(collision.bodyB.label)
        ) {
          this.world.gravity.y = 1;
          this.world.bodies.forEach(body => {
            if (body.label === "wall") {
              Body.setStatic(body, false);
            }
          });
        }
      });
    });
  }

  // Go to next cell
  goToNextCell(row, column) {
    if (this.grid[row][column]) return;

    this.grid[row][column] = true;

    const neighbors = this.shuffle([
      [row - 1, column, "up"],
      [row, column + 1, "right"],
      [row + 1, column, "down"],
      [row, column - 1, "left"]
    ]);

    // For each neighbor
    for (let neighbor of neighbors) {
      const [nextRow, nextCol, direction] = neighbor;

      // Check if neighbor is out of bounds
      if (
        nextRow < 0 ||
        nextRow >= this.blocks ||
        nextCol < 0 ||
        nextCol >= this.blocks
      ) {
        continue;
      }

      // If visited neighbor, go to next neighbor
      if (this.grid[nextRow][nextCol]) {
        continue;
      }

      // Remove wall
      switch (direction) {
        case "left":
          this.verticals[row][column - 1] = true;
          break;
        case "right":
          this.verticals[row][column] = true;
          break;
        case "up":
          this.horizontals[row - 1][column] = true;
          break;
        case "down":
          this.horizontals[row][column] = true;
          break;
      }

      this.goToNextCell(nextRow, nextCol);
    }
  }

  // Shuffle utility
  shuffle(arr) {
    let counter = arr.length;

    while (counter > 0) {
      const index = Math.floor(Math.random() * counter);

      counter--;

      const temp = arr[counter];
      arr[counter] = arr[index];
      arr[index] = temp;
    }

    return arr;
  }
}

new Maze(document.querySelector("body"), 10, 400, 400);

              
            
!
999px

Console