Java Callbacks Ruby Style

Java (pre version 8, anyway) doesn't have proper anonymous functions1 for things like callbacks. Instead, the Java Way is to create an anonymous subclass implementing the behaviour you care about in an overridden method, then passing that instance to whatever needs it. So you see a lot of stuff like this:

addListener(new ChangeListener() {
    public void changed (InputEvent event, Actor actor) {
        do_a_thing(event, actor);

ChangeListener is an abstract class in LibGDX implementing a bunch of callback hooks; this snippet passes addListener an anonymous subclass that overrides one of these callbacks and does what I want it to.

The Ruby Way, on the other hand, is to use blocks. This gives you the same power but requires less code. The equivalent (hypothetical) Ruby framework's interface might look something like:

addKeyDown {|event, keycode| do_a_thing(event, keycode)}

So this becomes jarring when you wish to call Java APIs from JRuby, as I did when writing a game in JRuby.

Initially, I just bit the bullet and wrote (non-anonymous) subclasses to hold the callbacks. Soon though, the number of callbacks got larger than my personal threshold (two) and I decided to try something else.

My first attempt was to create anonymous Ruby subclasses, which is fine but not really compact:

addListener( {
    def changed(event, actor)
      do_a_thing(event, actor)

Another downside--and this is a bit more subtle--is that local variables defined in the method calling addListener are not visible to the new class. For example, this:

def listenForThing(someEvent)
    addListener( {
        def changed(event, actor)
          do_a_thing(event, actor) if someEvent == event

won't work; changed can't see someEvent.

There had to be a better way--this is Ruby, after all! And there was.

Ruby provides the method define_method, which takes a block and name and turns it into a method which is then added to the class. I added a helper function to do the work:

def newListener(klass, name, &block)
  c =

  c.send(:define_method, name, &block)

and used it like this:

addListener(newListener(ChangeListener, :changed)  {|event, actor|
    do_a_thing(event, actor)

This is almost Ruby-like in it's compactness, but there's one subtle quirk.

The block has redefined self to be the owner of the new method (the sub-instance of ChangeListener created by newListener), so the method do_a_thing the block is trying to call should actually belong to that, not the class which called newListener in the first place.

This isn't what most people expect when they see a block in Ruby, and so could lead to all kinds of unpleasant surprises. It also optimizes for the less-common case and is kind of unwieldly to work around:

outerSelf = self
addListener(newListener(ChangeListener, :changed)  {|event, actor|
    outerSelf.do_a_thing(event, actor)

Fortunately, this is easy to fix. Instead of turning the block into the method body, I just define the new method as a simple one-liner that evaluates the block:

def newListener(klass, name, &block)
  c =

  c.send(:define_method, name) { | *args|*args) }

This way, the block keeps its old self value and everything works as expected:

addListener(newListener(ChangeListener, :changed)  {|event, actor|
    outerSelf.do_a_thing(event, actor)

And now, we have Java callbacks that are almost as easy as their Ruby equivalents.

  1. And you could argue that Java 8 doesn't have them either. 

#   0 Comments Posted 2016-03-05 22:49:09 UTC; last changed 2016-03-13 18:57:21 UTC

Thoughts on game development with LibGDX and JRuby

As part of my ongoing, never-ending plan to Finally Write Another Roguelike, I've been dabbling with LibGDX, a game development library for Java. And having gotten to the point where it kind of does a few game-like things, I'm writing this to document my progress and in the hope that someone else may find this information useful.

LibGDX is a nice library but has the immediate major downside of requiring me to use Java without getting paid for it. I worked around that by using JRuby. (As you know Bob, JRuby is a version of Ruby that runs on the JVM and interoperates nicely with existing Java code.)

My first project was a class-by-class rewrite of Zombie Bird, a Flappy Bird clone written as a GDX tutorial. The code for that is here. (Feel free to grab it to use as a starting point.)

I then went on to port an existing Roguelike attempt in Ruby and ncurses to JRuby and GDX. This project is ongoing but I've managed to get it to do basic things (walk around, manage inventory) using GDX.

And during this process, I have managed to Learn Things. I will now impart my hard-won Knowledge to you.

Using Maven to Handle Java Dependencies

GDX has a GUI-based configuration thingy that will fetch the latest GDX jars and create an empty Gradle(?) project for you. Which is all well and good if you're using Java, but I'm not. Some Googling revealed that other people who've tried this just copied the jars somewhere into JRuby's classpath but I've gotten spoiled by the Maven repository network so I wanted something more automated.

JRuby has no problem accessing Java code in an external jar file, and GDX is accessible by Maven, so the solution was pretty straightforward:

  1. Create a trivial GDX program.
  2. Use Maven and the maven-assembly-plugin to build it into a big jar that includes all dependencies.
  3. Add the jar to my JRuby $CLASSPATH variable and require it.

(Why Maven and not one of the better other build tools? Because Maven is the one I know. You could do this with a better build tool or you could just clone my code from github and be done with it.)

My trivial GDX program was the default minimal program generated by one of the scaffolds (I don't remember which). One nice thing about it is that I can run it as a standalone program:

java -jar mvn_lib/target/bigjar-CURRENT-jar-with-dependencies.jar

It doesn't do much beyond display a moving image, but it's enough to prove to me that I successfully found all of the pieces GDX needs to run. This came in handy the times my program wouldn't work for some stupid reason because I could confirm that at least the library was correctly installed.

So now when I start on a fresh checkout, I just need to do a

cd mvn_lib; mvn clean package

and everything is there.

Upgrading GDX is simple too: just change the version in mvn_lib/pom.xml and rerun the build command.

Doing a GUI

GDX has a set of GUI widgets built on top of its 2D scene graph. As a GUI library, its, uh, pretty good for a game library.

Since I'm writing a turn-based game, having decent UI code is a lot more important to me than graphic performance and low-level control, and I started to regret using GDX for this project after a while. I persevered though and was eventually able to get a decent UI up and running. (Presumably, I'll need to do animations and sound effects at some point in the future, at which time I'll be thankful I stayed with GDX and didn't go to Swing or something.)

In any case, my game has a pretty simple screen layout: a map, a set of stats and a text window for game messages, arranged top to bottom:

(I'm using little pictures of characters because I'm oldschool. And a terrible artist.)

This was all pretty simple. The map is a subclass of com.badlogic.gdx.scenes.scene2d.ui.Widget and was pretty easy to code in Ruby. (Note: remember to super() in initialize, lest you get a really obscure crash.)

The others were just provided widgets (Table and TextArea respectively), each configured by a corresponding Ruby class. It would have been relatively simple to make them into subclasses, but I did them first and wasn't clear how well subclassing GDX components would work.

Getting the layout to work correctly was kind of painful and required a lot of trial-and-error intermixed with careful reading of the related Wiki pages. Turning on debug mode (by calling setDebug(true) on the table) helped a lot--this makes the table outline its cells with coloured lines and gives you a much better idea of how it works.

It also helped to be able to edit and run without needing to rebuild the project each time I made a small change, so that's one for Ruby1.

(This is not intended as a slam on the GDX UI code; this stuff is complicated. I have the same kinds of problems with Tcl/Tk and I've been using it on and off for decades.)

Don't Use Dialog

The one thing that ended up being a huge pain was the inventory window:

I initially wrote it as a subclass of com.badlogic.gdx.scenes.scene2d.ui.Dialog, which provides some nice functionality. Unfortunately, keystrokes sent to the inventory dialog would leak back to the main game. For example, pressing 'U' to stop equipping an item would then also cause the player to move up and to the right, which is what 'U' means during normal movement.

It turns out that pressing a key emits three events: KeyDown, KeyPressed and KeyUp, in that order. The Dialog was listening for KeyDown while the map listened for KeyPressed, so using a keyboard shortcut on the inventory window would close it on the KeyDown, returning control to the main game which would then receive the KeyPressed.

I wasn't able to find a way to make Widget deal with this correctly and ultimately ended up rewriting the inventory window as a subclass of Window, Dialog's parent.

Function Overloading

One major pain in using JRuby to call Java code is dealing with overloaded functions. The workaround is ugly, so it's fortunate that this comes up pretty rarely.

Here's the problem:

Suppose a Java class defines two functions with the same name and number of arguments but different types:

class Foo {
    int bar(int x) { ... }
    int bar(String x) { ... }

When calling them from Java, like this:

Foo x = new Foo();
...;              // calls int version"forty-two");     // calls string version

the Java compiler knows exactly which function to actually call because it knows the type of the argument. This is not the case in JRuby:"thingy")   # may or may not work

Because Ruby is dynamically typed, JRuby can't tell which bar() to call, so it guesses and issues a warning.

Fortunately, JRuby provides the java_send method, which lets you call a method by name and type signature: :bar, [java.lang.String], "thingy"

I've only needed to do this once in my project; most overloaded methods also have different numbers of arguments.

Implied Setters

Ruby (mostly) follows the Uniform Access Principle, while Java does not. As a result, the convention is for Java classes to implement getter and setter methods of the form setXXX() and getXXX().

However, JRuby automagically converts between the two. That is, this:

x.text = "some text"
puts x.text

works the same way as this:

x.setText("some text")
puts x.getText()

in a Java class that implements only setText() and getText().

I initially stuck to the Java form for Java classes because I didn't want to obscure the underlying implementation. However, the Ruby form is so much nicer that I eventually gave in. I'm not sure if that's a good idea or not.

Unsolved Stuff

Dynamic Constructors

Similar to method overloads above, JRuby has trouble with overloaded constructors. And like the method above, it provides a workaround:

construct = JavaClass.java_class.constructor(Java::int, Java::int, Java::int)
object = construct.new_instance(0xa4, 0x00, 0x00)

When I tried it, I did indeed get an object that claimed to be of the expected class, but I couldn't call the methods. It looked to me like it was an instance of the class but deep down, JRuby believed it was an instance of java.lang.Object.

It ended up that I didn't need that class at all, so I never investigated further, but I wasn't able to find out if this was a JRuby bug or something else I didn't understand.

Worst case, I can write a helper function in Java and include it in my part of the big JAR.

Building a Release

I haven't yet come up with a satisfactory way of creating a release suitable for end-users.

Warbler looks promising. I've played with it a little, but haven't yet gotten it to do what I want. Perhaps with more fiddling, I can get it to make a releasable build for me.

The other issue is that JRuby needs you to include the source code in the jar file. This won't be a problem if you're just going to release it as open-source software, but if you're trying to sell the game or even are just trying to prevent spoilers, you'll need to do something else.

One possible solution is to encrypt the Ruby sources and keep them as resources, then write a small Java loader that reads them in, decrypts them and hands them off to the JRuby API. Alternately, you could write a script to compile the Ruby sources into a Java array literal which, once again a loader routine decodes and hands off to the JRuby API. Either way, the result is a more-or-less ordinary Java program.

Overall, It's Not Bad

In general, I'm finding the JRuby+GDX combination to work pretty well. There's nothing insurmountable and the problem areas, where they exist, are pretty rare. Ruby itself is a much more powerful and expressive language than Java, and is a lot more fun to use.

  1. That being said, it takes about 6 seconds for JRuby to go from invocation to displaying that first window, so it's not lightning-fast either. There's a bunch of time that static typing and an IDE would have saved me too. 

#   0 Comments Posted 2016-03-05 21:55:13 UTC; last changed 2016-03-05 22:30:58 UTC

Fallout 4: I am Disappoint

Let me tell you my half-assed1 literary theory. It goes like this: plot is character. A story is what happens when characters are placed in a situation. The plot is extrapolated from that.

You let three suspicious acquaintences find a tote-bag full of money and you know it's going to end in gunfire. An angsty prince discovering that his father was murdered by his new stepfather will ultimately end up killing a bunch of people. And so on. The characters react to the situation, and that's the story.

At least, that's how you write a novel or play or film script. With story-based video games, there's a problem: the main character is the player, which means that you know nothing about them. You have no idea how they'll react, so it's not actually possible to write a plausible plot for a game.

(Okay, you can and lots of games do that, but the way they do it is by creating a main character and then telling the player that they are that person. When that happens to me, it stops being my story. And then I hate the game.)

The plot of a game should be a collaboration between the game's designers and the player. The designers have created the setting and secondary characters and it is up to the player to decide what they want to do with it. The story of the game becomes what the player does.

For example, in Fallout (i.e. the first game of the series), there's a quest you run into early in the game. Aradesh, the leader of a small town has a daughter (Tandi) who has been kidnapped by raiders. He asks you to rescue her.

Now, the obvious way to do it is to just go in with guns blazing and kill all of the raiders. This is possible and if you're good enough at combat, you can do it. Alternately, you can sneak in (if you're good enough at stealth) and free her that way. Or, if you're a persuasive speaker, you can convince the raiders' leader to just let her go. Finally, if all of that fails, you can offer to buy her from the raiders if you have enough money or if you're good at haggling2.

I ended up sneaking in and freeing Tandi, getting caught and shooting my way out, then escaping into the desert. Your game will almost certainly be different.

And this is not a special case. The Fallout series has been very good at colaborating with the player, Fallout 3's heavy-handed ending notwithstanding.

So, Fallout 4.

Bethesda merged skills (i.e. the way you determine what you're good at) and perks (bonus rule-bending abilities that you can get) and ruined both. Previous Fallouts would give me points to add to my skills as I progressed. So I could specialize in guns (and be a gunslinger), stealth (and be a ninja), speech (con artist), lockpicking and science (burglar) or just evenly spread them across everything (bleached skeleton).

But Fallout 4 replaces them with a bunch of perks3. Instead of adding points to (e.g.) my repair skill, I take a level of a perk that improves some aspect of repair (e.g. the ability to modify guns to a degree). And this will take a long time to maximize because the later levels of these perks also require a higher experience level. I will not be able to customize my weapons or armor to its full potential for at least the first 40 hours of gameplay.

This means that I'm no longer allowed to specialize. There are now fewer interesting things I can do in this game and fewer stories I can create4.

It is, in other words, less of a Fallout game.

Update: All that being said, Fallout 4 is still an amazing game. I'm currently 170 hours into my first playthrough and still enjoying it. Someday perhaps, I'll make another post detailing what I liked about the game.

  1. Half-assed in that I cribbed it from someone else without digging to see if there's more to it than that. 

  2. Alternately, you could also just turn down Aradesh's request or avoid his town entirely. 

  3. I'm mostly talking about skills in this post, but they're also doing perks wrong. A perk is supposed to be a special exception to the normal rules of the game. The best perks are clever and imaginative and can be used in interesting ways, and there are some of them in Fallout 4, because they were carried over from previous games. But the new ones are all mostly of the form you do X slightly better. Booooooooring! 

  4. I should mention that it's not just skills. There's the character's backstory as a married suburban parent, the reduced dialog options, the way they are voiced--all of that takes away from my part of the storytelling. 

#   0 Comments Posted 2015-11-21 08:12:06 UTC; last changed 2016-02-06 23:24:46 UTC

I'm Over There

For those following me here, I've started dabbling with the thing and so have started another blog at I'm expecting the posts to eventually migrate back here, but for now, I'm putting my low-effort stuff there.

And currently, it's all low-effort.

Update: I'm back. Unfortunately, the thing doesn't seem to have very much traction, at least not with me. While I was gone, I made a small Twine game and wrote this script for the codebase.

#   0 Comments Posted 2014-12-27 04:12:27 UTC; last changed 2015-10-31 21:02:45 UTC

Another blog post, another blogging program

So I decided to take another run at blogging. It's not really my thing, but I sometimes get the urge to post something longer than 140 characters.

In fact, my last two posts were written sometime after I inadvertently broke ii (or more precisely, I broke my web server in a way ii couldn't handle) and so they've languished in my git repostories for a while.

And since I enjoy writing blogging software much more than I enjoy blogging, I did what came naturally and wrote another blogging tool, then moved this blog to it.

The new tool is called jj and it's basically ii rewritten in Ruby, only with Markdown and various gems replacing the hand-coded stuff I did last time.

As usual, it's free and on the net. If you're looking for a static blog generator and have never heard about Jekyll or Octopress, you might want to give it a try.

#   0 Comments Posted 2014-05-19 22:24:07 UTC; last changed 2014-05-19 22:15:15 UTC