JSFiddle - React, Tailwind, and code Playground

by Sebastian Kay

HTML

<canvas id="canvas"></canvas>
<div id="stats"></div>

CSS

body {
  margin: 0;
  overflow: hidden;
}
canvas {
  display: block;
}
#stats {
  position: fixed;
  top: 10px;
  left: 10px;
  color: white;
  font-family: monospace;
}

JavaScript

const canvas = document.getElementById("canvas")
  const ctx = canvas.getContext("2d")
  const CELL_SIZE = 64
  const FOV = Math.PI / 3
  const WALL_HEIGHT = CELL_SIZE

  // Texturen
  const textures = {
    ceiling: new Image(),
    wall: new Image(),
    floor: new Image(),
  }

  // Zustand
  let player = {
    x: CELL_SIZE / 2,
    y: CELL_SIZE / 2,
    angle: 0,
    speed: 0,
  }

  let maze = []
  const MAZE_SIZE = 8

  // Lade Texturen
  Promise.all([
    loadTexture(textures.ceiling, "celling.png"),
    loadTexture(textures.wall, "wall.png"),
    loadTexture(textures.floor, "floor.png"),
  ]).then(init)

  function loadTexture(img, src) {
    return new Promise((resolve) => {
      img.onload = resolve
      img.src = src
    })
  }

  function init() {
    resize()
    generateMaze()
    addEventListeners()
    gameLoop()
  }

  function generateMaze() {
    // Einfaches Labyrinth-Grid
    maze = Array(MAZE_SIZE)
      .fill()
      .map(() =>
        Array(MAZE_SIZE)
          .fill()
          .map(() => ({
            north: true,
            east: true,
            south: true,
            west: true,
            visited: false,
          })),
      )

    // Rekursiver Backtracking-Algorithmus
    const stack = []
    let current = { x: 0, y: 0 }
    maze[0][0].visited = true
    stack.push(current)

    while (stack.length > 0) {
      const neighbors = getUnvisitedNeighbors(current.x, current.y)

      if (neighbors.length) {
        const next = neighbors[Math.floor(Math.random() * neighbors.length)]
        removeWall(current, next)
        maze[next.y][next.x].visited = true
        stack.push(next)
        current = next
      } else {
        current = stack.pop()
      }
    }
  }

  function getUnvisitedNeighbors(x, y) {
    const neighbors = []
    if (y > 0 && !maze[y - 1][x].visited) neighbors.push({ x, y: y - 1 })
    if (x < MAZE_SIZE - 1 && !maze[y][x + 1].visited)
      neighbors.push({ x: x + 1, y })
    if (y < MAZE_SIZE - 1 &&...