Game Programming HW1

University of Reddit Learn Game Programming Lesson 1 Homework

HTML

<canvas id="stage">It seems your current browser does not support HTML5 Canvas. Please try using one of the following browsers: <a href="http://www.mozilla.org/firefox">Firefox</a>
 <a href="http://www.google.com/chrome">Google Chrome</a>

</canvas>

CSS

body {
    background-color: #111;
    color: #eee;
    margin: 0;
    padding: 0;
}
#stage {
    display: block;
}

JavaScript

function removeObjFromArray(obj, a) {
    a.splice(a.indexOf(obj), 1);
}

function Game(canvas) {
    this.canvas = canvas || document.createElement("canvas");
    this.stageWidth = 800;
    this.stageHeight = 600;
    this.canvas.width = this.stageWidth;
    this.canvas.height = this.stageHeight;
    this.ctx = this.canvas.getContext("2d");
    this.timer = 0;
    this.dt = 1 / 50; // seconds/frame
    this.objects = [];
    this.players = [];
    this.img = {};
    this.input = {
        up: false,
        down: false,
        left: false,
        right: false
    };
}

// Dictionary mapping each key code to its corresponding input
Game.prototype.inputBindings = (function () {
    var b = {};
    b["W".charCodeAt(0)] = b[38] = "up";
    b["A".charCodeAt(0)] = b[37] = "left";
    b["S".charCodeAt(0)] = b[40] = "down";
    b["D".charCodeAt(0)] = b[39] = "right";
    return b;
})();

// Set the canvas size; call with no params means full viewport
Game.prototype.setSize = function (w, h) {
    if (typeof w !== "number" || typeof h !== "number") {
        if (window.innerWidth !== "number") {
            w = document.documentElement.clientWidth;
            h = document.documentElement.clientHeight;
        } else {
            w = window.innerWidth;
            h = window.innerHeight;
        }
    }
    this.canvas.width = this.stageWidth = w;
    this.canvas.height = this.stageHeight = h;
};

// Add an image to the game under a name in the Game.img object
Game.prototype.loadImg = function (name, src, fn) {
    if (!name || !src) return;
    var img = (this.img[name] = new Image());
    img.src = src;
    if (typeof fn === "function") img.onload = fn;
};

// Adds a player object to the Game.objects and Game.players arrays
Game.prototype.addPlayer = function (x, y) {
    var player = {
        type: "player",
        x: x,
        y: y,
        vx: 0,
        vy: 0,
        w: 50,
        h: 50
    };
    this.objects.push(player);
   ...