/* Create a class that represents a grid of squares on the screen. The number of squares in the x and y dimensions should be defined by a parameter in the initalizer. The initializer should also have parameters that define the size of the squares and the thickness of their borders. Each square can be either on or off. The class should keep track of which squares are on and which squares are off and it should expose a method for setting individual squares on or off, as well as a method to clear the grid by setting all of the squares to off. It should then have a draw method that draws all the squares. If the square is off, it should be filled black, otherwise it should be filled white. The border should be gray in both cases. The squares should be right next to each other, such that their borders overlap. */

function Grid(x, y, size, border) {
  this.x = x;
  this.y = y;
  this.size = size;
  this.border = border;
  this.grid = [];
  this.createGrid();
}
Grid.prototype.createGrid = function() {
  for (var i = 0; i < this.x; i++) {
    this.grid[i] = [];
    for (var j = 0; j < this.y; j++) {
      this.grid[i][j] = {
        on: false,
        x: i,
        y: j
      };
    }
  }
};
Grid.prototype.setSquare = function(x, y, on) {
  this.grid[x][y].on = on;
};
Grid.prototype.clear = function() {
  for (var i = 0; i < this.x; i++) {
    for (var j = 0; j < this.y; j++) {
      this.grid[i][j].on = false;
    }
  }
};
Grid.prototype.draw = function() {
  for (var i = 0; i < this.x; i++) {
    for (var j = 0; j < this.y; j++) {
      var square = document.createElement('div');
      square.style.width = this.size + 'px';
      square.style.height = this.size + 'px';
      square.style.border = this.border + 'px solid gray';
      square.style.position = 'absolute';
      square.style.left = i * (this.size + this.border) + 'px';
      square.style.top = j * (this.size + this.border) + 'px';
      if (this.grid[i][j].on) {
        square.style.backgroundColor = 'white';
      } else {
        square.style.backgroundColor = 'black';
      }
      document.body.appendChild(square);
    }
  }
};

/* Create a class repesenting a snake that takes as initial parameters the size of the snake (an integer) and a grid object.  The snake should store whether it is dead or alive. It should initally be alive. The snake should also store a list of x and y indices representing the squares on the grid that the snake is composed of. Initially the list should be empty. Upon initialization, a number of squares equal to the size of the snake should be added to the list, starting from the square in the bottom center of the grid and moving upwards. Do not allow snake sizes larger than the height of the grid nor sizes smaller than 2. Add a method that moves the snake, with a parameter that tells the snake whether to rotate clockwise, anti-clockwise or not at all when moving, and another parameter that tells whether the snake should grow. The method first checks which direction the snake is facing by checking whether the last square is left, right, up or down relative to the position of the second to last square in the list. After that modify the direction based on the rotation parameter (for example, if we're facing left and the rotation is clockwise, we should now be facing up) . Once that is done, find the square that is next to the last one in the direction that we have just computed. If the square is out of the range of the grid, set the snake to dead. Also set the snake to dead if the new square is already inside the list of squares. Regardless of that, add the new square to the list. If the grow parameter is false, remove the first square from the list, otherwise don't do that. The snake class should also have a draw method that goes through each square in the list, and turns on the coresponding square in the grid. */

function Snake(size, grid) {
  this.size = size;
  this.grid = grid;
  this.alive = true;
  this.snake = [];
  this.createSnake();
}
Snake.prototype.createSnake = function() {
  var x = Math.floor(this.grid.x / 2);
  var y = this.grid.y - 1;
  for (var i = 0; i < this.size; i++) {
    this.snake[i] = {
      x: x,
      y: y
    };
    y--;
  }
};
Snake.prototype.move = function(rotation, grow) {
  var last = this.snake[this.snake.length - 1];
  var secondToLast = this.snake[this.snake.length - 2];
  var direction = 'right';
  if (last.x < secondToLast.x) {
    direction = 'left';
  } else if (last.y < secondToLast.y) {
    direction = 'up';
  } else if (last.y > secondToLast.y) {
    direction = 'down';
  }
  if (rotation === 'clockwise') {
    if (direction === 'right') {
      direction = 'up';
    } else if (direction === 'up') {
      direction = 'left';
    } else if (direction === 'left') {
      direction = 'down';
    } else if (direction === 'down') {
      direction = 'right';
    }
  } else if (rotation === 'counterclockwise') {
    if (direction === 'right') {
      direction = 'down';
    } else if (direction === 'down') {
      direction = 'left';
    } else if (direction === 'left') {
      direction = 'up';
    } else if (direction === 'up') {
      direction = 'right';
    }
  }
  var newSquare = {};
  if (direction === 'right') {
    newSquare = {
      x: last.x + 1,
      y: last.y
    };
  } else if (direction === 'left') {
    newSquare = {
      x: last.x - 1,
      y: last.y
    };
  } else if (direction === 'up') {
    newSquare = {
      x: last.x,
      y: last.y - 1
    };
  } else if (direction === 'down') {
    newSquare = {
      x: last.x,
      y: last.y + 1
    };
  }
  if (newSquare.x < 0 || newSquare.x >= this.grid.x || newSquare.y < 0 || newSquare.y >= this.grid.y || this.snake.indexOf(newSquare) !== -1) {
    this.alive = false;
  } else {
    this.snake.push(newSquare);
    if (!grow) {
      this.snake.shift();
    }
  }
};
Snake.prototype.draw = function() {
  for (var i = 0; i < this.snake.length; i++) {
    this.grid.setSquare(this.snake[i].x, this.snake[i].y, true);
  }
};

/* Add a class that describes food and takes a grid object as a parameter. The food object should store its position in the grid with x and y indices. Add a regenerate method that takes a list of pairs of coordinates called blacklist as a parameter. In the regenerate method generate a list of all the possible pairs of coordinates in the grid, excluding the ones in the blacklist list, then pick a random pair and set it as the food's position. The class should also have a method that draws the food by turning the appropriate square in the grid on. */

function Food(grid) {
  this.grid = grid;
  this.position = {
    x: 0,
    y: 0
  };
  this.regenerate();
}
Food.prototype.regenerate = function(blacklist) {
  var possiblePositions = [];
  for (var i = 0; i < this.grid.x; i++) {
    for (var j = 0; j < this.grid.y; j++) {
      possiblePositions.push({
        x: i,
        y: j
      });
    }
  }
  if (blacklist) {
    for (var i = 0; i < blacklist.length; i++) {
      var index = possiblePositions.indexOf(blacklist[i]);
      if (index !== -1) {
        possiblePositions.splice(index, 1);
      }
    }
  }
  var randomIndex = Math.floor(Math.random() * possiblePositions.length);
  this.position = possiblePositions[randomIndex];
};
Food.prototype.draw = function() {
  this.grid.setSquare(this.position.x, this.position.y, true);
};

/* Add a reset method to the snake that clears its square list, calls createSnake, and sets it to alive. */

Snake.prototype.reset = function() {
  this.snake = [];
  this.createSnake();
  this.alive = true;
};

/* Add a game class that takes a grid object and creates new snake and food objects. The size of the snake should be 2. In the constructor call the food's regenerate method with the snake's square list as the blacklist. The game should also keep track of whether the snake has eaten anything with a booelan hasEaten, which should be set to false. Another variable should be used to keep track of which direction we want the snake to rotate (clockwise, counterclockwise or no rotation). By default it should be set to no rotation. Add an update method that moves the snake, and pass it the hasEaten variable as the grow parameter. Then check if the snake's last square is the same as the square that the food is on. If it is, set hasEaten to true, and regenerate the food with snake's squares as the blacklist parameter. Otherwise just set hasEaten to false. Next set the direction variable to "no rotation". Finally check if the snake is dead. If it's dead, display a message saying "The snek has commit die" with an Ok button. After the user presses the Ok button, call the snake's reset method, and then regenerate the food. Add a draw method that first clears the grid, then draws the snake and the food, and finally draws the grid. */

function Game(grid) {
  this.grid = grid;
  this.snake = new Snake(2, grid);
  this.food = new Food(grid);
  this.hasEaten = false;
  this.direction = 'no rotation';
  this.food.regenerate(this.snake.snake);
  this.update();
}
Game.prototype.update = function() {
  this.snake.move(this.direction, this.hasEaten);
  if (this.snake.alive) {
    if (this.snake.snake[this.snake.snake.length - 1].x === this.food.position.x && this.snake.snake[this.snake.snake.length - 1].y === this.food.position.y) {
      this.hasEaten = true;
      this.food.regenerate(this.snake.snake);
    } else {
      this.hasEaten = false;
    }
    this.direction = 'no rotation';
  } else {
    alert('The snek has commit die');
    this.snake.reset();
    this.food.regenerate();
  }
};
Game.prototype.draw = function() {
  this.grid.clear();
  this.snake.draw();
  this.food.draw();
  this.grid.draw();
};

/* Now create a 10 by 10 grid with square size of 50 pixels and border width of 3 pixels and pass it to a new game object. */

var grid = new Grid(10, 10, 50, 3);
var game = new Game(grid);

/////////////// I exceeded the length limit here, so I had to continue with a fresh instance /////////////////

/* Create a function that takes as an argument a variable named game and stores it into a global variable. */
function setGame(game) {
  window.game = game;
}

/* game is an object that has two methods called update and draw, and a string variable called direction that can either be "clockwise", "counterclockwise" or "no rotation". When the left arrow key is pressed, set the game's direction variable to "counterclockwise". When the right arrow key is pressed, set it to "clockwise". */
game.direction = 'no rotation';
document.addEventListener('keydown', function(e) {
  if (e.keyCode == 37) {
    game.direction = 'counterclockwise';
  } else if (e.keyCode == 39) {
    game.direction = 'clockwise';
  }
});

/* Now create a loop that draws and updates game every half a second. */
setInterval(function() {
  gasme.update();
  game.draw();
}, 500) 

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");