'Randomize the first element of consecutive elements in an array

I'm making the Snake Game and want to randomize the position. The snake is an array of 3 objects, each with x and y coordinates. I want to randomize only the first object, and the rest, either the x or the y coordinates, would just add 1 on it.

The code below won't work because every x and y is calling a different random number. What are the workarounds?

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}
]


Solution 1:[1]

You are returning an x and y coordinate in your function randomPos() but you are only ever using one of them.

Additionally you only need one random position but you're calling randomPos() 6 times.

Only call it once as it calculates both an x and y coordinate and you only need one position, not 6. Then use both those values using object destructuring and use them to calculate the other two values.

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);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mushroomator