Sounds in DragonRuby

The sound API in DragonRuby is a little tricky because at first it seems similar to the sprite API (e.g. using args.outputs) but it diverges sharply when you want to have some more control.

So let’s take a quick look at audio in DragonRuby!

Simple Music

As usual with DragonRuby, the simple stuff is simple.

To play a looping sound, for example as background music, get a sound file in .ogg format and then add it on to args.outputs.sounds:

args.outputs.sounds << 'sounds/my_music.ogg'

The audio will loop forever.

Simple Sound Effects

Want to fire off a single sound effect?

Get a sound file in .wav format and then add it on to args.outputs.sounds:

args.outputs.sounds << 'sounds/my_effect.wav'

The sound will play once.

Wait so the API behaves differently based on the file format?

Yep. A little odd but it works.

Adjusting the Volume Knob

Playing a sound effect in DragonRuby is pretty easy. But what if we need to adjust the volume or some other attribute of the audio? Or maybe loop a .wav or not loop a .ogg file?

You might think, based on how sprites work in DragonRuby, you could do something like this:

# This does not work!
args.outputs.sounds << {
  input: 'sounds/my_music.ogg',
  gain: 0.5,      # Half volume
  looping: false  # Don't loop
}

But this does not work.

Instead, you need to use an entirely different interface: args.audio.

args.audio is a hash table of sounds.

To add a new sound, assign it with a name:

args.audio[:music] = {
  input: 'sounds/my_music.ogg',
  gain: 0.5,
  looping: false
}

To adjust an attribute of the audio, access it by the same name:

# Turn up the volume
args.audio[:music].gain = 0.75

To pause a sound:

args.audio[:music].paused = true

To completely remove a sound:

args.audio.delete :music

More Music Manipulation

This is the full set of options for audio from the documentation:

args.audio[:my_music] = {
  input: 'sounds/my_music.ogg',
  x: 0.0, y: 0.0, z: 0.0,   # Relative position to the listener, x, y, z from -1.0 to 1.0
  gain: 1.0,                # Volume (0.0 to 1.0)
  pitch: 1.0,               # Pitch of the sound (1.0 = original pitch)
  paused: false,            # Set to true to pause
  looping: false,           # Set to true to loop
}

That’s it!

DragonRuby: Render Targets

Next up in my notes on DragonRuby: render targets!

Weirdly, the documentation on DragonRuby’s render targets is limited to example code. Personally, I prefer prose when I am trying to learn… so here we are!

In DragonRuby, a render target is like an infinite canvas you can render as many regular sprites onto as you want, then manipulate the whole thing as if it is one sprite.

This is especially good for things like tiled backgrounds that are built once and do not change.

Let’s take an example.

Clouds!

Let’s start off very simple and build up.

First, here’s all the code to render a single 250x250 pixel image to the screen:

def tick args
  clouds = {
    x: 0,
    y: 0,
    h: 250,
    w: 250,
    path: 'sprites/cloud.png'
  }

  args.outputs.sprites << clouds
end

Single cloud tile

More Clouds

Cool, but I’d like to fill the whole window with clouds, so I’m going to tile them.

The code below makes a 6x3 grid of the cloud image.

(In DragonRuby, the screen is always 1280x720. Our grid is 1500x750 but I’m not trying to be too precise with the numbers here.)

def tick args
  clouds = []

  6.times do |x|
    3.times do |y|
      clouds << {
        x: x * 250,
        y: y * 250,
        h: 250,
        w: 250,
        path: 'sprites/cloud.png'
      }
    end
  end

  args.outputs.sprites << clouds
end

Screen full of blue clouds

Ah… blue clouds. Nice.

On every tick, the code builds up an array of 18 sprites (images) and renders it out to the screen.

(There are a number of ways to make this more efficient - check out the previous posts in this series for different ways to “cache” the sprite information.)

Render Targets

But in this post we are talking about render targets - which is a way of rendering a bunch of sprites (or any other renderable thing) just once, and then treating the whole group of sprites as a single sprite. This is faster, simpler, and enables some neat effects.

The code only needs minor changes to switch the cloud grid to using a render target instead:

# Move cloud grid creation into a helper method
def make_clouds(args)
  clouds = []

  6.times do |x|
    3.times do |y|
      clouds << {
        x: x * 250,
        y: y * 250,
        h: 250,
        w: 250,
        path: 'sprites/cloud.png'
      }
    end
  end

  # Similar to `args.outputs`,
  # render targets have `.sprites`, `.solids`, etc.
  # The argument will be used as the path below
  args.render_target(:clouds).sprites << clouds
end

def tick(args)
  # Set up the render target on the first tick
  if args.tick_count == 0
    make_clouds(args)
  end

  # Output a single sprite
  # located at 0,0 and the size of the whole grid
  # created in `make_clouds`
  args.outputs.sprites << {
    x: 0,
    y: 0,
    w: 250 * 6,
    h: 250 * 3,
    path: :clouds # Name of the render target!
  }
end

For convenience, the code above moves the creation of the cloud grid and the render target into a helper method which gets called on the first tick of the game.

args.render_target(:clouds) automatically creates a new render target named :clouds if it does not already exist. Then we can render things to it just as if it were args.outputs.

Interestingly, render targets do not seem to have an innate width or height. In order to avoid unintentional scaling, you will need to “know” how big the render target is. In this case, we know it is a 6x3 grid of 250x250 images, so the size is fairly straightforward. I left the math in to make it clearer.

Finally, we reference the render target similarly to an image file, but pass in the name of the render target as the :path instead of an actual file path.

Static Sprites, Too!

As explored in a different post, we can use static_sprites to “render” the sprite once.

# No changes here
def make_clouds(args)
  clouds = []

  6.times do |x|
    3.times do |y|
      clouds << {
        x: x * 250,
        y: y * 250,
        h: 250,
        w: 250,
        path: 'sprites/cloud.png'
      }
    end
  end

  args.render_target(:clouds).sprites << clouds
end

def tick(args)
  if args.tick_count == 0
    make_clouds(args)

    # Create the clouds sprite once
    # and keep it in `args.state`.
    args.state.clouds = {
      x: 0,
      y: 0,
      w: 250 * 6,
      h: 250 * 3,
      path: :clouds
    }

    # Add the clouds sprite just once
    # as a "static" sprite
    args.outputs.static_sprites << args.state.clouds
  end
end

And now we can move the clouds around just by changing the attributes on the render target.

Adding a little bit of code at the end of tick:

  args.state.clouds.x = (Math.sin(args.tick_count / 20) * 100) - 100

(The calculation and numbers aren’t really important here, I just fiddled around until something looked decent.)

Clouds moving back and forth

Oh hey! Those extra pixels on the sides of the cloud grid actually came in handy.

What Else?

Remember, the entire render target is like one sprite now. That means all the regular sprite attributes (e.g. color, size, blending, flipping, rotation) can be applied to the entire thing at once.

Wait, did you say rotation?

Sure, let’s make ourselves dizzy.

  args.state.clouds.angle = (Math.sin(args.tick_count / 120) * 180)

Spinning clouds

Okay, that’s as deep as we’ll go on render targets in this post!

DragonRuby: Object-Oriented Starter

I enjoy playing with the DragonRuby Game Toolkit, but the documentation and many of the examples are very much intended for non-Rubyists. Additionally, as a game engine, it’s more data/functionally-oriented than most Rubyists are used to. For example, the main game loop in the tick method needs to be implemented as a top-level method.

This post walks through structuring a game in a way that is a little more familiar to Rubyists.

Caveat! I am new to DragonRuby myself and this is not meant to be the “correct” or “best” or even “great” way to organize your code. It’s just a pattern I’ve started using and it might be useful for you!

(By the way, while DragonRuby is a commercial product, you can often grab a free copy. Keep an eye out for sales!)

Starting Example

First, let’s start with some code that isn’t using any class definitions at all. Everything happens inside tick:

def tick(args)
  # Set up player object
  args.state.player ||= {
    x: args.grid.w / 2,
    y: args.grid.h / 2,
    w: 20,
    h: 20,
  }

  # Move player based on keyboard input
  if args.inputs.keyboard.left
    args.state.player.x -= 10
  elsif args.inputs.keyboard.right
    args.state.player.x += 10
  elsif args.inputs.keyboard.down
    args.state.player.y -= 10
  elsif args.inputs.keyboard.up
    args.state.player.y += 10
  end

  # Render the "player" as a square to the screen
  args.outputs.solids << args.state.player
end

DragonRuby Example - Moving a black square around

As a reminder, DragonRuby automatically loads up code from a file called mygame/app/main.rb and then calls tick 60 times per second.

args.state is like an OpenStruct where you can add on whatever attributes you want and store whatever you would like. In this case, we add a hash that we name player.

The code then checks for keyboard input and adjusts the position of the “player”. (To keep things very simple, we don’t worry about keeping the player on the screen.)

Finally, we render the “player” as a solid square.

This is simple enough and the code isn’t too complicated. But, just for fun, let’s slowly transform it to be a little more “object-oriented”.

Game Object

First, let’s create a main “game” object to hold our logic, instead of putting it all in tick.

class MyGame
  # Adds convenience methods for args, gtk, keyboard, etc.
  attr_gtk

  def initialize(args)
    args.state.player = {
      x: args.grid.w / 2,
      y: args.grid.h / 2,
      w: 20,
      h: 20,
    }
  end

  def tick
    if keyboard.left
      state.player.x -= 10
    elsif keyboard.right
      state.player.x += 10
    elsif keyboard.down
      state.player.y -= 10
    elsif keyboard.up
      state.player.y += 10
    end

    outputs.solids << state.player
  end
end

def tick args
  $my_game ||= MyGame.new(args)
  $my_game.args = args
  $my_game.tick
end

Now the tick method only sets up the global $my_game on the first tick, then sets args on each tick and calls the game’s tick method.

(Tangent alert! Is it necessary to set args on every tick? Not strictly - you could set self.args = args in initialize and it will work okay. But if you want to use DragonRuby’s unit test framework, it may cause problems because each test has a fresh copy of args.)

Using attr_gtk allows the code to be a bit shorter. args, state, keyboard, and more now have convenience methods for them.

Instance Variables Instead of State

args.state is essentially a global variable space. This is a big convenience when a game is all top-level methods - otherwise you would have to figure out where to stash all your game state yourself.

However, it’s not required to use it.

The code below uses @player to store the player hash, instead of args.state.

class MyGame
  attr_gtk
  attr_reader :player

  def initialize(args)
    @player = {
      x: args.grid.w / 2,
      y: args.grid.h / 2,
      w: 20,
      h: 20,
    }
  end

  def tick
    if keyboard.left
      player.x -= 10
    elsif keyboard.right
      player.x += 10
    elsif keyboard.down
      player.y -= 10
    elsif keyboard.up
      player.y += 10
    end

    outputs.solids << player
  end
end

def tick args
  $my_game ||= MyGame.new(args)
  $my_game.args = args
  $my_game.tick
end

One thing that has thrown me off with DragonRuby is understanding just how much “regular” Ruby I can use. For the most part, other than how the tick method is used as the main game loop, you can use the Ruby language constructs you are comfortable with.

Splitting Things Up

No big change here, but as a game grows it’s easier to split the steps of each game loop into different methods.

class MyGame
  attr_gtk
  attr_reader :player

  def initialize(args)
    @player = {
      x: args.grid.w / 2,
      y: args.grid.h / 2,
      w: 20,
      h: 20,
    }
  end

  def tick
    handle_input
    render
  end

  def handle_input
    if keyboard.left
      player.x -= 10
    elsif keyboard.right
      player.x += 10
    elsif keyboard.down
      player.y -= 10
    elsif keyboard.up
      player.y += 10
    end
  end

  def render
    outputs.solids << player
  end
end

def tick args
  $my_game ||= MyGame.new(args)
  $my_game.args = args
  $my_game.tick
end

Player Class

Final step in this post - let’s move the “player” out to a separate class.

In this example, it might not make a lot of sense. But in most games there will be a lot of state and logic you might want to associate with the “player” or any other objects in the game. Having it be its own class helps keep the logic in one place.

class MyGame
  attr_gtk
  attr_reader :player

  def initialize(args)
    @player = Player.new(args.grid.w / 2, args.grid.h / 2)
  end

  def tick
    handle_input
    render
  end

  def handle_input
    if keyboard.left
      player.x -= 10
    elsif keyboard.right
      player.x += 10
    elsif keyboard.down
      player.y -= 10
    elsif keyboard.up
      player.y += 10
    end
  end

  def render
    outputs.solids << player
  end
end

class Player
  attr_sprite

  def initialize(x, y)
    @x = x
    @y = y
    @w = 20
    @h = 20
  end
end

def tick args
  $my_game ||= MyGame.new(args)
  $my_game.args = args
  $my_game.tick
end

Here the code uses another DragonRuby convenience. attr_sprite adds a bunch of helper methods that allow you to use any object as a sprite/solid/border, etc. (Note that the code still passes player into outputs.solids and DragonRuby treats it as a solid. If it were passed into outputs.sprites then it would be treated like a sprite instead!)

Separate Files?

For the sake of a blog post, all the code is together. But there is no reason not to start splitting the code across separate files.

But! In DragonRuby there is one weirdness with require: you must include the file extension (usually .rb), while in regular Ruby that is usually omitted.

Wrapping Up

Did our code become longer and less straight-forward? Yes, for this small example, definitely.

But as a game (or any project) grows, pulling bits out into modular pieces is going to be an advantage. Personally I fall back on this structure pretty quickly when I start a new DragonRuby project.

Hopefully this post is useful to Rubyists trying to get into DragonRuby!