Module: Turing::Image::SquaringHelper

Included in:
BlackSquaring, WhiteSquaring
Defined in:
lib/turing/image_plugins/__squaring_helper.rb

Overview

Squaring helper

Skeleton for Turing::Image::*Squaring (mixin, actually).

Instance Method Summary collapse

Instance Method Details

#generate(img, word, bg = nil) ⇒ Object

contract method - generate the challenge

Raises:

  • (RuntimeError)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/turing/image_plugins/__squaring_helper.rb', line 15

def generate(img, word, bg = nil) # {{{
	if bg.nil?
		possible = Dir[File.join(@options[:bgdir], '*')]
		bg = possible[rand(possible.size)]
	else
		unless FileTest.exists?(bg)
			raise ArgumentError, "Wrong background!"
		end
	end

	img_tmp = GD2::Image.load(File.open(bg, 'r'))

	if img_tmp.width < img.width || img_tmp.height < img.height
		raise "Background has insufficient dimensions"
	end

	img.merge_from(img_tmp, 0, 0, 0, 0, img.width, img.height, 30.percent)

	# XXX: is this equivalent to "img_tmp.destroy" ?
	img_tmp = nil

	fg = GD2::Color[0, 0, 0]

	write_string(img, 'cour.ttf', fg, word, 35)

	raise RuntimeError, "no squaring color selected!" if @squaring_color.nil?
	fg = @squaring_color
	
	img.draw do |canvas|
		canvas.color = fg
		if rand(2).zero?
			delta = word.size > 8 ? 6 : 4
			0.step(img.width, delta) { |x| canvas.line(x, 0, x, img.height) }
			0.step(img.height, delta) { |y| canvas.line(0, y, img.width, y) }
		else
			i = 0
			while i <= img.width
				canvas.line(i, 0, i, img.height)
				i += 3 + rand(4)
			end

			i = 0
			while i <= img.height
				canvas.line(0, i, img.width, i)
				i += 3 + rand(4)
			end
		end
	end
end