class MonsterID

Generates cute monsters from a seed

Constants

BODY_COLOR_PARTS
COLORS

Test color set [hue, sat]

PARTS
SPECIFIC_COLOR_PARTS
WHITE_PARTS

Attributes

id[R]

Public Class Methods

new(seed, size = 120) click to toggle source
# File lib/monsterid.rb, line 81
def initialize(seed, size = 120)
  @id = Digest::SHA1.hexdigest seed.to_s

  parts = {
    legs: {
      part: PARTS[:legs][@id[0, 2].hex % PARTS[:legs].length],
      color: COLORS[@id[2, 2].hex % COLORS.length]
    },
    hair: {
      part: PARTS[:hair][@id[4, 2].hex % PARTS[:hair].length],
      color: COLORS[@id[6, 2].hex % COLORS.length]
    },
    arms: {
      part: PARTS[:arms][@id[8, 2].hex % PARTS[:arms].length],
      color: COLORS[@id[10, 2].hex % COLORS.length]
    },
    body: {
      part: PARTS[:body][@id[12, 2].hex % PARTS[:body].length],
      color: COLORS[@id[14, 2].hex % COLORS.length]
    },
    eyes: {
      part: PARTS[:eyes][@id[16, 2].hex % PARTS[:eyes].length],
      color: COLORS[@id[18, 2].hex % COLORS.length]
    },
    mouth: {
      part: PARTS[:mouth][@id[20, 2].hex % PARTS[:mouth].length],
      color: COLORS[@id[22, 2].hex % COLORS.length]
    }
  }

  @monster = ChunkyPNG::Image.new(120, 120, ChunkyPNG::Color::TRANSPARENT)

  parts.each do |_, part|
    path = File.join(File.dirname(__FILE__), 'parts', part[:part])
    partimg = ChunkyPNG::Image.from_file(path)

    if BODY_COLOR_PARTS.include? part[:part]
      part[:color] = parts[:body][:color]
    elsif SPECIFIC_COLOR_PARTS.include? part[:part]
      part[:color] = SPECIFIC_COLOR_PARTS[part[:part]]
    end

    partimg = colorise(partimg, part[:color][0], part[:color][1]) unless WHITE_PARTS.include? part[:part]

    @monster.compose!(partimg)
  end

  resize(size) unless size == 120
end

Public Instance Methods

inspect() click to toggle source
# File lib/monsterid.rb, line 149
def inspect
  "#<#{self.class.name}:#{object_id} id: #{@id}>"
end
resize(size) click to toggle source
# File lib/monsterid.rb, line 131
def resize(size)
  @monster.resample_bilinear!(size, size)
end
save(path) click to toggle source
# File lib/monsterid.rb, line 135
def save(path)
  @monster.save path
end
to_data_url() click to toggle source
# File lib/monsterid.rb, line 145
def to_data_url
  @monster.to_data_url
end
to_datastream() click to toggle source
# File lib/monsterid.rb, line 139
def to_datastream
  @monster.to_datastream
end

Private Instance Methods

colorise(img, h, s = 255) click to toggle source
# File lib/monsterid.rb, line 155
def colorise(img, h, s = 255)
  s = s.to_f / 255 # ChunkyPNG uses sat from 0.0 to 1.0

  img.pixels.map! do |px|
    _, _, v, a = ChunkyPNG::Color.to_hsv(px, true)
    ChunkyPNG::Color.from_hsv(h, s, v, a)
  end

  img
end