DEV Community

Cover image for Build a Simple Arcade Game With Vanilla JavaScript - DOM Manipulation🚀
Roberto Hernandez
Roberto Hernandez

Posted on • Originally published at mullinstack.com

Build a Simple Arcade Game With Vanilla JavaScript - DOM Manipulation🚀

Originally published on my blog MullinStack

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

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>
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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();
});
Enter fullscreen mode Exit fullscreen mode

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;
};
Enter fullscreen mode Exit fullscreen mode

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));
}
Enter fullscreen mode Exit fullscreen mode

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";
};
Enter fullscreen mode Exit fullscreen mode

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

The Completed Program

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 and Medium

Top comments (12)

Collapse
 
scrabill profile image
Shannon Crabill

Fun! This is a good example of what seems complex, is relatively straightforward when the concept/requirements are broken down into individual functions.

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

I think you have a bug in your game. The duck will sometimes spawn under the image. Your counter is also positioned incorrectly and overlaps partially with the background.

Collapse
 
blindfish3 profile image
Ben Calder

Fun. My only suggestion would be to store the score as a variable in the code rather than in the DOM. Once an application grows, storing values in the DOM is a surefire way to generate hard to trace bugs.

Collapse
 
blarzhernandez profile image
Roberto Hernandez

Yes you're right. The idea is playing with the DOM at first. Thanks for sharing!

Collapse
 
devpato profile image
Pato

The cover image is such a click bait lol

Collapse
 
blarzhernandez profile image
Roberto Hernandez

Sorry, I had any intention.😀 thanks for reading! 😀

Collapse
 
sjellen profile image
SJellen

Here's my mine

I'm fidgeting with the lines: duck.style.top/left by adding a multiplier to keep the duck in bounds

Collapse
 
blarzhernandez profile image
Roberto Hernandez

Love it. Thanks for sharing

Collapse
 
zaimazhar97 profile image
zaimazhar97

Hi.

Cool post but any more further explanation on why not using data attributes when working with data instead of id?

Thanks.

Collapse
 
jlrxt profile image
Jose Luis Ramos T.

Gracias

Collapse
 
johndavemanuel profile image
John Dave Manuel

It would be better if the duck is "moving" inside the background only :)

Collapse
 
blindfish3 profile image
Ben Calder

I think you just set yourself a challenge :P