Lunar Lander (HTML Canvas)

--Maija Kekkonen 2016--

HTML

<body>
  <canvas id="canvas" width="300" height="300"></canvas>
  <p>LUNAR LANDER</p>
  <p>L/R arrow keys move, up arrow thrusts</p>
  <p>Land gently onto the <b><i>flat surface</i></b></p>
</body>

CSS

body {
  background-color:black;
}

p {
  font-family:monospace;
  color:green;
}

JavaScript

var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");

var N_POINTS = 15;
var CANVAS_DIM = 300;
var CONTOUR_HEIGHT = 150;
var EPSILON = 0.00001;

var map = [];
var flatIndex;
var ship = createShip();
var shipCopy;
var shipLocation = new VectorPoint(CANVAS_DIM / 2, 15);
var velocity = new VectorPoint(0, 0);
var accel = new VectorPoint(0, 0);
var g = new VectorPoint(0, 1 / 15);
var friction = new VectorPoint(1.5, 0);
var died = false;

run();

function initMap() {
	// get the location where the landing area will be located
	flatIndex = Math.floor(Math.random() * N_POINTS); 
	for(var i = 0; i < N_POINTS - 1; i++) {
  		// get the y-coordinate for the contour map
  		var value = Math.random() * CONTOUR_HEIGHT + (CANVAS_DIM - CONTOUR_HEIGHT); 
  		map.push(value);
      // add two same coordinates to the map to generate the landing area
    	if(i == flatIndex)
      	map.push(value);
    }
}

function drawMap() {
	c.beginPath();
  c.strokeStyle = "#00ff00"; // green
  c.moveTo(0, map[0]); // start drawing
  // loop through the contour map, draw it
	for(var i = 1; i < N_POINTS; i++)
  	c.lineTo(i * 20, map[i]);
  c.stroke(); // draw
}

function createShip() {
	// generate the ship according to the origin (the intersection of X and Y axes)
	var body = [
  	new VectorPoint(-7, -7),
    new VectorPoint(7, -7),
    new VectorPoint(7, 7),
    new VectorPoint(-7, 7)
  ];
  var antenna = [
  	new VectorPoint(-3, -10),
    new VectorPoint(0, -7),
    new VectorPoint(3, -10)
  ];
  return new Ship(antenna, body);
}

function drawShip(microseconds) {
	velocity = VectorFunctions.add(velocity, accel);
  velocity = VectorFunctions.add(velocity, g);
  shipLocation = VectorFunctions.add(shipLocation, velocity);
  if(shipLocation.x > CANVAS_DIM) {
  	shipLocation.x = CANVAS_DIM;
    resetVA(true);
  }
  if(shipLocation.x < 0) {
  	shipLocation.x = 0;
    resetVA(true);
  }
  if(shipLocation.y > CANVAS_DIM) {
  	shipLocation.y = CANVAS_DIM;
    resetVA();
 ...