Rubygame: attempting to enable passing arguments to define game screen size

69 views Asked by At

A rubygame tutorial has a basic screen creation section followed by an excersize to modify the code to allow passing command line arguments that define screen size. I was able to use google to cobble together something I thought would work:

#! /usr/bin/ruby -w

# require 'rubygame'

screenx = ""
screeny = ""

# Rubygame.init

ARGV.each do |a|
    if a.scan("x=")
            screenx = a["x="] = ""
    end
    if a.scan("y=")
            screeny = a["y="] = ""
    end
end

puts screenx
puts screeny

# screen = Rubygame::Screen.new [screenx, screeny]
# loop {}

Without the comments I get a huge mess of errors which I don't understand and found very few results for any of them on Google.

With the comments I get different errors: If I give it a nonsense argument, it outputs "String not matched" If I give it a properly formatted request, I get "can't modify frozen String"

I'm not sure this is even the best way to extract x and y values from arguments.

1

There are 1 answers

0
Matheus Moreira On BEST ANSWER

Take a look at OptionParser:

options = {}

OptionParser.new do |opts|
  opts.on '-w', '--width WIDTH', 'Screen width' do |width|
    options[:width] = width
  end

  opts.on '-h', '--height HEIGHT', 'Screen height' do |height|
    options[:height] = height
  end
end.parse!

# options is now filled with values

There are separate gems for this – I'm the author of one. However, since your game isn't a full-blown command line application, I don't think you really need an extra dependency.