class Mario extends Player {
  [...]

  Mario() {
    super("Mario");
    setStates();
    handleKey('UP');
    handleKey('LEFT');
    handleKey('DOWN');
    handleKey('RIGHT');
    setImpulseCoefficients(DAMPENING, DAMPENING);
    setForces(0, DOWN_FORCE);
    setAcceleration(0, ACCELERATION);
  }

  // We want ot make sure all states are center/bottom anchored,
  // so that when we switch from normal to crouch and back, the
  // sprite will always be anchored to the floor.
  void addState(State st) {
    st.sprite.anchor(CENTER, BOTTOM);
    super.addState(st);
  }  
  
  // the same as before, but now with crouch and crouchjump
  void setStates() {
    addState(new State("idle", "graphics/mario/small/Standing-mario.gif"));
    addState(new State("crouching", "graphics/mario/small/Crouching-mario.gif"));
    addState(new State("running", "graphics/mario/small/Running-mario.gif", 1, 4));
    
    State jumping = new State("jumping", "graphics/mario/small/Jumping-mario.gif");
    jumping.setDuration(15);
    addState(jumping);
    SoundManager.load(jumping, "audio/Jump.mp3");

    State crouchjumping = new State("crouchjumping", "graphics/mario/small/Crouching-mario.gif");
    crouchjumping.setDuration(15);
    addState(crouchjumping);
    SoundManager.load(crouchjumping, "audio/Jump.mp3");

    setCurrentState("idle");
  }

  // When 'fixed frame count' animations end
  // such as the jump animation, what should we do?
  void handleStateFinished(State which) {
    setCurrentState("idle");
  }

  // We add in handling of the 'S' key, too
  void handleInput() {
    // we can't move left/right if we're crouching!
    if (active.name!="crouching" && (isKeyDown('A') || isKeyDown('D'))) {
      if (isKeyDown('A')) {
        setHorizontalFlip(true);
        addImpulse(-speed, 0);
      }
      if (isKeyDown('D')) {
        setHorizontalFlip(false);
        addImpulse(speed, 0);
      }
    }

    if (active.mayChange() && isKeyDown('W') && boundaries.size()>0) {
      ignore('W');
      addImpulse(0, -35);
      // regular jump, or crouch jump?
      if (active.name!="crouching") { setCurrentState("jumping"); }
      else { setCurrentState("crouchjumping"); }
      SoundManager.play(active);
    }

    // what to do when 'S' is pressed:
    if (isKeyDown('S')) {
      if (active.name=="jumping") { setCurrentState("crouchjumping"); }
      else { setCurrentState("crouching"); }
    }

    if (active.mayChange()) {
      // and finally, make sure we don't run if we're crouching
      if (active.name!="crouching" && (isKeyDown('A') || isKeyDown('D'))) {
        setCurrentState("running");
      }
      else if (noKeysDown()) { setCurrentState("idle"); }
    }
  }
  
  [...]
}

class TeleportBoundary extends Boundary {
  float teleport_location_x=0, teleport_location_y=0;

  TeleportBoundary(float x1, float y1, float x2, float y2) {
    super(x1,y1,x2,y2);   
    teleport_location_x = (x1+x2)/2;
    teleport_location_y = (y1+y2)/2;
    // set up the "plop" sound for playing when we teleport
    SoundManager.load(this,"audio/Squish.mp3");
  }
  
  // where should this teleport surface teleport actors to?
  void setTeleportLocation(float x, float y) {
    teleport_location_x = x;
    teleport_location_y = y;
  }
  
  // Teleport an actor to the predefined coordinates!
  void teleport(Actor a) {
    a.setPosition(teleport_location_x,teleport_location_y);
  }

  // when we teleport an actor, it should get a zero-impulse
  float[] STATIONARY = {0,0};
   
  // keeps Processing.js happy
  float[] redirectForce(float fx, float fy) {
    return super.redirectForce(fx,fy);
  }

  // teleport based on what the actor is doing
  float[] redirectForce(Actor a, float fx, float fy) {
    if(a.active.name=="crouching") {
      a.detachFrom(this);
      a.setCurrentState("idle");
      teleport(a);
      SoundManager.play(this);
      return STATIONARY;
    }
    else { return super.redirectForce(a,fx,fy); }
  }
}

class MainLevelLayer extends LevelLayer {
  Mario mario;
  
  MainLevelLayer(Level owner) {
    super(owner);
    addBackgroundSprite(new TilingSprite(new Sprite("graphics/backgrounds/sky.gif"),0,0,width,height));

    // set up Mario!
    mario = new Mario();
    mario.setPosition(32, height-64);
    addPlayer(mario);

    // we don't want mario to walk off the level, so we keep the side walls
    addBoundary(new Boundary(-1,0, -1,height));
    addBoundary(new Boundary(width+1,height, width+1,0));

    // the ground now has an unjumpable gap:
    addGround("ground", -32,height-48, width/2-96,height);
    addGround("ground", width/2 + 49,height-48, width+32,height);

    // then, add two teleporters on either side of the gap
    Teleporter t1 = addTeleporter(width/4+20, height-48);
    Teleporter t2 = addTeleporter(3*width/4-68, height-48);

    // and we link them together, so they teleport to each other
    t1.teleportTo(t2);
    t2.teleportTo(t1);
  }

  // for convenience we change the draw function
  // so that if Mario falls outside the screen,
  // we put him back at his start position:
  void draw() {
    super.draw();
    if(mario.y>height+64) { mario.setPosition(32,height-64); }
  }

  // Add a teleporter to the scene, and make sure to give
  // back a reference to it so that we can use that to link
  // up two (or more!) teleporters.
  Teleporter addTeleporter(float x, float y) {
    Teleporter t = new Teleporter(x, y);
    addBoundedInteractor(t);
    return t;
  }
  
  // same function as before
  void addGround(String tileset, float x1, float y1, float x2, float y2) {
    [...]
  }
}

class MainLevelLayer extends LevelLayer {
  Mario mario;
  
  MainLevelLayer(Level owner) {
    [...]

    // add two teleporters on either side of the gap
    Pipe t1 = addPipe(width/4-16, height-48);
    Pipe t2 = addPipe(3*width/4-64, height-48);

    // and link them together
    t1.teleportTo(t2);
    t2.teleportTo(t1);
  }

  [...]

  /**
   * Add a teleporter pipe
   */
  Pipe addPipe(float x, float y) {
    Pipe p = new Pipe(x, y);
    addBoundedInteractor(p);
    addForegroundSprite(p.head);
    addForegroundSprite(p.body);
    addTrigger(p.trigger);
    return p;
  }
  
  [...]
}

class Pipe extends BoundedInteractor {
  Lid lid;
  Sprite head, body;
  TeleportTrigger trigger;
  
  Pipe(float x, float y) {
    super("Teleporter");
    setPosition(x,y);

    // set up the sprite graphics
    head = new Sprite("graphics/assorted/Pipe-head.gif");
    head.align(LEFT,BOTTOM);
    head.setPosition(x,y-16);
    body = new Sprite("graphics/assorted/Pipe-body.gif");
    body.align(LEFT,BOTTOM);
    body.setPosition(x,y);
    
    // add the five boundaries, of which the top is a special "lid" boundary
    lid = new Lid(x,y-48, x+32,y-48);
    addBoundary(lid);
    addBoundary(new Boundary(x+32,y-48, x+32,y));
    addBoundary(new Boundary(x+32,y, x,y));
    addBoundary(new Boundary(x,y, x,y-48));

    // a hidden boundery inside the pipe, so we don't fall through
    addBoundary(new Boundary(x,y-8, x+32,y-8));

    // and set up our teleport trigger
    trigger = new TeleportTrigger(x+2,y-10,28,2);
    trigger.setLid(lid);
  }

  void teleportTo(Pipe other) {
    trigger.setDestination(other.x+16, other.y-24);
  }
}

class Lid extends Boundary {
  Lid(float x1, float y1, float x2, float y2) {
    super(x1,y1,x2,y2);
  }

  // when we teleport an actor, it should get a zero-impulse
  float[] STATIONARY = {0,0};
   
  // keeps Processing.js happy
  float[] redirectForce(float fx, float fy) {
    return super.redirectForce(fx,fy);
  }

  // teleport based on what the actor is doing
  float[] redirectForce(Actor a, float fx, float fy) {
    if(a.active.name=="crouching") {
      disable();
    }
    return super.redirectForce(a,fx,fy);
  }
}

class TeleportTrigger extends Trigger {
  Lid lid;
  float teleport_x, teleport_y;
  
  // we build a trigger with the classic "brrp brrp brrp" sound
  TeleportTrigger(float x, float y, float w, float h) {
    super("Teleporter",x,y,w,h);
    SoundManager.load(this, "audio/Pipe.mp3");
  }
  
  // we'll need to enable the pipe lid when we teleport
  void setLid(Lid l) { lid = l; }
  
  // we'll also need to know WHERE to teleport to =)
  void setDestination(float x, float y) {
    teleport_x = x;
    teleport_y = y;
  }
  
  // when the trigger is activated...
  void run(LevelLayer level, Actor actor, float[] intersection) {
    //... enable the lid again, so it's a real boundary again,
    lid.enable();
    // and teleport the actor,
    actor.setPosition(teleport_x,teleport_y);
    // and give it an upward jump, 
    actor.setImpulse(0,-30);
    // and play the brrp brrp brrp sound!
    SoundManager.play(this);
  }
}

class MainLevel extends Level {
  MainLevel(float levelWidth, float levelHeight) {
    super(levelWidth, levelHeight);
    addLevelLayer("background layer", new BackgroundLayer(this));
    LayerSuperClass mainLayer = new MainLevelLayer(this);
    addLevelLayer("main layer", mainLayer);
    setViewBox(0,0,screenWidth,screenHeight);
    
    // set up Mario in the main layer
    mario = new Mario();
    mario.setPosition(32, height-64);
    mainLayer.mario = mario;
    mainLayer.addPlayer(mario);
  }
}

class LayerSuperClass extends LevelLayer {
  // our intrepid hero. Or rather, a variable that can hold him.
  Mario mario;
  
  // fallthrough constructors
  LayerSuperClass(Level owner) {
    super(owner); }

  LayerSuperClass(Level owner, float w, float h, float tx, float ty, float sx, float sy) {
    super(owner,  w,h,  tx,ty,  sx,sy); }

  // moved here from MainLevelLayer, so we can all it in the background layer too
  void addGround(String tileset, float x1, float y1, float x2, float y2) {
    [...]
  }

  // New: a layer "teleport" method
  void moveToLayer(Player p, String layerName) {
    // first, remove the player from "this" layer
    removePlayer(p);
    mario = null;
    // then, inject the player into the other layer
    LayerSuperClass other = (LayerSuperClass) parent.getLevelLayer(layerName);
    other.mario = p;
    p.setPosition(64, -64);
    other.addPlayer(p);
  }
}

class BackgroundLayer extends LayerSuperClass {
  BackgroundLayer(Level owner) {
    [...]
    addBoundary(new Boundary(-1,0, -1,height));
    addBoundary(new Boundary(width+1,height, width+1,0));
    addGround("ground", 0, height/2, width, height/2+16);
  }
  
  // if mario falls off, teleport to foreground
  void draw() {
    super.draw();
    if(mario != null && mario.y>height+64) {
      moveToLayer(mario, "main layer");
    }
  }
}

class MainLevelLayer extends LayerSuperClass {  
  MainLevelLayer(Level owner) {
    super(owner);
    addBoundary(new Boundary(-1,0, -1,height));
    addBoundary(new Boundary(width+1,height, width+1,0));
    addGround("ground", -32,height-48, width/2-96,height);
  }

  // if mario falls off, teleport to background  
  void draw() {
    super.draw();
    if(mario != null && mario.y>height+64) {
      moveToLayer(mario, "background layer");
    }
  }
}

class MarioLevel extends Level {
  Mario mario;
  MarioLevel(float levelWidth, float levelHeight) {
    super(levelWidth, levelHeight);
  }
  void swapForLevel(String otherLevel) {
    setActiveScreen(otherLevel);
  }
}

class MarioLayer extends LevelLayer {
  MarioLayer(Level owner) {
    super(owner); 
  }

  void addGround(String tileset, float x1, float y1, float x2, float y2) {
    [... you kow what this code does by now ...]
  }
}

class LevelOne extends MarioLevel {
  LevelOne(float w, float h) {
    super(w, h);
    addLevelLayer("main layer", new LevelOneLayer(this));
    setViewBox(0,0,w,h);
    // set up a mario
    mario = new Mario();
    mario.setPosition(32, height-64);
    getLevelLayer("main layer").addPlayer(mario);
  }

  void mousePressed(int mx, int my, int mb) {
    if(mb == RIGHT) swapForLevel("Level Two");
  }
}

class LevelOneLayer extends MarioLayer {
  LevelOneLayer(Level owner) {
    super(owner);
    setBackgroundColor(color(0, 100, 190));
    addBackgroundSprite(new TilingSprite(new Sprite("graphics/backgrounds/sky.gif"),0,0,width,height));
    addBoundary(new Boundary(-1,0, -1,height));
    addBoundary(new Boundary(width+1,height, width+1,0));
    addGround("ground", 0,height-48, width,height);
  }
}

class LevelTwo extends MarioLevel {
  LevelTwo(float w, float h) {
    super(w, h);
    addLevelLayer("main layer", new LevelTwoLayer(this));
    setViewBox(0,0,w,h);
    // set up another mario
    mario = new Mario();
    mario.setPosition(32, height-64);
    getLevelLayer("main layer").addPlayer(mario);
  }

  void mousePressed(int mx, int my, int mb) {
    if(mb == RIGHT) swapForLevel("Level One");
  }
}

class LevelTwoLayer extends MarioLayer {
  LevelTwoLayer(Level owner) {
    super(owner);
    setBackgroundColor(color(0, 0, 100));
    addBackgroundSprite(new TilingSprite(new Sprite("graphics/backgrounds/bonus.gif"),0,0,width,height));
    addBoundary(new Boundary(-1,0, -1,height));
    addBoundary(new Boundary(width+1,height, width+1,0));
    addGround("cave", 0,height-48, width,height);
  }
}
 

Javascript Online Compiler

Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

About Javascript

Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

Key Features

  • Open-source
  • Just-in-time compiled language
  • Embedded along with HTML and makes web pages alive
  • Originally named as LiveScript.
  • Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc.

Syntax help

STDIN Example

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log("Hello, " + line);
});

variable declaration

KeywordDescriptionScope
varVar is used to declare variables(old way of declaring variables)Function or global scope
letlet is also used to declare variables(new way)Global or block Scope
constconst is used to declare const values. Once the value is assigned, it can not be modifiedGlobal or block Scope

Backtick Strings

Interpolation

let greetings = `Hello ${name}`

Multi line Strings

const msg = `
hello
world!
`

Arrays

An array is a collection of items or values.

Syntax:

let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);

Example:

let mobiles = ["iPhone", "Samsung", "Pixel"];

// accessing an array
console.log(mobiles[0]);

// changing an array element
mobiles[3] = "Nokia";

Arrow functions

Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

Syntax:

() => expression

Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
                                    .map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);

De-structuring

Arrays

let [firstName, lastName] = ['Foo', 'Bar']

Objects

let {firstName, lastName} = {
  firstName: 'Foo',
  lastName: 'Bar'
}

rest(...) operator

 const {
    title,
    firstName,
    lastName,
    ...rest
  } = record;

Spread(...) operator

//Object spread
const post = {
  ...options,
  type: "new"
}
//array spread
const users = [
  ...adminUsers,
  ...normalUsers
]

Functions

function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
  console.log(`Hello ${name}!`);
}
 
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar

Loops

1. If:

IF is used to execute a block of code based on a condition.

Syntax

if(condition){
    // code
}

2. If-Else:

Else part is used to execute the block of code when the condition fails.

Syntax

if(condition){
    // code
} else {
    // code
}

3. Switch:

Switch is used to replace nested If-Else statements.

Syntax

switch(condition){
    case 'value1' :
        //code
        [break;]
    case 'value2' :
        //code
        [break;]
    .......
    default :
        //code
        [break;]
}

4. For

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
//code  
} 

5. While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
  // code 
}  

6. Do-While

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
  // code 
} while (condition); 

Classes

ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

Syntax:

class className {
  constructor() { ... } //Mandatory Class method
  method1() { ... }
  method2() { ... }
  ...
}

Example:

class Mobile {
  constructor(model) {
    this.name = model;
  }
}

mbl = new Mobile("iPhone");