【发布时间】:2020-02-20 05:11:02
【问题描述】:
我正在用 Javascript 和 React 构建一个战舰游戏,即使在谷歌搜索和 StackOverflowing 之后,我也被这个问题困扰了一段时间。
基本上我的电路板是一个二维数组,一个数组中有 10 个数组。我正在尝试随机放置船只,但我在检查一艘船是否与另一艘船相交时遇到了困难。
这是我为我的船准备的:
placeShips = () => {
// Logic to place boats randomly below
// Checks required before placing a boat:
// 1. Does the boat go off the board
// 2. Does the boat overlap another boat
// 3. If checks above pass then place boat
let placedPosition = []
let board = this.state.board.slice()
let i
for (i = 0; i < this.state.ships.length; i++) {
// First randomly select coordinates for where the boat will start
let xcoord = Math.floor(Math.random() * 10)
let ycoord = Math.floor(Math.random() * 10)
// Get positions in array where a boat will be
let potentialBoat = []
let newCoords
let j
for (j = 0; j < this.state.ships[i].getLength(); j++) {
newCoords = [xcoord, ycoord + j]
potentialBoat.push(newCoords)
第一个 for 循环对我所在州的每艘船重复放置,第二个 for 循环取一艘船的长度,获取预期的坐标 ([[0, 1], [0,2]] 用于 2 长船例如)并将其存储在 potentialBoat 数组中。
我的想法是使用这个 potentialBoat 数组,看看是否有任何 [xcoordinate, ycoordinate] 已经存在于placedPosition 数组中,如果是,则再次循环当前船并获取新坐标,直到它们不相交。
这可能吗?还是我应该重新考虑我的整个实施?谢谢!
【问题讨论】:
标签: javascript arrays multidimensional-array