战舰游戏中使用随机坐标放置舰船时的越界及未定义错误解决求助
战舰游戏中使用随机坐标放置舰船时的越界及未定义错误解决求助
我现在卡在这个战舰游戏的收尾阶段了——如果手动指定坐标放舰船,肯定能完美适配棋盘,但用Math.floor(Math.random() * 10)生成x、y随机坐标的话,舰船经常会跑到棋盘边界外,甚至触发奇怪的未定义错误。
我试过让函数递归调用自己来重新生成合法坐标,也试过把数组的索引路径从array[y+i][x]改成array[y-i][x]这类不同的写法,但都没起到理想的效果。下面是调用这段放置代码的示例,还有具体的代码片段:
随机坐标生成及调用示例
let [kX, kY, lX, lY, mX, mY, nX, nY, oX, oY] = Array.from({ length: 10 }, () => Math.floor(Math.random() * 10)) let [pX, pY, qX, qY, rX, rY, sX, sY, tX, tY] = Array.from({ length: 10 }, () => Math.floor(Math.random() * 10)) // 手动指定方向的放置代码(注释掉后用随机方向的逻辑就会触发问题) // cpu.placeShip(kX,kY,chaser,"vertical") // cpu.placeShip(lX,lY,seeker,"vertical") // cpu.placeShip(mX,mY,longride,"horizontal") // cpu.placeShip(nX,nY,underwater,"horizontal") // cpu.placeShip(oX,oY,toofast,"vertical")
放置舰船的核心函数代码
placeShip(x, y, ship, direction){ // 参考思路:在二维数组中放置垂直方向的物体 let array = this.board let length = array.length if(x < 0 || x >= length || y < 0 || y >= length){ return "Out of bounds" } let len = ship.length // 把舰船对象加入玩家舰船列表 this.playerShips.push(ship) x = x-1 y = y-1 // 这里需要加判断防止舰船超出棋盘 if(direction === "horizontal"){ for(let i = 0; i < len; i++){ array[y][x+i] = "S"; this.queue.push(`${y}-${x+i}`) ship.coords.push(`${y}-${x+i}`) } }else if (direction === "vertical"){ for(let i = 0; i < len; i++){ array[y+i][x] = "S"; this.queue.push(`${y+i}-${x}`) ship.coords.push(`${y+i}-${x}`) } } return array }
目前运行时会碰到三种情况:要么触发未定义错误导致函数崩溃,要么舰船还是会超出棋盘的9号边界(棋盘是10x10的,索引应该是0-9),要么就完全正常运行。
备注:内容来源于stack exchange,提问作者Jermain Singleton




