Introduction to JavaScript👾

Carlos Giraldo & Tiffany Le-Nguyen

Prerequisites

  • Basic understanding of HTML
  • Optional basic understanding of JavaScript
  • Optional basic understanding of git
  • Optional git & GitHub account

The game (🤞)

Steps

  1. Creation of spaceship.
  2. Moving the spaceship up and down with arrows.
  3. Creation of the laser and moving laser from left to right with the spacebar.
  4. Creation of creatures that move towards the spaceship.
  5. Explosion when the laser hits the creature or the creature hits the ship.
  6. Randomnly generate creatures

Ship

Creature

Extra

  • Losing lives
  • Scoring system
  • Score saving
  • More fluid movement
  • Extra complexity (more ship and alien movement, aliens shoot you, etc.)

JavaScript

  • Programming language

  • Must be run within a host environment (browser or server)

  • Contains a standard library (bunch of pre-written js) of objects such as Array, Date and Math (built-in tools/utilities)

Starting with JavaScript🚗

Open a modern web browser like Chrome

Node.js

Node is a JavaScript runtime built on Chrome's V8 JavaScript engine

 

In short, Node lets us run JavaScript on the server (ex: directly on your computers). That's all!

Etape 0: Installation

  1. Clone/Download https://github.com/sirMerr/spaceship-game (branch 0.hello_world)

  2. Find the folder and open index.html in your chosen modern browser (chrome)

  • Select an element(s) by CSS selector (class, id, tag, etc.)
// index.html
<h1 class="exampleClass">Hi</h1>
<img src="👨‍💻"/>
<img id="uniqueId" src="👯‍♂️"/>
// main.js
const exampleClass = document.querySelector(".exampleClass");
const uniqueId = document.querySelector("#uniqueId");
const imgs = document.querySelectorAll("img"); // Array of elements

document.querySelector

 

Variables

// The value of a constant cannot change through reassignment
// and it can't be redeclared.
const iCantChange = "👾";
// Just like var, this can be changed
let changeMe = 0;

iCantChange = 2 // Error

changeMe = 1 // All good

Functions

// Function declaration
function foo1(bar) {
    console.log(bar)
}

// Equivalent in an arrow function
const foo2 = (bar) => {
    console.log(bar
}

// How to call your function
foo1("Hello freeCodeCamp Montreal!"); // Prints "Hello freeCodeCamp Montreal!"
foo2("Hello online viewers!"); // Prints "Hello online viewers!"

Class

// Class declaration
class Rectangle {
  // This runs on initiation
  constructor(height, width) {
    // this refers to the class object itself
    this.height = height;
    this.width = width;
  }

  calculateDimensions() {
    // It uses this scope's this
    return this.height * this.width;
  }
}

// You first need to declare your class and 
// then access it or you'll get an error
const rectangle = new Rectangle(30, 50);

Classes are in fact "special functions"

Creation of spaceship in the DOM

Starting point:

event listeners

The addEventListener() method attaches an event handler to the specified element.

// Define how the event should be handled
function someHandler(event) {
    console.log(event);
    console.log(event.code);
    console.log(event.keyCode);
}

// Note, we don't add () as to not run the function 
// immediately! We give it the event to listen to 
// and the handler it should run
document.addEventListener('keydown', someHandler);

event listeners

The removeEventListener() method removes an event handler from the specified element.

// Define how the event should be handled
function someHandler(event) {
    console.log(event);
}

// After this runs, a keyDown event will no longer log anything
document.removeEventListener('keydown', someHandler);

Switch

Evaluates an expression, matching the expression's value to a case, and executes statements associated with that case

function fruitHandler(fruit) {
    switch (fruit) {
      case 'Oranges':
        console.log('Orange you glad I didn\'t say Banana');
        // Terminates switch
        break;
      // Runs if fruit is Mangoes or Papayas
      case 'Mangoes':
      case 'Papayas':
        console.log('Mangoes are real');
        break;
      // Run if there's no matching case
      default:
        console.log('Sorry, we are out of ' + fruit);
    }
}

Moving the spaceship up and down

Starting point:

Create Element

// index.html
<div class="space"></div>
// someJsFile.js
const space = document.querySelector(".space");
const img = document.createElement('img');

// Set class names
img.className = "foo classB";
// Set style
img.style.right = "0px";

// Adds img to the end of the list of 
// children (elements) of the space node
space.appendChild(img);

setInterval

// Run myCallback every 500ms, or 0.5 seconds
const intervalID = window.setInterval(myCallback, 500);

function myCallback() {
  console.log("Hello");
}

// Clear the interval. You can put this in a button 
// onClick or even inside the callback itself
clearInterval(intervalID);

Repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

Creation of the laser and movement via the spacebar

Starting point:

Creation of creatures

Starting point:

Creature movement and explosion on contact

Starting point:

Randomnly generate creatures

Starting point:

Made with Slides.com