// Grid system for collision detection / 用于碰撞检测的网格系统
import { CELL_SIZE } from './constants.js'

/**
 * Grid class for map parsing and collision queries / 网格类，用于地图解析和碰撞查询
 */
export class Grid {
  constructor(mapData) {
    this.cells = []
    this.width = 0
    this.height = 0
    this.parseMap(mapData)
  }

  // Parse map data into internal grid / 将地图数据解析为内部网格
  parseMap(mapData) {
    this.height = mapData.length
    this.width = mapData[0]?.length || 0
    this.cells = []
    for (let y = 0; y < this.height; y++) {
      this.cells[y] = []
      for (let x = 0; x < this.width; x++) {
        this.cells[y][x] = mapData[y][x] || 0
      }
    }
  }

  // Check if a grid cell is a wall (static=1 or nut=4) / 检查网格单元格是否为墙
  isWall(gridX, gridY) {
    if (gridX < 0 || gridX >= this.width || gridY < 0 || gridY >= this.height) return true
    const cell = this.cells[gridY][gridX]
    return cell === 1 || cell === 4
  }

  // Convert world coordinates to grid coordinates / 将世界坐标转换为网格坐标
  worldToGrid(wx, wy) {
    return {
      x: Math.floor(wx / CELL_SIZE),
      y: Math.floor(wy / CELL_SIZE)
    }
  }

  // Convert grid coordinates to world coordinates / 将网格坐标转换为世界坐标
  gridToWorld(gx, gy) {
    return {
      x: gx * CELL_SIZE + CELL_SIZE / 2,
      y: gy * CELL_SIZE + CELL_SIZE / 2
    }
  }

  // Check if a world position is walkable (no wall collisions) / 检查世界位置是否可行走（无墙壁碰撞）
  isWalkable(wx, wy, size) {
    const half = size / 2
    const corners = [
      { x: wx - half, y: wy - half },
      { x: wx + half, y: wy - half },
      { x: wx - half, y: wy + half },
      { x: wx + half, y: wy + half }
    ]
    for (const corner of corners) {
      const g = this.worldToGrid(corner.x, corner.y)
      if (this.isWall(g.x, g.y)) return false
    }
    return true
  }
}


