Class: Spritely::Collection

Inherits:
Struct
  • Object
show all
Defined in:
lib/spritely/collection.rb

Overview

A ‘SpriteMap` has a `Collection` that knows how to calculate the size of the sprite, based on image repetition and spacing.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#filesObject

Returns the value of attribute files

Returns:

  • (Object)

    the current value of files



6
7
8
# File 'lib/spritely/collection.rb', line 6

def files
  @files
end

#optionsObject

Returns the value of attribute options

Returns:

  • (Object)

    the current value of options



6
7
8
# File 'lib/spritely/collection.rb', line 6

def options
  @options
end

Class Method Details

.create(*args) ⇒ Object



7
8
9
10
11
# File 'lib/spritely/collection.rb', line 7

def self.create(*args)
  new(*args).tap do |collection|
    collection.position!
  end
end

Instance Method Details

#cache_keyObject



21
22
23
# File 'lib/spritely/collection.rb', line 21

def cache_key
  files.collect { |file| Digest::MD5.file(file) }.join
end

#find(name) ⇒ Object



17
18
19
# File 'lib/spritely/collection.rb', line 17

def find(name)
  image_sets.find { |image_set| image_set.name == name }
end

#heightObject



45
46
47
# File 'lib/spritely/collection.rb', line 45

def height
  heights.reduce(:+)
end

#imagesObject



13
14
15
# File 'lib/spritely/collection.rb', line 13

def images
  image_sets.flat_map(&:images)
end

#position!Object

Upon creation, the collection is then positioned appropriately by positioning each image within the sprite.



51
52
53
54
55
56
# File 'lib/spritely/collection.rb', line 51

def position!
  image_sets.each_with_index do |image_set, index|
    image_set.top = heights[0..index].reduce(:+) - image_set.outer_height
    image_set.position_in!(width)
  end
end

#widthObject

Returns the width of the to-be-generated sprite image. When none of the images repeat, it is simply the max width of all images in the sprite. When an image in the sprite is repeated, a calculation is performed based on the least common multiple of all repeated images. That least common multiple is then multiplied by the minimum multiple that will result in a value greater than or equal to the max width of all images in the sprite.



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/spritely/collection.rb', line 31

def width
  return @width if @width

  max_width = image_sets.collect(&:width).max
  if image_sets.none?(&:repeated?)
    @width = max_width
  else
    @width = lcm = image_sets.select(&:repeated?).collect(&:width).reduce(:lcm)
    @width += lcm while @width < max_width
  end

  @width
end