1. Computing

Embedding Images in Gosu Programs

By

4 of 4

Loading Embedded Files
Embedding Images in Gosu Programs

Once you have the files embedded in your script, it's time to use them. The example below uses them with Gosu::Image.new, which expects filenames. How do you get a filename from a file embedded in the DATA section? The with_data method will write the data out to a temporary file and pass it to a given block.

If you need to access this data manually, you can query the $data object and run Base64.decode64 with the data it returns. This can be useful if the method can load directly from a string, or if the data is actually text data.


#!/usr/bin/env ruby
require 'rubygems'
require 'gosu'
require 'yaml'
require 'tempfile'
require 'base64'
$data = YAML.parse(DATA.read)

def with_data(key,&block)
 Tempfile.open(File.basename(__FILE__)) do |tmp|
    tmp.binmode
    tmp.write( Base64.decode64($data[key].value) )
    tmp.close
   
    block.call(tmp.path)
 end
end

class MyWindow < Gosu::Window
 def initialize
    super(640, 480, false)
   
    with_data('player.png') do |f|
     @player = Gosu::Image.new(self, f, false)
    end
 end

 def draw
    @player.draw(100, 100, 0)
 end
end

MyWindow.new.show

__END__
---
player.png: |
 iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAAAXNSR0IArs4c
 6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOwwAADsMBx2+oZAAAAAd0
 SU1FB9gCGAIGHesMB8MAAAHVSURBVFjD7ZexboMwEIZ/I8Y+QSU6ROyVkLox
 ZwlS10pZ8xCkD1DlBbrlAegYySzM3SpF6W6yRKLv0OU6NFBCHILDkUQq/0KE
 fcen/3yODfTq1avX/5ZgykMd5WVJRMPhcOdFkiRskDYHnOd5ewNJkhAHpM0B
 5/s+giAAAEgpWSEtjjIEQQAiAhEVoFyyGRoCAPD2dXdsvjgHIA0Wvw6tH+XO
 wNPtRhtQmn9SuVlKLKUsSlxegxcpcdU57vltAIvymny4EmNcZtukMV4ePv/W
 XMNATQzL/rgDR0SUP3NtHaUoc6iqKHNosAi0MfmTy8FtvqNbyUHpYogIQohG
 TtZ1MSmlkKYp+wklTVMopdDESbsODgDm83nx8vnjvjRlA/f1GytvjBs/xmg0
 AgDEcYzV+xjucom1JmY6nQIAJpMJlFJwXbfWSbspHGOTFLmbQB5cg1U4nYNN
 VBeTQxqvQR1cVzr2La2Ds9msMyDT3LbBSZuYGI1ym+7oVImlBjDUxV3FCDoM
 w+LfIgxDYnT7+m91HOdBijKnOA9GmcO5XlngtIcFLkirrXOHxOWk1WLNifwe
 Uj6x5L+3Y6ItpHWG5hKX7uK9Upfcu55tJofkhGPv6GvaXs6mH5HTJzgvjhgR
 AAAAAElFTkSuQmCC

This article is part of a series. Read more articles about Rapid Game Prototyping in Ruby

  1. About.com
  2. Computing
  3. Ruby
  4. Tutorials
  5. Rapid Game Prototyping with Gosu
  6. Loading Embedded Files

©2014 About.com. All rights reserved.