Breaking Down Ania Kabow’s Candy Crush Tutorial Part 4- Move Candies Down, Generate New Candies, and Add a Scoreboard
Tags: codenewbie, javascript, tutorial, 100daysofcode
Published: 2020-08-27 14:58:17

Continuing on from [part 3](https://dev.to/courtneypure/breaking-down-ania-kabow-s-candy-crush-tutorial-part-3-valid-moves-checking-for-matches-4lj3) of this technical breakdown, the next and final tasks in creating this game is generate candies moving down, creating new candies, and creating a scoreboard!

## Move Candies Down
We begin by creating a function which we named moveDown and add a for loop to check all the squares up to square 55.  In this function we want to check each of the squares below the selected indexes for an empty square.  You take the index number plus the width which is 8.  For example if you are at index 7 we want to check if the square below it, index 15, is an empty square.  

Inside the for loop, we check the .style.backgroundColor property to see if the squares background color is empty by using an if statement and set it to an empty string using strict equality.

```javascript
function moveDown () {
	for(let i = 0; i < 55; i++){
		if (squares[i + width].style.backgroundColor === ‘’){
		
		}
```

Next we want to move the candy square down if it is empty. If we are using the same example from above of square 7 and square 15, we essential want square 15 to be equal to square 7.  This is creating the down movement where now since square 15 is empty square 7 is now moving in that spot.

```javascript
squares[i + width].style.backgroundColor = squares [i].style.backgroundColor
```
Lastly we set the square to an empty string.  So now square 7 is empty and this loop would repeat to make sure empty spaces are filled with the appropriate squares.

```javascript
squares[i].style.backgroundColor = ‘’
```

```javascript
function moveDown () {
	for(let i = 0; i < 55; i++){
		if (squares[i + width].style.backgroundColor === ‘’){
		squares[i + width].style.backgroundColor = squares [i].style.backgroundColor
        squares[i].style.backgroundColor = ‘’
		}
	}
}
```

To make sure that this executes throughout the game we add it to our setInterval function. Again this function will execute every 100 milliseconds.

```javascript
window.setInterval(function(){
		moveDown()
		checkRowForFour()
		checkColumnForFour()
		checkRowForThree()
		checkColumnForThree()
	}, 100)

```

## Generate New Candies
Still within the moveDown function we will first define the first row as a const variable.

```javascript
const firstRow = [0, 1, 2, 3, 4, 5, 6, 7]
```

Then we will check if the first row includes any of the above array items.  If so it will come back as a boolean value of true.

```javascript
const isFirstRow = firstRow.includes(i)
```

By creating an if statement we check if both conditions of the square being in the first row and if the square is empty. If so, then we need to fill it with a random color. As Ania states in the video, the “random color” is actually a random number we can use to access the candy colors in the candyColor array.

```javascript
if (isFirstRow && squares[i].style.backgroundColor === ‘’){
	let randomColor = Math.floor(Math.random() * candyColors.length)
}
```

Lastly we take that square and set it equal to candyColors array.  We are using the randomColor variable we created in the statement to get a number within the candyColors array.

```javascript
if (isFirstRow && squares[i].style.backgroundColor === ‘’){
	let randomColor = Math.floor(Math.random() * candyColors.length)
	squares[i].style.backgroundColor = candyColors[randomColor]
}
```

The final code should look like this:

```javascript
function moveDown () {
	for(let i = 0; i < 55; i++){
		if (squares[i + width].style.backgroundColor === ‘’){
		squares[i + width].style.backgroundColor = squares [i].style.backgroundColor
squares[i].style.backgroundColor = ‘’
		if (isFirstRow && squares[i].style.backgroundColor === ‘’){
		let randomColor = Math.floor(Math.random() * candyColors.length)
		squares[i].style.backgroundColor = candyColors[randomColor]
			}
		}
	}
}
```


## Scoreboard
Create a const called scoreDisplay and set it equal to the score id within your HTML file.  You do this by using the getElementById() method.

```javascript
document.addEventListener('DOMContentLoaded', () =>
	const grid = document.querySlector('.grid')
	const scoreDisplay = document.getElementbyId('.score')
	const width = 8
	const squares = []
	let score = 0
)
```

Next we will add the scoreDisplay to the 'check for matches' functions we created in part 3 of this series.  Using the innerHTML property we set the score markup onto our page.

```javascript
// Check column for a match of 4
function checkColumnForFour() {
    for(i = 0; i < 39; i++){
        let columnOfFour = [i, i+width, i+width*2, i+width*3]
        let decidedColor = squares[i].style.backgroundColor
        const isBlank = squares[i].style.backgroundColor === ‘ ’
        if (columnOfFour.every(index => squares[index].style.backgroundColor === decidedColor && !isBlank){
            score += 4
	        scoreDisplay.innerHTML = score
            columnOfFour.forEach(index => {
            squares[index].style.backgroundColor = ‘’
        })
      }
    }
}
```

In the HTML file we add a div with a class of Score-Board.  This is where we are injecting the scoreboard.  Then we added two heading tags.  One has the word Score and the other will have an id of score will hold the actual score.  This is where we assigned our cont scoreDisplay in JavaScript.

```HTML
<!DOCTYPE html>

<html>
    <head>
      <meta charset=“utf-8”>
      <title>Candy Crush</title>
      <link rel=“stylesheet” href=“css/style.css”>
      <script src=“js/app.js” charset=“utf-8”></script>
    </head>
    <body>

      <img class=“logo” src= “images/candycrush.png” alt=“Candy Crush Logo”>

      <div class=“gameboard”>
      <div class=“Score-Board”>
        <h3>Score</h3>
        <h3 id=“score”></h3>
      </div>

      <br>
      <div class=“grid”></div>
    </div>
    </body>
</html>
```

And there you have it a super simple rendition of Candy Crush! If you want to see my version of the game you can check out my [GitHub repository](https://github.com/courtneypure/jsCandyCrushGame).  

Mine is themed around Animal Crossing which I, and pretty much most of the world, are currently obsessed.  At the end of the video Ania shows how you can add images in your candyColors array so I created fruits to represent the candy colors.  The rest of the styling - background, candy icons, and logo I created in Adobe Photoshop and Illustrator.

Thanks for following along as I broke down this code! Thanks to Ania Kubow for an awesome tutorial and I hope you have a better understanding of javascript.

{% vimeo 452232343 %}

## MDN web docs
###Topics Includes:

* [includes() -]( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)

* [conditional statements](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals)

* [logical AND (&&)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND)

* [for loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)

* [setInterval function](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval)

* [getElementById()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)

* [innerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML)



Each function and method above is linked to their respective MDN web doc pages.  This concludes the series of Breaking Down [Ania Kabow’s Candy Crush video](https://www.youtube.com/watch?v=XD5sZWxwJUk).

If there are any errors in my syntax or grammar please shoot me a comment or message to let me know!  This is my first technical blog post so I want to make sure I'm sharing the best information possible.