main.rb 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. class Image
  2. attr_reader :width, :height
  3. def initialize(width:, height:)
  4. @width = width
  5. @height = height
  6. @data = Array.new(width * height, 1)
  7. end
  8. def [](x, y)
  9. @data[x + y * @height]
  10. end
  11. def []=(x, y, r)
  12. @data[x + y * @height] = r
  13. end
  14. def scale(factor)
  15. img = Image.new(width: @width * factor, height: @height * factor)
  16. (0...@width).each do |x|
  17. (0...@height).each do |y|
  18. (0...factor).each do |dx|
  19. (0...factor).each do |dy|
  20. img[x*factor+dx,y*factor+dy] = self[x,y]
  21. end
  22. end
  23. end
  24. end
  25. img
  26. end
  27. def blit(img, at_x, at_y)
  28. (0...img.width).each do |x|
  29. (0...img.height).each do |y|
  30. self[at_x + x, at_y + y] = img[x, y]
  31. end
  32. end
  33. end
  34. def to_pbm
  35. buf = String.new
  36. buf << "P1\n"
  37. buf << "#{@width} #{@height}\n"
  38. @data.each {|x| buf << "#{x} "}
  39. buf
  40. end
  41. def self.glyph(size)
  42. img = Image.new(width: size, height: size)
  43. (0...size).each do |x|
  44. (0...size).each do |y|
  45. if x % 2 == 0 && y % 2 == 0 then
  46. img[x, y] = 0
  47. elsif (x % 2 == 0 || y % 2 == 0) && rand > 0.5 then
  48. img[x, y] = 0
  49. end
  50. end
  51. end
  52. img
  53. end
  54. end
  55. module Main
  56. def self.main
  57. glyphs_w = 4
  58. glyphs_h = 4
  59. size = 5
  60. img = Image.new(width: glyphs_w * (size + 2) + 2, height: glyphs_h * (size + 2) + 2)
  61. (0...glyphs_w).each do |x|
  62. (0...glyphs_h).each do |y|
  63. img.blit(Image.glyph(size), 2 + x * (size + 2), 2 + y * (size + 2))
  64. end
  65. end
  66. puts img.scale(20).to_pbm
  67. end
  68. end
  69. if $PROGRAM_NAME == __FILE__ then
  70. Main.main
  71. end