mdiehr / Spielmatrix

A tile-based game engine for prototyping abstract games.
3 stars 0 forks source link

Implement sprite/component system #13

Open mdiehr opened 9 years ago

mdiehr commented 9 years ago

Similar to the Perlenspiel "Saccade" component engine.

Entity hierarchy:

entity      Base class for every game object/piece/component
scene       Object with timing loop to hold game pieces
component   Object that automatically pairs with parent
sprite      Object with dimensions and collision implications
extend      Prototypal inheritance
constants   Object type and direction enumerations
utils       Miscellaneous functionality

Example component:

// Add balls to parent on touch
var RectBorder = component.extend({
    name: "RectBorder",
    type: ComponentType,

    create: function(parent, width) {
        var self = component.create.call(this, parent);
        self.width = width;
        return self;
    },

    render: function(x, y) {
        var p = this.getParent();
        var l = p.x;
        var t = p.y;
        var r = l + p.w-1;
        var b = t + p.h-1;
        // Borders
        for (var x = l; x <= r; ++x) {
            PS.border(x, t, {top:this.width});
            PS.border(x, b, {bottom:this.width});
        }
        for (var y = t; y <= b; ++y) {
            PS.border(l, y, {left:this.width});
            PS.border(r, y, {right:this.width});
        }
    },
});

Example sprite which uses this component:

// Solid wall
var Wall = sprite.extend({
    name: "Wall",
    create: function (x, y, w, h) {
        var self = sprite.create.call(this, x, y, w, h);
        self.color = 0x444444;
        self.borderColor = 0x223322;
        self.spawnComponent(RectBorder, 4);
        return self;
    },

    sleep: function() {
        PS.audioPlay("fx_squish");
    },

    render: function() {
        var l = this.x;
        var t = this.y;
        var r = l + this.w-1;
        var b = t + this.h-1;
        for (var x = l; x <= r; ++x) {
            for (var y = t; y <= b; ++y) {
                if (InBounds(x, y)) {
                    PS.color(x, y, this.color);
                    PS.borderColor(x, y, this.borderColor);
                    PS.border(x, y, 0);
                    PS.scale(x, y, 100);
                    PS.radius(x, y, 0);
                }
            }
        }
    },
});