我需要一种方法从数组中获取随机数 (0-10),然后获取以下 2 个后续 #。如7、8、9。 3,4,5等
I need a way to get a Random number (0-10) from an array then get the following 2 subsequent #'s. Such as 7,8,9. 3,4,5 etc
我正在制作一个一维战舰游戏,其中只有 1 个 1x10 行,所以我想在每个游戏中生成一个随机 #(0-10),但接下来的 2 个数字必须就在它旁边,因为它一艘船。到目前为止,我一直在尝试很多不同的选择,但都没有成功。此代码获取 3 个无重复的随机 #'s,这也很重要,但数字并不相邻。任何帮助将不胜感激。
const nums = [0,1,2,3,4,5,6,7,8,9,10];
const shuffled = nums.sort(() => 0.5 - Math.random());
let selected = shuffled.slice(0, 3);
console.log(selected);
试试这个:
function getShipPosition(shipSize, nums) {
const startPosition = Math.floor(Math.random() * (nums.length - shipSize + 1));
return nums.slice(startPosition, startPosition + shipSize)
}
const nums = [0,1,2,3,4,5,6,7,8,9,10];
console.log(getShipPosition(3, nums));
您可以生成一个随机索引并使用 Array#slice
获取从那里开始的三个数字。
const nums = [0,1,2,3,4,5,6,7,8,9,10];
let rand = Math.random() * (nums.length - 2) | 0;
let randomThree = nums.slice(rand, rand + 3);
console.log(randomThree);
我正在制作一个一维战舰游戏,其中只有 1 个 1x10 行,所以我想在每个游戏中生成一个随机 #(0-10),但接下来的 2 个数字必须就在它旁边,因为它一艘船。到目前为止,我一直在尝试很多不同的选择,但都没有成功。此代码获取 3 个无重复的随机 #'s,这也很重要,但数字并不相邻。任何帮助将不胜感激。
const nums = [0,1,2,3,4,5,6,7,8,9,10];
const shuffled = nums.sort(() => 0.5 - Math.random());
let selected = shuffled.slice(0, 3);
console.log(selected);
试试这个:
function getShipPosition(shipSize, nums) {
const startPosition = Math.floor(Math.random() * (nums.length - shipSize + 1));
return nums.slice(startPosition, startPosition + shipSize)
}
const nums = [0,1,2,3,4,5,6,7,8,9,10];
console.log(getShipPosition(3, nums));
您可以生成一个随机索引并使用 Array#slice
获取从那里开始的三个数字。
const nums = [0,1,2,3,4,5,6,7,8,9,10];
let rand = Math.random() * (nums.length - 2) | 0;
let randomThree = nums.slice(rand, rand + 3);
console.log(randomThree);