Simple Observer with JavaScript

April 24th, 2012 No comments

Something quick I threw together. (note that “Machinespark” is just my namespace)

var Machinespark = Machinespark || {};
 
Machinespark.Event = function () {
  this.f = [];
};
 
Machinespark.Event.prototype.subscribe = function (fn) {
  this.f.push(fn);
};
 
Machinespark.Event.prototype.fire = function () {
  for (var i in this.f) this.f[i](arguments);
};
 
var evFoo = new Machinespark.Event();
evFoo.subscribe(function (a, b, c) {
  // ...
});
 
evFoo.fire('foo', 'bar', 'baz');
Categories: JavaScript Tags:

Canvas Tile System

September 15th, 2011 No comments

Here’s something quick that I put together to see how easily I could create a Tile System (as in 2d sprite map for games) using JavaScript and Canvas.

First I set out to create a system for loading, caching, and retrieving the tiles. Here’s what I came up with:

// Allows you to load image sprite and then make cached tiles
// that can be retrieved
var TileLibrary = function (img) {
  var oTileLibrary = {},
      elCanvas = document.createElement('canvas'),
      cxCanvas = elCanvas.getContext('2d');
 
  elCanvas.width  = img.width;
  elCanvas.height = img.height;
  cxCanvas.drawImage(img, 0, 0, img.width, img.height);
 
  return {
    makeType: function (name, x, y, width, height) {
      oTileLibrary[name] = cxCanvas.getImageData(x, y, width, height);
    },
    getTileData: function (name) {
      return oTileLibrary[name];
    }
  };
};

 

This allows me to take an Image object and turn pieces of it into data that canvas can understand. Usage would look something like this:

// img is a preloaded image object
var oTileLibrary = new TileLibrary(img);
 
// cuts out a chunk of the image at (0, 0) with dimensions 64x64 and caches it
oTileLibrary.makeType("FloorTile", 0, 0, 64, 64);
 
// gets the ImageData out of cache and ready to be dumped into a canvas
var tFloorTile = oTileLibrary.getTileData("FloorTile");
 
// inserts that floor tile into its final destination
myCanvas.putImageData(tFloorTile, 0, 0);

 

I ended up borrowing this image for my prototype:
Desert Sprite Map

( http://www.lostgarden.com/2006/02/250-free-handdrawn-textures.html )

 

I cut out the third tile and the fourth tile, and arranged them in a 3×3 grid, with the middle tile being the little circle looking thing.

Check out the sample here: Tile System Prototype

Categories: JavaScript Tags:

Canvas Pixel Manipulation a’ la Quick and Dirty

September 9th, 2011 No comments

In a recent prototype I attempted to load in a PNG onto a canvas, change the image to a silhouette, as well as create a desaturated version, cache all three (including the initial state) sets of pixel data, and swap them out interchangeably. Then I wanted to spit the data back out into something I could incorporate into the DOM.

Here’s what I came up with: Canvas Pixel Manipulation

Categories: JavaScript Tags:

PHP Singleton Database Class

August 31st, 2011 No comments

Here’s a newer iteration of the PHP Database class I tend to prototype with. This one is cleaner than its predecessor.

Usage:

# Config
$aSettings = array(
  'username'  => 'foo',
  'password'  => 'xxxxxx',
  'host'      => 'localhost',
  'db'        => 'my_database'
);
 
# Get Instance, Settings, and Connect
$Db = Db::getInstance();
$Db->Settings($aSettings);
$Db->Connect();
 
# Set Query
$sQuery = "INSERT INTO `table` VALUES (`foo`,`bar`) VALUES ('value', 'value')";
$Db->Set($sQuery);
 
# Get Query
$sQuery = "SELECT * FROM table";
$aResults = $Db->Get($sQuery); // Returns an Array of Rows
 
echo $aResults[0]['foo']; // First row of "foo" Column
 
# Count
$iCounted = $Db->Count('table', "WHERE `bla`='blue'"); // Returns a Number
 
# Sanitize String
$sString = "This isn't unusual";
$sCleanString = $Db->Clean($sString);

And the Class:

<?php
  class Db {
 
    private $ref;
    private $settings;
    private $is_connected;
    private $errors = array();
 
    private static $singleton;
 
    public function __construct () {
      $this->is_connected = false;
    }
 
    public static function getInstance () {
      if(!self::$singleton) self::$singleton = new self();
      return self::$singleton;
    }
 
    public function Settings ($aSettings) {
      $this->settings = $aSettings;
    }
 
    public function Connect () {
      if($this->is_connected) $this->Disconnect();
 
      $this->ref = mysql_connect(
        $this->settings['host'],
        $this->settings['username'],
        $this->settings['password'],
        true
      );
 
      if(!$this->ref) {
        array_push($this->errors, mysql_error());
        return false;
      }
 
      $bSelectDatabase = mysql_select_db(
        $this->settings['db'],
        $this->ref
      );
 
      if(!$bSelectDatabase) {
        array_push($this->errors, mysql_error());
        return false;
      }
 
      $this->is_connected = true;
      return true;
    }
 
    public function Disconnect () {
      mysql_close($this->ref);
      $this->is_connected = false;
    }
 
    public function Clean ($sString) {
      if($this->is_connected) return mysql_real_escape_string($sString);
    }
 
    public function Set ($sQuery) {
      $bSet = mysql_query($sQuery, $this->ref);
      if(!$bSet) {
        array_push($this->errors, mysql_error());
        return false;
      }
 
      return true;
    }
 
    public function Get ($sQuery) {
      $sqlResults = mysql_query($sQuery, $this->ref);
 
      if(!$sqlResults) {
        array_push($this->errors, mysql_error());
        return false;
      }
 
      $aResults = array();
      while($aRow = mysql_fetch_array($sqlResults, MYSQL_ASSOC)) {
        $aResults[] = $aRow;
      }
 
      return $aResults;
    }
 
    public function Count ($sTable, $sCondition) {
      $sQuery = "SELECT COUNT(*) AS 'COUNT' FROM `$sTable` $sCondition";
      $aResults = $this->Get($sQuery);
 
      return $aResults[0]['COUNT'];
    }
 
    public function Errors() {
      return $this->errors;
    }
 
  }
?>
Categories: PHP Tags:

JavaScript Timer Countdown

August 2nd, 2011 No comments

Working on a new game. Wrote this TimerCountdown object for a Timer in the game. Works pretty well, still not fully tested.

var TimerCountdown = function() {
  var oOnZero     = function(){},
      oOnUpdate   = function(){},
      oTimer,
      iCurTime    = 0;
 
  function CreateTimer() {
    oTimer = setInterval(IterateTimer, 1000)
  }
 
  function DestroyTimer() {
    clearInterval( oTimer );
  }
 
  function IterateTimer() {
    iCurTime = iCurTime - 1;
    oOnUpdate({
      Seconds: iCurTime,
      Minutes: parseInt( iCurTime / 60 ),
      Hours: parseInt( iCurTime / 60 / 60 )
    });
 
    if( iCurTime <= 0 ) {
      DestroyTimer();
      oOnZero();
    }
  }
 
  return {
    SetTime: function( iSeconds ) {
      iCurTime = iSeconds;
    },
    Start: function() {
      CreateTimer();
    },
    Stop: function() {
      DestroyTimer();
    },
    Time: function() {
      return iCurTime;
    },
    Add: function( iSeconds ) {
      iCurTime = iCurTime + iSeconds;
    },
    Subtract: function( iSeconds ) {
      iCurTime = iCurTime - iSeconds;
    },
    OnUpdate: function( cbFunction ) {
      oOnUpdate = cbFunction;
    },
    OnZero: function( cbFunction ) {
      oOnZero = cbFunction;
    }
  };
};
Categories: JavaScript Tags: , ,

Ventrilo App for iPhone – VentBL

I just released VentBL ( Ventrilo Buddy List ) for the iPhone. Ventrilo Buddy List allows you to easily monitor who’s online your favorite Ventrilo server, from your iPhone, iPad, and iPod Touch.

Check it out: iTunes – VentBL

Categories: Apps Tags:

JavaScript Replace All

March 25th, 2011 No comments

Here’s my version of the replaceAll() method for JavaScript. I doubt it’s faster than RegEx, but it was certainly fun to make. :)

String.prototype.replaceAll = function(s, r, n) {
	if( this.toString().indexOf(s) < n ) n = 0;
	if( !n ) return this.toString().split( s ).join( r );
 
	var j = this.toString();
	while( n-- ) {
		j = j.replace( s, r );
	}
 
	return j;
}
 
var TestString = "I Love My Pie So Much, Don't You?";
 
// Usage
console.log( TestString.replace("o", "*") );
console.log( TestString.replaceAll("o", "*", 2) );
Categories: JavaScript Tags:

Logo Ideas

March 7th, 2011 No comments

Playing around with Illustrator again. Trying to come up with some branding for me. Working with the letters “m” and “h” (psst, they’re my initials). Here’s one of my drafts:

Categories: Notice Tags:

Text to Pixel Font!

January 16th, 2011 No comments

So, this is a silly little proof of concept I came up with to kill 20 minutes in between projects. Takes regular text and turns it into 1px sized divs. That’s right, the div’s actually form the pixels of each letter! :D Awesome, right!? Check it out!

jsTexty Example

How’s it done? Easy:
* Get the text of an element
* Move through it, 1 character at a time
* Match the character with a pattern (currently only supports lowercase)
* Convert the pattern to markup
* Replace the text with excessive amounts of html :D

$(document).ready(function() {
    var jsTexty = {};
 
    jsTexty.Make = function(e) {
        var strLetterString = $(e).text();
        var strReplaceHtml = '';
 
        for(var i = 0; i<strLetterString.length; i++) {
            var strThisLetter = strLetterString.substr(i,1);
            var arrLetterCode = jsTexty.GetLetterCode(strThisLetter);
                strReplaceHtml += jsTexty.LetterCodeToHtml(arrLetterCode);
        }
 
        $(e).html(strReplaceHtml + '<div class="clear"></div>');
    };
 
    jsTexty.LetterCodeToHtml = function(arrLetterCode) {
        var strReplaceHtml = '<div class="lbBlock">';
        for(var i = 0; i<arrLetterCode.length; i++) {
            var strThisRow = arrLetterCode[i];
            for(var j = 0; j<strThisRow; j++) {
                var strThisLetterBlock = strThisRow.substr(j,1);
                if(strThisLetterBlock==='1') {
                    strReplaceHtml += '<div class="lbSolid"></div>';
                }
                if(strThisLetterBlock==='0') {
                    strReplaceHtml += '<div class="lbEmpty"></div>';
                }
            }
            strReplaceHtml+='<div class="clear"></div>';
        }
        return strReplaceHtml + '</div>';
    }
 
    jsTexty.GetLetterCode = function(strSingleLetter) {
        switch(strSingleLetter) {
            case ' ':
                var arrLetterCode = [
                '0000',
                '0000',
                '0000',
                '0000',
                '0000'
                ];
                break;
            case 'a':
                var arrLetterCode = [
                '0110',
                '1001',
                '1111',
                '1001',
                '1001'
                ];
                break;
            case 'b':
                var arrLetterCode = [
                '1110',
                '1001',
                '1110',
                '1001',
                '1110'
                ];
                break;
            case 'c':
                var arrLetterCode = [
                '0111',
                '1000',
                '1000',
                '1000',
                '0111'
                ];
                break;
            case 'd':
                var arrLetterCode = [
                '1110',
                '1001',
                '1001',
                '1001',
                '1110'
                ];
                break;
            case 'e':
                var arrLetterCode = [
                '1111',
                '1000',
                '1110',
                '1000',
                '1111'
                ];
                break;
            case 'f':
                var arrLetterCode = [
                '1111',
                '1000',
                '1110',
                '1000',
                '1000'
                ];
                break;
            case 'g':
                var arrLetterCode = [
                '0111',
                '1000',
                '1011',
                '1001',
                '0111'
                ];
                break;
            case 'h':
                var arrLetterCode = [
                '1001',
                '1001',
                '1111',
                '1001',
                '1001'
                ];
                break;
            case 'i':
                var arrLetterCode = [
                '111',
                '010',
                '010',
                '010',
                '111'
                ];
                break;
            case 'j':
                var arrLetterCode = [
                '0001',
                '0001',
                '0001',
                '1001',
                '0110'
                ];
                break;
            case 'k':
                var arrLetterCode = [
                '1001',
                '1010',
                '1100',
                '1010',
                '1001'
                ];
                break;
            case 'l':
                var arrLetterCode = [
                '1000',
                '1000',
                '1000',
                '1000',
                '1111'
                ];
                break;
            case 'm':
                var arrLetterCode = [
                '10001',
                '11011',
                '10101',
                '10001',
                '10001'
                ];
                break;
            case 'n':
                var arrLetterCode = [
                '10001',
                '11001',
                '10101',
                '10011',
                '10001'
                ];
                break;
            case 'o':
                var arrLetterCode = [
                '0110',
                '1001',
                '1001',
                '1001',
                '0110'
                ];
                break;
            case 'p':
                var arrLetterCode = [
                '1110',
                '1001',
                '1110',
                '1000',
                '1000'
                ];
                break;
            case 'q':
                var arrLetterCode = [
                '0000',
                '0110',
                '1001',
                '0111',
                '0001'
                ];
                break;
            case 'r':
                var arrLetterCode = [
                '1110',
                '1001',
                '1110',
                '1001',
                '1001'
                ];
                break;
            case 's':
                var arrLetterCode = [
                '0111',
                '1100',
                '0110',
                '0011',
                '1110'
                ];
                break;
            case 't':
                var arrLetterCode = [
                '11111',
                '00100',
                '00100',
                '00100',
                '00100'
                ];
                break;
            case 'u':
                var arrLetterCode = [
                '1001',
                '1001',
                '1001',
                '1001',
                '0110'
                ];
                break;
            case 'v':
                var arrLetterCode = [
                '10001',
                '10001',
                '01010',
                '01010',
                '00100'
                ];
                break;
            case 'w':
                var arrLetterCode = [
                '10101',
                '10101',
                '10101',
                '10101',
                '01010'
                ];
                break;
            case 'x':
                var arrLetterCode = [
                '10001',
                '01010',
                '00100',
                '01010',
                '10001'
                ];
                break;
            case 'y':
                var arrLetterCode = [
                '10001',
                '01010',
                '00100',
                '00100',
                '00100'
                ];
                break;
            case 'z':
                var arrLetterCode = [
                '1111',
                '0001',
                '0010',
                '0100',
                '1111'
                ];
                break;
            case '.':
                var arrLetterCode = [
                '000',
                '000',
                '000',
                '110',
                '110'
                ];
                break;
            case ',':
                var arrLetterCode = [
                '000',
                '000',
                '000',
                '110',
                '010'
                ];
                break;
            case '!':
                var arrLetterCode = [
                '010',
                '010',
                '010',
                '000',
                '010'
                ];
                break;
            case '(':
                var arrLetterCode = [
                '010',
                '100',
                '100',
                '100',
                '010'
                ];
                break;
            case ')':
                var arrLetterCode = [
                '010',
                '001',
                '001',
                '001',
                '010'
                ];
                break;
            case '?':
                var arrLetterCode = [
                '01110',
                '00001',
                '00110',
                '00000',
                '00100'
                ];
                break;
        }
        if(!arrLetterCode) {
            var arrLetterCode = [
            '1111',
            '1111',
            '1111',
            '1111',
            '1111'
            ];						
        }
        return arrLetterCode;
    };
 
    // ACTIVATE
    $('#doit').click(function(){jsTexty.Make('#letterBox');});
});
Categories: CSS, Fun, JavaScript Tags:

Loading JavaScript Better :)

July 20th, 2010 No comments

After watching some very stimulating google tech talks on YouTube, I walked away with some new insight on how browsers load content. The following is a technique I picked up that allows for all included javascripts to load in parallel (instead of sequentially), and to prioritize the loading of your visible page content first.

The following code is placed before the closing body tag (and not in the head, as is traditionally done).

<script type="text/javascript"> 
	var DocumentHead = document.getElementsByTagName('head')[0];
 
	function jsOptimizedLoader(src) {
		var Script = document.createElement('script');
			Script.src = src;
			Script.type = 'text/javascript';
			DocumentHead.appendChild(Script);
	}
 
	jsOptimizedLoader('js/app/foo.js');
	jsOptimizedLoader('js/app/bar.js');
	jsOptimizedLoader('js/app/boo.js');
	jsOptimizedLoader('js/app/far.js');
</script>

Once your DOM has finished loading, all the scripts tags are added to the head via javascript. Allowing your page to display PRIOR to spending the time loading all of those scripts will win you usability points and ease of access points with your audience.