Newer
Older
game_template / script.js
window.addEventListener('load', function() {

    const canvas = this.document.getElementById('canvas1');
    const ctx = canvas.getContext('2d');
    canvas.width = 1500;
    canvas.height = 500;

    class InputHandler {
        constructor(game) {
            this.game = game;
            window.addEventListener('keydown', e => {
                if ((e.key === 'ArrowUp') && (this.game.keys.indexOf(e.key) === -1)) {
                    this.game.keys.push(e.key);
                }
                console.log(this.game.keys);
            });
            window.addEventListener('keyup', e => {
                if (this.game.keys.indexOf(e.key) > -1) {
                    this.game.keys.splice(this.game.keys.indexOf(e.key), 1);
                }
                console.log(this.game.keys);
            });
        }
    }
    class Projectile {

    }
    class Particle {

    }
    class Player {
        constructor(game) {
            this.game = game;
            this.width = 120;   // width of single sprite in Sprite sheet used in course
            this.height = 190;  // height of single sprite in sprite sheet
            this.x = 20;
            this.y = 100;
            this.speedY = 0;
        }
        update() {
            this.y += this.speedY;
        }
        draw(context) {
            context.fillRect(this.x, this.y, this.width, this.height);
        }
    }
    class Enemy {

    }
    class Layer {

    }
    class Background {d

    }
    class UI {

    }
    class Game {
        constructor(width, height) {
            this.wdith = width;
            this.height = height;
            this.player = new Player(this);
            this.input = new InputHandler(this);
            this.keys = [];
        }
        update() {
            this.player.update();
        }
        draw(context) {
            this.player.draw(context);
        }
    }

    const game = new Game(canvas.width, canvas.height);
    // animation loop
    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        game.update();
        game.draw(ctx);
        requestAnimationFrame(animate);
    }
    animate();
});

/*
Ref: Make Your Own Animated 2D Games
Author: Frank Dvorak 
Udemy Course

---
Classes need to be defined in particular order.  Classes are hoisted but 
if hoisted classes are NOT initialized.  Therefore any class that is used by
another class must be defined prior to being used. 
(Module 3: Object Orientd Programming with JavaScript, ~2m20s)
*/