walk2.html 2.36 KB
<html>
  <body>
    <table id='grid'></table>
    <script>
      const SIZE = 30 // width and height of the grid
      const DELAY = 500 // delay in ms between steps of the walk

      // Build the SIZE x SIZE grid
      const table = document.getElementById('grid')
      // `grid[i][j]` stores the table cell in row `i` and column `j`,
      // as well as the number of times it has been visited during the walk
      const grid = []
      for (let i = 0; i < SIZE; i++) {
        // `tr` is a "table row" element
        const rowElement = document.createElement('tr')
        const row = []
        for (let j = 0; j < SIZE; j++) {
          // `td` is a "table cell" element
          const element = document.createElement('td')
          rowElement.appendChild(element)
          row.push({element, count: 0})
        }
        table.appendChild(rowElement)
        grid.push(row)
      }

      // Visit a given grid position and
      // display the number of times it has been visited
      function visit(position) {
        // Don't do anything if we're off the grid
        const row = grid[position.row]
        if (row === undefined) return
        const cell = row[position.col]
        if (cell === undefined) return

        cell.count++
        cell.element.innerText = String(cell.count)
      }
      // Compute the next position by randomly going left, right, up, or down
      function nextPosition(position) {
        const {row, col} = position
        const random = Math.random()
        if (random < 0.25) return {row: row + 1, col}
        else if (random < 0.5) return {row: row - 1, col}
        else if (random < 0.75) return {row, col: col + 1}
        else return {row, col: col - 1}
      }

      function walkFrom(position) {
        // To perform the walk from the given starting position,
        // visit it and then start from the next position after a delay
        visit(position)
        setTimeout(() => walkFrom(nextPosition(position)), DELAY)
      }

      // Start in the middle of the grid
      walkFrom({row: Math.floor(SIZE / 2), col: Math.floor(SIZE / 2)})
    </script>
    <style>
      #grid {
        border-collapse: collapse;
      }
      #grid td {
        border: 1px solid black;
        width: 20px;
        height: 20px;
        font-size: 15px;
        font-family: sans-serif;
        text-align: center;
      }
    </style>
  </body>
</html>