You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript二维数组中按长度横竖放置战舰

解决战舰按长度横竖放置的问题

你的核心问题出在placeShip函数里——当前代码嵌套遍历整个棋盘,却只修改了board[x][y]这一个单元格,自然只能放置单个格子。要实现按长度横竖放置,需要根据方向和战舰长度连续填充对应单元格,同时还要做边界校验避免超出棋盘范围。

修改后的代码实现

const createShip = (shipLength, name) => {
  let hits = 0
  let sunk = false

  function getLength() {
    return this.shipLength
  }

  function hit() {
    hits += 1
    return hits
  }

  function isSunk() {
    sunk = hits >= shipLength
    return sunk
  }
  return {
    getLength,
    hit,
    isSunk,
    shipLength,
    name
  }
}

const Gameboard = () => {
  const rows = 10
  const columns = 10
  const board = []

  // 初始化棋盘(调整顺序避免cellCount计算错误)
  for (let i = 0; i < rows; i += 1) {
    board[i] = []
    for (let j = 0; j < columns; j += 1) {
      board[i][j] = null
    }
  }

  const cellCount = board.reduce((row, col) => row + col.length, 0)

  const getBoard = () => [...board]

  const placeShip = (x, y, ship, direction = 'horizontal') => {
    // 边界校验:防止战舰超出棋盘
    if (direction === 'horizontal') {
      if (y + ship.shipLength > columns) {
        console.error('战舰横向放置超出棋盘范围')
        return
      }
      // 横向连续填充对应长度的单元格
      for (let i = 0; i < ship.shipLength; i++) {
        board[x][y + i] = ship.name
      }
    } else if (direction === 'vertical') {
      if (x + ship.shipLength > rows) {
        console.error('战舰纵向放置超出棋盘范围')
        return
      }
      // 纵向连续填充对应长度的单元格
      for (let i = 0; i < ship.shipLength; i++) {
        board[x + i][y] = ship.name
      }
    }
  }

  return {
    placeShip,
    getBoard,
    cellCount
  }
}

// 测试用例
const gameboard = Gameboard()
const testShip1 = createShip(3, "Boat")
const testShip2 = createShip(3, "Boat")

// 横向放置战舰
gameboard.placeShip(3, 3, testShip1, 'horizontal')
// 纵向放置战舰
gameboard.placeShip(7, 1, testShip2, 'vertical')

// 打印棋盘查看效果
console.log(gameboard.getBoard().map(row => JSON.stringify(row)))

关键修改说明

  • 调整棋盘初始化顺序:把棋盘循环初始化移到cellCount计算前,避免原代码中cellCount因空数组计算为0的问题。
  • 重构placeShip函数:
    • 移除无意义的棋盘全遍历,改为根据方向循环填充对应长度的单元格。
    • 添加边界检查,防止战舰超出10x10棋盘范围。
    • 支持horizontal(横向,默认值)和vertical(纵向)两种方向参数。
  • 简化isSunk逻辑:直接通过hits >= shipLength赋值给sunk,让代码更简洁直观。

运行修改后的代码,就能实现你期望的战舰横竖放置效果。

内容的提问来源于stack exchange,提问作者DataMoshing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:53:16