Workshop › Snake › Step 14 of 28
The snake needs something to eat. placeFood picks a random cell on the board and keeps it in food.
```js
const COLS = canvas.width / CELL
const ROWS = canvas.height / CELL
let food
function placeFood() {
food = { x: Math.floor(Math.random() * COLS), y: Math.floor(Math.random() * ROWS) }
}
placeFood()
```COLS and ROWS are how many cells fit: 400 / 20 = 20 each way.let food makes an empty variable that placeFood fills.Math.random() gives a number from 0 up to (not including) 1; times 20 is 0 to 19.99…;
Math.floor cuts off the decimals, giving a whole column 0–19.const CELL = 20 write COLS and ROWS.let dir = ... write let food.let last = 0, after an empty line, write placeFood and the call placeFood().Skills: Functions
← Move the whole body Draw the food →