我正在制作蛇游戏,并想随机化位置。蛇是一个由3个对象组成的数组,每个对象都具有x和y坐标。我只想随机化第一个对象,其余的,无论是x还是y坐标,只需在上面添加1。
下面的代码不能工作,因为每个x和y都调用不同的随机数。解决办法是什么?
function randomPos() {
let x = Math.floor(Math.random()*numOfColumns + 1)
let y = Math.floor(Math.random()*numOfRows + 1)
return { x, y }
}
const snakeBody = [
{x: randomPos().x, y: randomPos().y},
{x: randomPos().x + 1, y: randomPos().y},
{x: randomPos().x + 2, y: randomPos().y}
]
发布于 2022-03-25 14:31:57
您将在函数x
中返回一个y
和randomPos()
坐标,但您只使用其中的一个。
此外,您只需要一个随机位置,但您要调用randomPos()
6次。
只需调用一次,因为它同时计算x
和y
坐标,您只需要一个位置,而不是6。然后使用对象破坏使用这两个值,并使用它们来计算其他两个值。
const numOfColumns = 20;
const numOfRows = 20;
function randomPos() {
let x = Math.floor(Math.random()*numOfColumns + 1)
let y = Math.floor(Math.random()*numOfRows + 1)
return { x, y }
}
const { x: x1st, y: y1st } = randomPos()
const snakeBody = [
{x: x1st, y: y1st},
{x: x1st + 1, y: y1st},
{x: x1st + 2, y: y1st}
]
console.log(snakeBody);
https://stackoverflow.com/questions/71623748
复制相似问题