ProjectDrinks

October 5, 2011 rob other

I’ve decided to start up the ProjectDrinks meetup again here in Montreal, if you’re interested in coming down you can check out the details here.

More

0

Events in Javascript

October 1, 2011 rob javascript

One of the features of C# that I really enjoy is events. For the many folks out there who have never used C#, an event is an implementation of the observer pattern that allows objects to watch for certain notifications within other objects. For example in the Windows.Forms library the Button object has a Click event that you can bind an action to:

  var button = new Button();
  button.Click += (sender, ev) => {
    MessageBox.Show("Hello, world!");
  };

You can define events within your own classes and fire them easily:

  public delegate void MyEventHandler();
  public event MyEventHandler MyEvent;

  //  ... lots of code ...

  // ... in some method that triggers the event:
    if (MyEvent != null){
      MyEvent();
    }

Turns out this is fairly easily implemented in Javascript. This code here should do the trick:

function createEvent(eventName, obj){
  var event = function() {
    var ob;
    for (var i = 0; i < obj[eventName].observers.length; i++){
      ob = obj[eventName].observers[i];
      ob.apply(ob, arguments);
    }
  };

  event.observers = [];

  event.add = function(observer) {
    event.observers.push(observer);
  };

  event.remove = function(observer) {
    var i = event.observers.indexOf(observer);
    if (i >= 0){
      event.observers.splice(i, 1);
    }
  };

  obj[eventName] = event;
}

Now you can go like this:

var obj = {};

createEvent("test", obj);

obj.test.add(function(){
  alert("Hello, world!");
});

obj.test();


You can try it by clicking here.

More

0

Crafty: Gaming Engine for Javascript

September 26, 2011 rob game-programming

I started fiddling with this Javascript gaming library called Crafty, which allows you to build simple video games using DOM or canvas elements. Up front I like it better than gameQuery since it allows you to use canvas, but also because it seems to be much more of a framework rather than just a collection of jQuery extensions for gaming.

The most interesting thing about the library though is the use of components, which are essentially an implementation of Ruby’s mixins in Javascript. A large number of built-in components support fancy things sprites, physics and input-related components that make an entity (such as a player) automatically respond to the arrow keys on the keyboard.

You can even define your own components. For example, you could define a component called FollowsMouse which means the sprite will follow the mouse cursor.

The main issue so far is that the documentation is sparse and the examples are not at all up-to-date. When you create an entity, you do it like this:

obj = Crafty.e("list", "of", "included", "components");

However it turns out that the capitalization style of components has changed:

// examples say to do this:
obj = Crafty.e("2D", "canvas");
// when in fact you do this:
obj = Crafty.e("2D", "Canvas");

These types of problems are very difficult to track down, since there is no failure notice when a required component doesn’t exist. Instead, the system just ignores it and your entities don’t render. I typically follow the adage, “the bug is not in the library, despite how much it seems like it” and yet, sometimes the bug is actually in the library (or in this case, the documentation).

There is probably a few other hiccups, maybe I’ll make a few tweaks to the library and send it over in hopes they’ll merge a patch in.

More

0

Ruby’s instance_eval and Structured Configuration Files

September 12, 2011 rob ruby

Recently at work I was setting up a section of the program involving a user-configurable GUI element. Initially I thought about using something like XML to handle this, however if I went that route I’d have to manage parsing the XML through some library, traversing the XML tree, and create some sort of GUI element based on what type of node it was, what the attributes were, etc.

On top of that it was highly likely that the requirements for this GUI system would change and the level of sophistication behind the GUI system would increase – buttons would need to do more complicated tasks that could potentially be arbitrary. Having a hard-coded system in C# would not be feasible since tweaking logic would require a re-compile and an application restart.

I decided that since the system already had an IronRuby install built in, perhaps I could do this configuration file in Ruby as well. Given an XML configuration file that looks like this:

<group name="Buttons">
  <line>
    <button text="Cool Script">
      <something_crazy_and_awesome />
    </button>
  </line>
</group>

I could translate this to Ruby that looks like this:

group "Buttons" do
  line do
    button "Cool Script" do
      something_crazy_and_awesome
    end
  end
end

On top of that in order to use this configuration file in a program I don’t actually need to parse the file, I can just execute it within the context of different objects. For the dialog box that allows the user to set up the configuration I can just execute the Ruby code within that dialog box object and it will automatically create the elements that allow the user to change the configuration. Then in the part of the application where the user actually uses the configuration, I can just execute the file again but with a different definition of group, line, etc. that construct the proper GUI elements.

This is not just applicable to GUI elements, you can use this for anything that uses some sort of structured configuration. Rake uses this to great effect with tasks. But how would you go about implementing this pattern?

Turns out it’s really simple using instance_eval. Here’s an example that constructs the GUI element (this is in
IronRuby so it uses .NET for GUI construction):

class GroupBuilder
  def initialize parent, name, &block
    @group_box = GroupBox.new(name)
    parent.Controls.Add(@group_box)
    instance_eval &block
  end

  def line &block
    LineBuilder.new(@group_box, &block)
  end
end

class LineBuilder
  attr_accessor :panel

  def initialize parent, &block
    # in the GUI environment we use a panel for adding things
    @panel = Panel.new
    parent.Controls.Add @panel

    instance_eval &block
  end

  def button text, &block
    ButtonBuilder.new(@panel, text, &block)
  end

  # ... anything else that can be placed in a line ...
end

class ButtonBuilder
  def initialize parent, text, &block
    # create a button
    btn = Button.new(text)
    # bind the click event of the button to execute the
    # Ruby code within the block
    btn.Click { self.instance_eval &block }
    parent.Controls.Add btn
  end

  def something_crazy_and_awesome
    # do something crazy and awesome
  end
end

class ScriptProcessor
  def initialize control, script
    @control = control
    instance_eval File.read(script)
  end

  def group name, &block
    GroupBuilder.new(@control, name, &block)
  end
end

To do all this stuff, you can just create a ScriptProcessor object, pass in a .NET control and a script filename:

f = Form.new
ScriptProcessor.new(f, "my_config_file.rb")
f.Show

For each type of nested element you can create a class which define a method for the various types of sub-elements that you are allowed to have. Each of those methods will then handle the processing that needs to happen when the system sees an element of that type.

I think you could probably do this without classes and just use lambdas, but I think the code is clearer when you have objects since it is very explicit as to what each object is for.

Doing this with C# is a bit trickier since C# doesn’t have instance_eval, but it turns out you can have a bit of a hack in order to get it to work quite well. I’ll write up a quick post about this at a later date.

More

0

VimConf

August 30, 2011 rob vim

I like Vim. Especially learning new tricks with it. Do you?

If yes, check out VimConf, it’s an online conference where people show all sorts of tips about using Vim, extending it with scripting, etc.

More

0

Project Euler

August 25, 2011 rob other

I’ve already managed to fail at my 250 words per day project, since I haven’t posted in a while. That’s alright I suppose, maybe it will take a bit of time to get into it. Anyway, here’s another brief post about something I discovered the other day: a site called Project Euler. This site has a whole bunch of mathematical problems that you can solve via programming.

The fun part about this site is that many of the problems are fairly easily solvable using a recursive solution. I find that in everyday coding, you don’t really do much development using recursive functions. This is disappointing because it really is quite an elegant way to solve problems! For example, problem 28 might not seem like a recursive problem, but in fact can be solved trivially using a recursive solution! I enjoy “games” where I begin to think in this way, maybe it helps stroke my nerd ego a little. On top of that, the focus is also on efficiency; it is possible for a computer to solve any of the problems within one minute (the one-minute rule) provided you’re using an efficient algorithm.

Most of the problems, if not all, are based on work done by Euler. This includes problems involving prime numbers, combinatorics, factorials and other tasty bits of number theory. These are very useful bits of math to learn, and the harder questions on the site force you to do a bit of research in order to find a proper solution.

More

0

250 Words

August 17, 2011 rob other

I’ve decided to start up my own little project based on the idea at the site 750words, which is a game where you’re supposed to write 750+ words per day to engage the brain juices. I remember when I first started going hardcore on my old blog this was my goal: to just write about random things and see what happens. It worked pretty well, I ended up getting a few articles posted on reddit and other silly places like that and basically learning how retarded some of my ideas were (or how retarded some other people on the Internet are).

From what my teachers and professors have told me I’ve always been very concise with my writing, so I think I’ll shorten it from 750 words to 250 words. That way if I don’t have a lot to say on a topic I have a lower bar to shoot for, but also to keep things bite-sized since reading long blocks of text that aren’t incredibly well written and aren’t really about anything is not always the most fun thing to do.

For the topics I’ll probably just be writing random posts about stuff that I’ve been thinking about, things that interest me, or maybe random happenings in life that are not too personal to tell the world about. I want to try and avoid rants since those tend to be annoying to read and there are enough rants on the web already (including on my old blog) that more of them would just pollute the Internet and not be terribly constructive. I’d also like to reserve my old blog for HOWTOs since I’m tired of writing about how to make the world a better place or how to help random folks because that is what discouraged me from writing before: the worry that what I’m saying isn’t good enough for the world means I avoid just writing for the sake of writing, which is the main reason why I started my blog in the first place! So I’ll stick to talking about things that I like to talk about, and anybody who cares to listen can do so.

More

0

New Blog

August 5, 2011 rob other

I’ve started up a new blog here to replace my old one. The old one was initially about Linux and my joys/woes with it (hence the name of the blog) but slowly over time posts about programming, statistics, economics, etc. took over and the content of the blog changed.

Unfortunately I ended up talking about things that I thought other people were interested in, and not so much about things that I was interested in. Eventually I just lost inspiration and stopped writing. This is a problem because I like to write and share stuff that I’m interested in, so this new blog is an attempt to start doing that again.

I suppose I could have just continued writing on the old blog, but I don’t really want to because the old blog has a Linux brand to it that I want to get away from and also I’m slowly losing trust in Google so I’d rather host the blog on my own server. Plus the fact that this blog has my own name as the domain lends some credibility to it!

Anyway if you’ve liked some of the things I posted about in my old blog (fractals, some of the stats stuff) then feel free to stick around! Otherwise I hate to disappoint, but I probably won’t be writing too much on Linux or how-to-be-a-better-programmer or things like that.

More

0

Next posts »

Powered by WordPress. Designed by elogi.