scrimba
Build a Snake game in JavaScript
Using .unshift() to add a square to the direction of our Snake
Go Pro!

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

To see this lesson you need to be logged in. Joining Scrimba is free and gives you access to 20+ courses.Sign up
Using .unshift() to add a square to the direction of our Snake
AboutCommentsNotes
Using .unshift() to add a square to the direction of our Snake
Expand for more info
index.js
run
preview
console
const grid = document.querySelector('.grid')
const startButton = document.getElementById('start')
const score = document.getElementById('score')
let squares = []
let currentSnake = [2,1,0]

function createGrid() {
//create 100 of these elements with a for loop
for (let i=0; i < 100; i++) {
//create element
const square = document.createElement('div')
//add styling to the element
square.classList.add('square')
//put the element into our grid
grid.appendChild(square)
//push it into a new squares array
squares.push(square)
}
}
createGrid()

currentSnake.forEach(index => squares[index].classList.add('snake'))

function move() {
//remove last element from our currentSnake array
const tail = currentSnake.pop()
console.log(tail)
console.log(currentSnake)
//remove styling from last element
squares[tail].classList.remove('snake')
//add sqaure in direction we are heading

//add styling so we can see it

}
move()

Console
0
,
[
2
,
1
]
,
/index.html
-4:04