Workshop › Snake › Step 5 of 28
Keep the position in a variable
What we are doing
To move the square later, its position must be data that can change. An object head holds its column and row,
and the drawing reads from it.
```js
let head = { x: 5, y: 5 }
ctx.fillRect(head.x * CELL, head.y * CELL, CELL, CELL)
```
What it means
let makes a variable: a name whose value can change later (const cannot).
{ x: 5, y: 5 } is an object: two named values in one package. x is the column, y the row.
head.x reads the x inside head. The square is now drawn wherever head says.
Your turn
- Under
const CELL = 20 write let head = { x: 5, y: 5 }.
- In the last line, replace each
5 with head.x and head.y. Press Run.
Skills: Game states
← Think in cells A function that draws →
All steps
- Find the canvas
- Get the pen
- Paint the board
- Think in cells
- Keep the position in a variable
- A function that draws
- A function that moves
- The game loop
- Slow it down
- A direction to move in
- Steer with the arrow keys
- A body made of a list
- Move the whole body
- Pick a spot for the food
- Draw the food
- Eat and grow
- Never put food on the snake
- A table of turns
- No U-turns
- Crash into the walls
- Crash into yourself
- The game over message
- Show the score
- One function that starts a game
- Play again with Space
- Remember the best score
- Speed up as you grow
- Build it yourself: through the walls