Build a Simple Arcade Game With Vanilla JavaScript - DOM Manipulation🚀
Tags: javascript, beginners, programming
Published: 2020-02-26 16:45:53

**Originally published on my blog [MullinStack](https://www.mullinstack.com/2020/02/22/build-arcade-game-vanilla-javascript-dom-manipulation/)**

Today’s a special day for those who just are starting out in the JavaScript world. The only way to master our craft is practice and today we’re going to dirty our hands and start improving our DOM manipulation skills. How? by building a simple arcade game just with vanilla JavaScript. Repeat, *It is just a practice of the DOM manipulation*

Despite this post being for beginners and newbies, it doesn’t mean that more experienced developers won’t find it useful too.


# What We Will Cover
- The basics of CSS and JavaScript.
- The basic of Flexbox, the CSS3 web layout model.
- Dynamically manipulate the DOM using JavaScript.
- A walkthrough.

The Challenge
![DOM Manipulation](https://miro.medium.com/max/1910/0*XxjxLo_wiKRZVqHt.gif)

## The arcade game has the following requirements:
- It uses an image as a background and has a clickable duck image.
- When the user clicks on the duck two things happen: 
     1. The current score is increased by one and 
     2. The duck moves to a random position.
- It should be build using ES6 specification features.
- It uses Flexbox for its layout.

Simple. Now what? As a general rule, the first thing we need to do with a problem like this is to think about the approach we need to follow and the recipe. That means we need to figure out each step and the detail we need to complete those requirements. Let’s break this down.

# The process to solve it

To solve the challenge we will follow the next steps in the given order. Divide and you will conquer!

1. Implement the layout using the assets (the background image and the duck) and the score box.
2. What do I need when I click on the duck? We need an event listener, which will be a trigger when we click on it.
3. Create a function to increase the current score.
4. Create a function to move the duck randomly.

#### Without further ado, let’s get our fingers dirty.

# 1. Layout
Our layout (index.html) will have a div as a container and then both images the background and the duck. Finally, a *scoreContainer* element with the score text and the score (a counter).

```
<div class="container">
     <img src="https://bit.ly/2Q4q14a" />
     <img id="duck" src="https://bit.ly/2KQJVKc" alt="duck" />
     <div class="scoreContainer">
       <div id="score-text">Score</div>
       <div id="score-counter">0</div>
    </div>
</div>
```
# Styles

```
/*Make any img element responsive*/
img {
 max-width: 100%;
}
/*Set a fixed size for width and height and in an absolute position*/
#duck {
 margin: 50px;
 width: 100px;
 height: 100px;
 position: absolute;
 left: 100px;
 top: 100px;
}
/*Style for the Score container*/
.scoreContainer {
 background-color: black;
 width: 15%;
 height: 15%;
 color: #ffffff;
 top: 5%;
 right: 5%;
 border: 2px solid greenyellow;
 border-radius: 10px;
 display: flex;
 position: fixed;
 flex-direction: column;
 align-items: center;
}
#score-text {
 font-size: 1.5em;
}
#score-counter {
 font-size: 3.1em;
 font-weight: bold;
 color: #06e515;
}
```

# 2. JavaScript
## 2.1 Create the event listener
Now, we are going to create an event listener on our duck image. When a user clicks on the duck image it will fire a function.

```
//Get the target element
const duck = document.querySelector("#duck");
//Add the click event listener
duck.addEventListener("click", () => {
  //Dont forget call the functions here 
  increaseScore();
  moveDuck();
});
```
### 2.2 Create a function to increase the current score
We just created the event listener. Now, we’re going to create a function that will increase the counter, our score, by one.

```
//Increase score by 1
const increaseScore = () => {
  //Get the content of the target element. The current value for score
  const score = document.querySelector("#score-counter").innerHTML;
  //Get the element to increase the value
  const scoreHTML = document.querySelector("#score-counter");
  //Cast the score value to Number type
  let count = Number(score);
  //Set the new score to the target element
  scoreHTML.innerHTML = count + 1;
};
```

### 2.3 Create a function to move the duck randomly
It’s time to move the duck. However, since the duck will move randomly, it’s a good choice to create a helper function to get a random number, which we will later use to set the random position. Let’s create that function:

```
//Get a random number
const getRandomNum = (num) => {
  return Math.floor(Math.random() * Math.floor(num));
}
```

Now, we’re going to create a function to move the duck. We are using the `innerWidth` property to get the inner width of the window in pixels and the `innerHeight` property gets the inner height of the window in pixels. Also, we use the `getRandomNum` function to set the pixel numbers for top and left properties to affect the vertical and horizontal position of the duck.

```
/*
Move the duck randomly 
*/
const moveDuck = () => {
  const w = window.innerWidth;
  const h = window.innerHeight;
  duck.style.top = getRandomNum(w) + "px";
  duck.style.left = getRandomNum(h) + "px";
};
```


This is all for today! I hope you followed this simple guide and have gained an understanding of DOM manipulation.

# The Completed Program


{% codepen https://codepen.io/blarz/pen/pqOrRx %}

Thanks for reading! If this story turned out to be interesting, I’d really appreciate it if you share it with your friends. 

***Feel free to reach me on [my blog](www.mullinstack.com) and [Medium](https://medium.com/@blarz)***