-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_pattern.rb
64 lines (55 loc) · 2.04 KB
/
file_pattern.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
64
require 'net/http'
require 'uri'
# Generates a looping pattern based on a file in /patterns.
# This allows drawing any specific picture by creating new patterns
#
# Defining pattern files:
# - must be in `REPO_ROOT/patterns`
# - must have 7 lines, with spaces for "off" pixels, and any non-space character for "on" pixels
# - not all lines need to be the same width. Whichever row is widest will set the pattern width for looping
# - There will be 2 pixels added for padding at the right edge of the pattern before padding
# - must be called {pattern_filename}.txt. E.g: To render `pacman.txt`, pass in "pacman" as initializer parameter
module GithubInvaders
module PatternGenerators
class FilePattern
attr_reader :pattern, :pattern_filename
def initialize(pattern_filename)
@pattern_filename = pattern_filename
@pattern = load_pattern
end
def generate(point)
pattern_x = point.x % pattern_width
pattern[point.y][pattern_x] # We store the pattern rows first, as it's simpler to read that way
end
private
def pattern_width
pattern.map(&:length).max + 2
end
def is_uri?(string)
uri = URI.parse(string)
%w( http https ).include?(uri.scheme)
rescue URI::BadURIError
false
rescue URI::InvalidURIError
false
end
def pattern_file_contents
if is_uri?(pattern_filename)
::Net::HTTP.get(URI.parse(pattern_filename))
else
full_path = "patterns/#{ pattern_filename }.txt"
File.open(full_path).read
end
end
# Loads
def load_pattern
file_lines = pattern_file_contents.split("\n")
raise "Invalid number of lines, expected 7: #{ file_lines.length }" unless file_lines.length == 7
pattern = file_lines.map do |line|
line = line.rstrip.tr("\s", "0").tr("^0", "1") # Turn spaces into "0" and everythig else into "1"
line.chars.map(&:to_i) # Split into chart, and turn them into ints
end
end
end
end
end