diff options
| author | Tom Black <[email protected]> | 2015-11-13 00:51:17 -0500 |
|---|---|---|
| committer | Tom Black <[email protected]> | 2015-11-13 00:51:17 -0500 |
| commit | 592dd9976211f8b00da0f4992ddbe27d7d2b300e (patch) | |
| tree | 834a134ad55a0dc6041403512b6362739b820c02 /lib | |
| parent | 211d858a78c856b1a2682cfe9bd67703784d8265 (diff) | |
| download | ruby2d-592dd9976211f8b00da0f4992ddbe27d7d2b300e.tar.gz ruby2d-592dd9976211f8b00da0f4992ddbe27d7d2b300e.zip | |
Improved color validation and assignment
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/ruby2d/color.rb | 20 | ||||
| -rw-r--r-- | lib/ruby2d/quad.rb | 18 |
2 files changed, 29 insertions, 9 deletions
diff --git a/lib/ruby2d/color.rb b/lib/ruby2d/color.rb index 9c7bc32..df28b52 100644 --- a/lib/ruby2d/color.rb +++ b/lib/ruby2d/color.rb @@ -6,6 +6,10 @@ module Ruby2D attr_reader :r, :g, :b, :a def initialize(c) + if !self.class.is_valid? c + raise Error, "`#{c}` is not a valid color" + end + case c when 'black' @r, @g, @b, @a = to_f([0, 0, 0, 255]) @@ -48,14 +52,24 @@ module Ruby2D when Array @r, @g, @b, @a = to_f([c[0], c[1], c[2], c[3]]) else - # raise Error, "Color does not exist!" - puts "Error! Bad color." + raise Error, "`#{c}` is not a valid color" end end + # Color must be String, like 'red', or Array, like [1.0, 0, 0, 1.0] + def self.is_valid?(c) + # TODO: Check if valid color string + # (c.class == String && c.has_key?(c)) || + (c.class == String) || + (c.class == Array && c.length == 4 && + c.all? { |el| el.is_a? Numeric } && + c.all? { |el| el.class == Fixnum && (0..255).include?(el) || + el.class == Float && (0.0..1.0).include?(el) }) + end + private - # Convert from Uint8 (0..255) to Float (0..1.0) + # Convert from Fixnum (0..255) to Float (0.0..1.0) def to_f(a) b = [] a.each do |n| diff --git a/lib/ruby2d/quad.rb b/lib/ruby2d/quad.rb index 2567185..08adf86 100644 --- a/lib/ruby2d/quad.rb +++ b/lib/ruby2d/quad.rb @@ -39,18 +39,24 @@ module Ruby2D private def update_color(c) - # If a 2D array - if c.class == Array && c.all? { |el| el.class == Array } + + # If a valid color, use it for each vertex + if Color.is_valid? c + @c1 = Ruby2D::Color.new(c) + @c2 = Ruby2D::Color.new(c) + @c3 = Ruby2D::Color.new(c) + @c4 = Ruby2D::Color.new(c) + + # If a valid array of colors, assign them to each vertex, respectively + elsif c.all? { |el| Color.is_valid? el } @c1 = Ruby2D::Color.new(c[0]) @c2 = Ruby2D::Color.new(c[1]) @c3 = Ruby2D::Color.new(c[2]) @c4 = Ruby2D::Color.new(c[3]) else - @c1 = Ruby2D::Color.new(c) - @c2 = Ruby2D::Color.new(c) - @c3 = Ruby2D::Color.new(c) - @c4 = Ruby2D::Color.new(c) + raise Error, "Not a valid color for #{self.class}" end + end end end |
