Cristian Vasta

Cristian Vasta

1576052963

Learn Javascript by Building a Simple Game

The Intro

The best way to learn a language is to speak it. If you’ve ever had a friend learning French for the first time, they’ve probably peppered you with a bevy of phrases in French. The same goes for medical students learning the language of medicine. Jargon is its own language. To learn it, you have to speak it.

Programming languages like JavaScript are special in that they help you communicate with your computer. The computer understands you through a third party called a compiler. So if JavaScript is a form of language, how do we speak it? We write it, of course, you may say. Okay, but how do we apply it?

We build stuff.

Yes, the best way to learn JavaScript is to build cool things. I’m going to teach you gals/guys advanced functions, functional programming, and jQuery all in one article. That sounds like a lot, but the amount of code you’ll be writing is minimal. These concepts alone can fill volumes, but we don’t want to become professors, we just want to code.

The Build: Whack-a-Frump

Today we’re going to be making a twist on the famous Whack-a-Mole game.

gameboard.html

<h1> Whack-A-Frump </h1>

<div class='score-brd'>
  <p class='score'>0</p>
</div>

<div class='sandbox'>
  <div class='row'>
    <div class='hole'><img class='frmp-hd' src="https://lh3.googleusercontent.com/6wALe1l716CQxW-Q5Q1AgyVti8sAW2TzQ9hZLOjW2hEI-8NCMYLJsPKT4yAk0bjSB2tZWJIMvElDDdDngBo1tKrOJaGz7au0cMN-p0fZVSnb3UtjYDyLSxFmhFywV_rxrH7OZ7JUdknk00SXwSFQk1a4PduukODRHvt1y0D3uUE_lPntYM-ujFcSwO81uT7j-pweGD35d4MMzjMZbQbkH7BMaMa0Wg8WIWsimL1FAGztlUpP4YGdJnCuZjx0GC6G64zp_CR0ApmI0zpJbeQT5j986c5Pubs30FuZv40HbPTgSpt4o-N-aUJB38JyQgx9Dim6gf_mRq_A1nxQJ6eEpYAW0C1nvdd01AoHW5cHOfFeilnzboG4c_cgBjj4BLG3MLGknorUTOp1eKAvU5YwqpL-O_DY3MFfeA06pD-7qVxvwg-rLyknNlA2ZTFJMlwI1koO2DUk3qU9TSD0byECm8fObdi2_f3Go6wimTf0_BEWIWI9s9XH5QUhzt-PA69H5p4Q7GWBY8bWFmOaSRG1O-1daXbpLEJkrl-w29aLkGcbsUdDUwuzT3eTEI9YN-ZYcNiYnjLqZuWE8JDrejsTFOj31zrlwzpf2UjIsE4=w800-h600-no"></div>
    <div class='hole'><img class='frmp-hd' src="https://lh3.googleusercontent.com/6wALe1l716CQxW-Q5Q1AgyVti8sAW2TzQ9hZLOjW2hEI-8NCMYLJsPKT4yAk0bjSB2tZWJIMvElDDdDngBo1tKrOJaGz7au0cMN-p0fZVSnb3UtjYDyLSxFmhFywV_rxrH7OZ7JUdknk00SXwSFQk1a4PduukODRHvt1y0D3uUE_lPntYM-ujFcSwO81uT7j-pweGD35d4MMzjMZbQbkH7BMaMa0Wg8WIWsimL1FAGztlUpP4YGdJnCuZjx0GC6G64zp_CR0ApmI0zpJbeQT5j986c5Pubs30FuZv40HbPTgSpt4o-N-aUJB38JyQgx9Dim6gf_mRq_A1nxQJ6eEpYAW0C1nvdd01AoHW5cHOfFeilnzboG4c_cgBjj4BLG3MLGknorUTOp1eKAvU5YwqpL-O_DY3MFfeA06pD-7qVxvwg-rLyknNlA2ZTFJMlwI1koO2DUk3qU9TSD0byECm8fObdi2_f3Go6wimTf0_BEWIWI9s9XH5QUhzt-PA69H5p4Q7GWBY8bWFmOaSRG1O-1daXbpLEJkrl-w29aLkGcbsUdDUwuzT3eTEI9YN-ZYcNiYnjLqZuWE8JDrejsTFOj31zrlwzpf2UjIsE4=w800-h600-no">      </div>
    <div class='hole'><img class='frmp-hd' src="https://lh3.googleusercontent.com/6wALe1l716CQxW-Q5Q1AgyVti8sAW2TzQ9hZLOjW2hEI-8NCMYLJsPKT4yAk0bjSB2tZWJIMvElDDdDngBo1tKrOJaGz7au0cMN-p0fZVSnb3UtjYDyLSxFmhFywV_rxrH7OZ7JUdknk00SXwSFQk1a4PduukODRHvt1y0D3uUE_lPntYM-ujFcSwO81uT7j-pweGD35d4MMzjMZbQbkH7BMaMa0Wg8WIWsimL1FAGztlUpP4YGdJnCuZjx0GC6G64zp_CR0ApmI0zpJbeQT5j986c5Pubs30FuZv40HbPTgSpt4o-N-aUJB38JyQgx9Dim6gf_mRq_A1nxQJ6eEpYAW0C1nvdd01AoHW5cHOfFeilnzboG4c_cgBjj4BLG3MLGknorUTOp1eKAvU5YwqpL-O_DY3MFfeA06pD-7qVxvwg-rLyknNlA2ZTFJMlwI1koO2DUk3qU9TSD0byECm8fObdi2_f3Go6wimTf0_BEWIWI9s9XH5QUhzt-PA69H5p4Q7GWBY8bWFmOaSRG1O-1daXbpLEJkrl-w29aLkGcbsUdDUwuzT3eTEI9YN-ZYcNiYnjLqZuWE8JDrejsTFOj31zrlwzpf2UjIsE4=w800-h600-no">      </div>
  </div>
  <div class='row'>
    <div class='hole'><img class='frmp-hd' src="https://lh3.googleusercontent.com/6wALe1l716CQxW-Q5Q1AgyVti8sAW2TzQ9hZLOjW2hEI-8NCMYLJsPKT4yAk0bjSB2tZWJIMvElDDdDngBo1tKrOJaGz7au0cMN-p0fZVSnb3UtjYDyLSxFmhFywV_rxrH7OZ7JUdknk00SXwSFQk1a4PduukODRHvt1y0D3uUE_lPntYM-ujFcSwO81uT7j-pweGD35d4MMzjMZbQbkH7BMaMa0Wg8WIWsimL1FAGztlUpP4YGdJnCuZjx0GC6G64zp_CR0ApmI0zpJbeQT5j986c5Pubs30FuZv40HbPTgSpt4o-N-aUJB38JyQgx9Dim6gf_mRq_A1nxQJ6eEpYAW0C1nvdd01AoHW5cHOfFeilnzboG4c_cgBjj4BLG3MLGknorUTOp1eKAvU5YwqpL-O_DY3MFfeA06pD-7qVxvwg-rLyknNlA2ZTFJMlwI1koO2DUk3qU9TSD0byECm8fObdi2_f3Go6wimTf0_BEWIWI9s9XH5QUhzt-PA69H5p4Q7GWBY8bWFmOaSRG1O-1daXbpLEJkrl-w29aLkGcbsUdDUwuzT3eTEI9YN-ZYcNiYnjLqZuWE8JDrejsTFOj31zrlwzpf2UjIsE4=w800-h600-no">      </div>
    <div class='hole'> <img class='frmp-hd' src="https://lh3.googleusercontent.com/6wALe1l716CQxW-Q5Q1AgyVti8sAW2TzQ9hZLOjW2hEI-8NCMYLJsPKT4yAk0bjSB2tZWJIMvElDDdDngBo1tKrOJaGz7au0cMN-p0fZVSnb3UtjYDyLSxFmhFywV_rxrH7OZ7JUdknk00SXwSFQk1a4PduukODRHvt1y0D3uUE_lPntYM-ujFcSwO81uT7j-pweGD35d4MMzjMZbQbkH7BMaMa0Wg8WIWsimL1FAGztlUpP4YGdJnCuZjx0GC6G64zp_CR0ApmI0zpJbeQT5j986c5Pubs30FuZv40HbPTgSpt4o-N-aUJB38JyQgx9Dim6gf_mRq_A1nxQJ6eEpYAW0C1nvdd01AoHW5cHOfFeilnzboG4c_cgBjj4BLG3MLGknorUTOp1eKAvU5YwqpL-O_DY3MFfeA06pD-7qVxvwg-rLyknNlA2ZTFJMlwI1koO2DUk3qU9TSD0byECm8fObdi2_f3Go6wimTf0_BEWIWI9s9XH5QUhzt-PA69H5p4Q7GWBY8bWFmOaSRG1O-1daXbpLEJkrl-w29aLkGcbsUdDUwuzT3eTEI9YN-ZYcNiYnjLqZuWE8JDrejsTFOj31zrlwzpf2UjIsE4=w800-h600-no"></div>
    <div class='hole'><img class='frmp-hd' src="https://lh3.googleusercontent.com/6wALe1l716CQxW-Q5Q1AgyVti8sAW2TzQ9hZLOjW2hEI-8NCMYLJsPKT4yAk0bjSB2tZWJIMvElDDdDngBo1tKrOJaGz7au0cMN-p0fZVSnb3UtjYDyLSxFmhFywV_rxrH7OZ7JUdknk00SXwSFQk1a4PduukODRHvt1y0D3uUE_lPntYM-ujFcSwO81uT7j-pweGD35d4MMzjMZbQbkH7BMaMa0Wg8WIWsimL1FAGztlUpP4YGdJnCuZjx0GC6G64zp_CR0ApmI0zpJbeQT5j986c5Pubs30FuZv40HbPTgSpt4o-N-aUJB38JyQgx9Dim6gf_mRq_A1nxQJ6eEpYAW0C1nvdd01AoHW5cHOfFeilnzboG4c_cgBjj4BLG3MLGknorUTOp1eKAvU5YwqpL-O_DY3MFfeA06pD-7qVxvwg-rLyknNlA2ZTFJMlwI1koO2DUk3qU9TSD0byECm8fObdi2_f3Go6wimTf0_BEWIWI9s9XH5QUhzt-PA69H5p4Q7GWBY8bWFmOaSRG1O-1daXbpLEJkrl-w29aLkGcbsUdDUwuzT3eTEI9YN-ZYcNiYnjLqZuWE8JDrejsTFOj31zrlwzpf2UjIsE4=w800-h600-no">      </div>
  </div>
</div>

HTML

gameboard.css

body {
  font-family: "Rubik Mono One", sans-serif;
}

h1 {
  position: absolute;
  left: 40%;
}

.sandbox {
  margin-top: 10px;
  position: relative;
  left: 40%;
  padding: 10px;
  border: 1px solid #e3dedb;
  border-radius: 4px;
  width: 350px;
  overflow: hidden;
  -webkit-box-shadow: 3px 2px 5px -3px rgba(0, 0, 0, 0.75);
  -moz-box-shadow: 3px 2px 5px -3px rgba(0, 0, 0, 0.75);
  box-shadow: 3px 2px 5px -3px rgba(0, 0, 0, 0.75);
  background: rgb(255, 255, 255); /* Old browsers */
  background: -moz-linear-gradient(
    top,
    rgba(255, 255, 255, 1) 0%,
    rgba(241, 241, 241, 1) 50%,
    rgba(225, 225, 225, 1) 51%,
    rgba(246, 246, 246, 1) 100%
  ); /* FF3.6-15 */
  background: -webkit-linear-gradient(
    top,
    rgba(255, 255, 255, 1) 0%,
    rgba(241, 241, 241, 1) 50%,
    rgba(225, 225, 225, 1) 51%,
    rgba(246, 246, 246, 1) 100%
  ); /* Chrome10-25,Safari5.1-6 */
  background: linear-gradient(
    to bottom,
    rgba(255, 255, 255, 1) 0%,
    rgba(241, 241, 241, 1) 50%,
    rgba(225, 225, 225, 1) 51%,
    rgba(246, 246, 246, 1) 100%
  ); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
  filter: progid:DXImageTransform.Microsoft.gradient(
      startColorstr="#ffffff",
      endColorstr="#f6f6f6",
      GradientType=0
    ); /* IE6-9 */
}
.score-brd {
  width: 100px;
  height: 50px;
  border: 1px solid #000;
  margin-bottom: 20px;
  position: relative;
  left: 0px;
  text-align: center;
  background-color: #000;
  color: red;
}

.score {
  font-size: 28px;
  margin-top: 10px;
}

.hole {
  width: 100px;
  height: 100px;
  border: 1px solid #e3dedb;
  border-radius: 100px;
  margin-top: 8px;
  margin-left: 10px;
  margin-bottom: 10px;
  overflow: hidden;
  background: rgba(0, 0, 0, 1);
  background: -moz-linear-gradient(
    left,
    rgba(0, 0, 0, 1) 0%,
    rgba(0, 0, 0, 0.85) 100%
  );
  background: -webkit-gradient(
    left top,
    right top,
    color-stop(0%, rgba(0, 0, 0, 1)),
    color-stop(100%, rgba(0, 0, 0, 0.85))
  );
  background: -webkit-linear-gradient(
    left,
    rgba(0, 0, 0, 1) 0%,
    rgba(0, 0, 0, 0.85) 100%
  );
  background: -o-linear-gradient(
    left,
    rgba(0, 0, 0, 1) 0%,
    rgba(0, 0, 0, 0.85) 100%
  );
  background: -ms-linear-gradient(
    left,
    rgba(0, 0, 0, 1) 0%,
    rgba(0, 0, 0, 0.85) 100%
  );
  background: linear-gradient(
    to right,
    rgba(0, 0, 0, 1) 0%,
    rgba(0, 0, 0, 0.85) 100%
  );
  filter: progid:DXImageTransform.Microsoft.gradient(
      startColorstr="#000000",
      endColorstr="#000000",
      GradientType=1
    );
}
.row {
  display: flex;
  flex-direction: row;
}

.frmp-hd {
  height: 150px;
  position: relative;
  top: -20px;
  left: 300px;
}
.frmp-hd:hover {
  cursor: pointer;
}

.wobble {
  animation: wobble 4s infinite;
}

.wobbler {
  animation: wobble 2s infinite;
}
@keyframes wobble {
  0%,
  100% {
    left: 0%;
  }
  50% {
    left: 60%;
  }
}

This is what the HTML and CSS gives us:
Game
Keep in mind that we’ll be making a very minimal version of this game. By the end, I’ll provide a list of issues that you can fix and some features you can add.

Setting up jQuery

What we now have is a static game board. Nothing works. With this example alone, you can see that JavaScript is responsible for a ton of the interactivity you see on websites (although, CSS does play its part here and there).

In order to make our HTML elements “do things,” we’re going to have to write some JavaScript. There are two ways of doing this. 1) We can use plain JavaScript and traverse the DOM(Document Object Model) 2) Or we can use jQuery, which does the same as option 1 but in a more user-friendly way.

If you’re unsure what “traversing the DOM” means, think of a marionette show. The puppeteer(JavaScript) moves his puppet(HTML). But he doesn’t use magic to make it do things. He uses strings that are attached to the puppet’s limbs.

We can divide the puppet up like so:

Body (parent of Head, Arm, Leg)
  Head
    eyes (child of head)
    mouth (child of head)
  Right Arm
    hand(parent of fingers & child of right arm)
      fingers(child of hand)
  Right Leg
    foot(child of right leg)

Say we were building our own marionette and we wanted to attach a string to its right foot. We would pick up our string, find the body, move down from the head to the right leg(aha!), and, finally, we would attach the string to the right foot. That’s DOM traversal marionette-style.

When you write up your HTML, it’s important to keep in mind the relationships of your elements, because in order to move a certain element, we need to know where it is first. That’s where jQuery comes in.

jQuery is a JavaScript library that helps us “query” (i.e. find) an element in the DOM so that we can make it do things with JavaScript. Before we can start using this library, we have to link it to our HTML file.

Stick the Google CDN(Content Distribution Network) into your <head> tag and make sure that it’s placed above all other script tags:

<head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

Now, we can begin coding by writing our first line of jQuery:

$(document).ready(function(){
  //all our code goes in here
});

In English, the above line of code reads, “jQuery, find my entire HTML document. When, it’s fully loaded, execute all of my code.”

The funny symbol $( ) is called a query selector. The dollar sign can be replaced with jQuery.

document and the ready() function are built into jQuery, meaning that you can traverse your way to the jQuery docs to find all of its available methods. That’s basically what a library is. A library of functions. Get it? No? Okay moving on…

Callback functions

Now’s the perfect time to tackle callback functions. We’re only going to explore one facet of callback functions to make things simple. Though, callbacks aren’t as advanced as some would have you believe. You can certainly do cool things with them, so if advanced means cool, then,yes, callbacks are advanced.

Here’s why:

See that ready() function? Well we’ve stuffed another function in the parameter. That means that ready() expects a function and once it receives it, it will execute it depending on certain conditions. That’s a callback function.

We’re almost at the cool part.

Normal functions are automatically executed, and then they’re discarded.

Callback functions, like packages, can be saved and “opened” whenever we’re ready to open them. It’s because of callbacks that we can wait for the DOM to fully load before we query elements.

Still not sure about callbacks?

That’s okay. Their power will make itself known the more you code. It also helps that they’re present almost everywhere you turn.

Let’s start jQuery-ing

Now that we have our marionette analogy down, let’s attach a string to one of our HTML elements. In other words, let’s query an element.

jQuery(and vanilla JS as well admittedly) makes querying easy because all we have to do is find class or id we’ve assigned to an element and plug it into the jQuery selector.

We’ll start by querying one of the frumps. The selector is called .frmp-hd . You can go ahead and make your class/id selectors infinitely more readable than mine, if you want.

$(.frmp-hd).

You know what? Let’s list all of the elements we’re going to need and use console.log() each one of them.

console.log($(“.score”));
console.log($(“.sandbox”));

console.log() prints data to the console. You can access your web browser’s console with Right Click -> Inspect or CTRL+SHIFT+I. You may have to tab over to the console.

Once you’re at the console, you will see the jQuery.fn.init object with a drop down arrow to the left. Click the arrow and you’ll find your element. The arrow next to your element will list all the methods you can call on said element.

jQuery-ing

This information is gold. Not only do we know everything about our element from its position to its specific styling, we can access those properties simply by using the key names provided to us by the DOM API. By the way, that’s where the Object in Document Object Model comes into play. Our HTML has been modeled in the form of an object that we can access with JavaScript.

So, $(“sandbox”)[0].className yields “sandbox”

Why the [0]?

The bracket([])notation is another way to access an object’s value. Unfortunately, 0 is the key name given to our <div> element. The dot( . )notation isn’t friendly with numbers so we have to use the bracket notation instead.

Variable Initialization

Are you tired of that jQuery selector yet? Dollar sign, parenthesis, quotations, periods, hashtags — man that’s annoying to type out. Instead of reusing the notation, stick your query selector into a variable.

This is good:

let sandbox = $(“.sandbox”);

This is better:

let $sandbox = $(“.sandbox”)[0];

You can now access your element’s methods without adding the ugly 0. The dollar variable is simply a convention to remind yourself and others that the variable is a special DOM variable.

Game Plan

Okay, breathe. I know we’ve covered quite a lot. Feel free to play around by testing your querying skills. Querying elements will become intuitive so keep practicing.

Now that we know a bit about accessing the DOM, we can start thinking about how we can make our creative Whack-a-Mole game. Whenever we want to build something, it’s always best to plan. Ideally, the planning should occur before any code is written, but for the purpose of this article we’ll start planning now that we’ve gotten our feet wet.

  1. The mole has to appear and disappear
  2. The appearance of a mole has to occur at random
  3. When we hit the mole, we should get points

Time to Solve Some Problems

To solve our first problem, we know we need to animate the elements somehow. JavaScript has a ton of animation libraries. Let’s choose animejs. We’ll deal with the library later. For now, you can plug the source into the head of your HTML.

https://cdnjs.cloudflare.com/ajax/libs/animejs/2.2.0/anime.js

To solve our second problem, we may be able to take advantage of JavaScript’s built in Math.random() function. We can then randomly select elements to animate.

But now we’ve encountered a hidden problem! We will need to trigger a new animation every time, otherwise our animation function will execute automatically and die. The animation should be packaged and ready to go when we want it to go. Sounds like the job of a callback, right?

Well, there’s a built-in function called setInterval(callback, 1000) that takes a callback function and executes it after a specified period of time. Rinse and repeat. It’s not the prettiest solution but it will work for our simple game.

Finally, we need to trigger an event when someone clicks on our “mole” so that we can add points to our score board.

Hmm…let’s step back a bit because we’re getting into the meat of JavaScript.

Event Driven Programming

Click send on your favorite messaging platform — you’ve just triggered an event. Every form of interaction can be considered an event. You can trigger an event by scrolling or by doing nothing for too long. Sometimes events are beyond your control. Other times, they’re entirely predictable. Generally, there’s a flow to these events. The user swipes his mouse over the menu button(trigger), triggers an event(likely a smooth animation) by clicking it, and the menu pops up. The event has been handled, thereby ending the event loop.

That loop is exactly what we’re looking for in our whack-a-mole game. In order to “catch” the event of a click, we need to have someone listening for it. That someone is an event listener. Event listeners wait for a specific event to occur before executing any code(event handler). And, as you may be thinking, that code lying in wait is our dear old callback function.

jQuery provides us with a bevy of event listeners. Here’s a list of them: https://api.jquery.com/category/events/

For our game, we need to listen for a click. It may be tempting to choose .click() from the library, but you’re actually better off choosing .on(). The main difference between the two is flexibility you get by writing .on(“click”, fn) vs .click(fn) . This stack overflow answer does a great job of fully addressing the benefits of .on().

Let’s Create an Event

So if we want to change the score when someone clicks on a frump, we write:

$frump.on("click", function() {
    $score = Number($score) + 10;
    $newScore.innerHTML = $score + "";
  });

What I did was convert our string into a number, add 10 and assign the new number to the $score variable. The new score is then forced into a string again.

Putting It All Together

In the first part of this series, we went through some of the basics of JavaScript. By the end, we were creating events to ensure that the score would change once you hit a frump.Now that we’ve got a handle on some of our problems, we’re ready to piece together our game. In this part, we’ll start by getting a handle on our animation.

Animation

var el = document.getElementsByClassName(“frmp-hd”)[0];
 anime({
 targets: el,
 left: “-40px”,
 direction: “reverse”
 });

This is a really simple animation. All I did here was shift the position of the first frump head to the left. Then, I allowed the animation to play in the opposite direction to hide the frump head. All of these options are baked into the animejs library. Check out the amazing documentation right here.

Now that we’ve animated our frump, we need to randomize its appearance.

Randomization

Wrapping Math.random() in Math.floor() will allow us to randomize our array of frumps. Below, I’ve created a function that will return a random number.

function rand() {
 return Math.floor(Math.random() * 7);
 }

Because we have 6 frumps, we need to multiply Math.random() by 7. That gives us a range of random numbers from 0 to 6. You can practise generating your own range of random numbers at W3schools.

Now we can plug our rand() function into the bracket notation. Remember, all our function does is output a random number. Every time we reload the browser, we should see a random frump appearing.

var el = document.getElementsByClassName(“frmp-hd”)[rand()];

Animation Loop

setInterval() will be a suitable tool for our simple game. It takes a callback function and an integer. The integer that we’ll put in the parameter is in the form of milliseconds. 5000 milliseconds equals 5 seconds.

Warning: Due to JavaScript’s event loop, setInterval() may not work as you expect. You might find that instead of 2 seconds, it may take 4 seconds for your code to execute.

setInterval(function() {
 // We can plug our animation in setInterval() to loop the animation
 },5000);

Now frump heads will appear every five seconds. Play around with the intervals of this extremely basic animation setup to get familiar with setInterval. If you want a more in depth explanation, check out JavaScript.info’s animation article.

Conclusion

That’s it for this part of the tutorial. Animations are a crucial part of gaming. Without them, games are drained of what makes them so fun. Hopefully this section has taught you a bit about how JavaScript can be used beyond websites. Visit howtocodejs.com if you want to learn JavaScript the fun way. Until next time, keep coding.

#javascript #programming #game

What is GEEK

Buddha Community

Learn Javascript by Building a Simple Game

JavaScript Snake Game Tutorial - Develop a Simple Snake Game

Work on real-time JavaScript Snake game project and become a pro

Snake game is an interesting JavaScript project for beginners. Snake game is a single-player game, which we’ve been playing for a very long time. The game mainly consists of two components – snake and fruit. And we just need to take our snake to the food so that it can eat and grow faster and as the number of fruits eaten increases, the length of snake increases which makes the game more interesting. While moving if the snake eats its own body, then the snake dies and the game ends. Now let’s see how we can create this.

JavaScript Project Prerequisites

To implement the snake game in JavaScript you should have basic knowledge of:

1. Basic concepts of JavaScript

2. HTML

3. CSS

Download Project Code

Before proceeding ahead please download source code of Snake Game: Snake Game in JavaScript

Steps to Build the Project – JavaScript Snake game

1. Create Html file

HTML builds the basic structure. This file contains some basic HTML tags like div, h1, title, etc. also we’ve used bootstrap (CDN is already included).

index.html:

Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DataFlair Snake game</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="static/style.css">
</head>
<body>
    <div class="container">
        <div class ="Jumbotron">
        <h1>DataFlair Snake game using vanilla JavaScript</h1>

            <h2 class="btn btn-info"> 
                Score:   0 
            </h2>

            <div class="containerCanvas">
                <canvas id="canvas" width="500" height="500" class="canvasmain"> </canvas>
            </div>
        </div>
    </div>
    <script src="static/fruit.js"></script>
    <script src="static/snake.js"></script>
    <script src="static/draw.js"></script>
</body>
</html>

We have used simple HTML tags except tag. This new tag was introduced in HTML5, which is used to draw graphics, via JavaScript. It is nothing without JavaScript so we will use it in our JavaScript file to actually draw the board and the objects required. We’ll see its implementation in JS files.

#javascript tutorial #javascript project #javascript snake game #simple snake game #javascript

Sival Alethea

Sival Alethea

1624298400

Learn JavaScript - Full Course for Beginners. DO NOT MISS!!!

This complete 134-part JavaScript tutorial for beginners will teach you everything you need to know to get started with the JavaScript programming language.
⭐️Course Contents⭐️
0:00:00 Introduction
0:01:24 Running JavaScript
0:04:23 Comment Your Code
0:05:56 Declare Variables
0:06:15 Storing Values with the Assignment Operator
0:11:31 Initializing Variables with the Assignment Operator
0:11:58 Uninitialized Variables
0:12:40 Case Sensitivity in Variables
0:14:05 Add Two Numbers
0:14:34 Subtract One Number from Another
0:14:52 Multiply Two Numbers
0:15:12 Dividing Numbers
0:15:30 Increment
0:15:58 Decrement
0:16:22 Decimal Numbers
0:16:48 Multiply Two Decimals
0:17:18 Divide Decimals
0:17:33 Finding a Remainder
0:18:22 Augmented Addition
0:19:22 Augmented Subtraction
0:20:18 Augmented Multiplication
0:20:51 Augmented Division
0:21:19 Declare String Variables
0:22:01 Escaping Literal Quotes
0:23:44 Quoting Strings with Single Quotes
0:25:18 Escape Sequences
0:26:46 Plus Operator
0:27:49 Plus Equals Operator
0:29:01 Constructing Strings with Variables
0:30:14 Appending Variables to Strings
0:31:11 Length of a String
0:32:01 Bracket Notation
0:33:27 Understand String Immutability
0:34:23 Find the Nth Character
0:34:51 Find the Last Character
0:35:48 Find the Nth-to-Last Character
0:36:28 Word Blanks
0:40:44 Arrays
0:41:43 Nest Arrays
0:42:33 Access Array Data
0:43:34 Modify Array Data
0:44:48 Access Multi-Dimensional Arrays
0:46:30 push()
0:47:29 pop()
0:48:33 shift()
0:49:23 unshift()
0:50:36 Shopping List
0:51:41 Write Reusable with Functions
0:53:41 Arguments
0:55:43 Global Scope
0:59:31 Local Scope
1:00:46 Global vs Local Scope in Functions
1:02:40 Return a Value from a Function
1:03:55 Undefined Value returned
1:04:52 Assignment with a Returned Value
1:05:52 Stand in Line
1:08:41 Boolean Values
1:09:24 If Statements
1:11:51 Equality Operator
1:13:18 Strict Equality Operator
1:14:43 Comparing different values
1:15:38 Inequality Operator
1:16:20 Strict Inequality Operator
1:17:05 Greater Than Operator
1:17:39 Greater Than Or Equal To Operator
1:18:09 Less Than Operator
1:18:44 Less Than Or Equal To Operator
1:19:17 And Operator
1:20:41 Or Operator
1:21:37 Else Statements
1:22:27 Else If Statements
1:23:30 Logical Order in If Else Statements
1:24:45 Chaining If Else Statements
1:27:45 Golf Code
1:32:15 Switch Statements
1:35:46 Default Option in Switch Statements
1:37:23 Identical Options in Switch Statements
1:39:20 Replacing If Else Chains with Switch
1:41:11 Returning Boolean Values from Functions
1:42:20 Return Early Pattern for Functions
1:43:38 Counting Cards
1:49:11 Build Objects
1:50:46 Dot Notation
1:51:33 Bracket Notation
1:52:47 Variables
1:53:34 Updating Object Properties
1:54:30 Add New Properties to Object
1:55:19 Delete Properties from Object
1:55:54 Objects for Lookups
1:57:43 Testing Objects for Properties
1:59:15 Manipulating Complex Objects
2:01:00 Nested Objects
2:01:53 Nested Arrays
2:03:06 Record Collection
2:10:15 While Loops
2:11:35 For Loops
2:13:56 Odd Numbers With a For Loop
2:15:28 Count Backwards With a For Loop
2:17:08 Iterate Through an Array with a For Loop
2:19:43 Nesting For Loops
2:22:45 Do…While Loops
2:24:12 Profile Lookup
2:28:18 Random Fractions
2:28:54 Random Whole Numbers
2:30:21 Random Whole Numbers within a Range
2:31:46 parseInt Function
2:32:36 parseInt Function with a Radix
2:33:29 Ternary Operator
2:34:57 Multiple Ternary Operators
2:36:57 var vs let
2:39:02 var vs let scopes
2:41:32 const Keyword
2:43:40 Mutate an Array Declared with const
2:44:52 Prevent Object Mutation
2:47:17 Arrow Functions
2:28:24 Arrow Functions with Parameters
2:49:27 Higher Order Arrow Functions
2:53:04 Default Parameters
2:54:00 Rest Operator
2:55:31 Spread Operator
2:57:18 Destructuring Assignment: Objects
3:00:18 Destructuring Assignment: Nested Objects
3:01:55 Destructuring Assignment: Arrays
3:03:40 Destructuring Assignment with Rest Operator to Reassign Array
3:05:05 Destructuring Assignment to Pass an Object
3:06:39 Template Literals
3:10:43 Simple Fields
3:12:24 Declarative Functions
3:12:56 class Syntax
3:15:11 getters and setters
3:20:25 import vs require
3:22:33 export
3:23:40 * to Import
3:24:50 export default
3:25:26 Import a Default Export
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=PkZNo7MFNFg&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=4

🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #learn javascript #learn javascript for beginners #learn javascript - full course for beginners #javascript programming language

Sival Alethea

Sival Alethea

1624323600

Learn Python by Building Five Games - Full Course. DO NOT MISS!!!

Learn Python in this full tutorial course for beginners. This course takes a project-based approach. We have collected five great Python game tutorials together so you can learn Python while building five games. If you learn best by doing, this is the course for you.
⭐️ Course Contents ⭐️
⌨️ (0:01:18) Pong
⌨️ (0:45:36) Snake
⌨️ (1:34:57) Connect Four
⌨️ (2:42:36) Tetris
⌨️ (4:22:12) Online Multiplayer Game
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=XGf2GcyHPhc&list=PLWKjhJtqVAbnqBxcdjVGgT3uVR10bzTEB&index=4
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#python #games #learn python by building five game #project-based approach #game in python #learn python by building five games - full course

Learning JavaScript: Working with Strings

Strings are the second most common data type used in JavaScript, and in many cases, since JavaScript is so widely used for web applications, it is the prominent data type. In this article I’ll discuss how strings work in JavaScript and how to work with them efficiently and effectively. I’ll also discuss some newer abilities of strings that are just being discovered and used.

Strings Defined

A string is any set of 0 or more characters enclosed in either single quotes or double quotes. The characters in a string can be alphabetic characters, numbers, symbols, and spaces. Here are some examples of JavaScript string literals:

"hello world"
'good bye, world!'
"1600 Pennsylvania Avenue"
'$*&!@ it!'

If you are using single quotes in your string, and you need to embed a single quote to write out a contraction, you use the backslash character (\) as an escape character. To see why you need to do this, let’s look at what happens when you don’t escape a single quote by writing out such a string in the JavaScript shell:

js> 'can't'
typein:1:5 SyntaxError: unexpected token: identifier:
typein:1:5 'can't'
typein:1:5 .....^

The interpreter can’t figure out what to do with the ‘t’ after the single quote.

Now watch what happens when we escape the single quote:

js> 'can\'t'
"can't"

The escape character tells the interpreter to treat the single quote as an apostrophe and not as an “end-of-string” character.

You can embed other characters into a string, including the newline character (\n) and the tab character (\t). Here are some examples using the shell:

js> print("Hello, \n world!");
Hello,
world!
js> print("Hello, \tworld");
Hello,  world

#javascript-training #learn-to-code #learn-to-program #javascript #javascript-tutorial #deep learning