pangrid 0.7.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,417 @@
1
+ # ipuz (http://www.ipuz.org) is an open JSON format for crosswords and other
2
+ # puzzles. We support the crossword kind.
3
+ #
4
+ # Coordinates (clue "cells", zone "cells" and "rect") are [col, row],
5
+ # counting from 0 at the top left, as in the examples in the spec.
6
+ #
7
+ # provides:
8
+ # Ipuz : read, write
9
+
10
+ require 'json'
11
+
12
+ module Pangrid
13
+
14
+ class Ipuz < Plugin
15
+
16
+ DESCRIPTION = "ipuz crossword format (http://www.ipuz.org)"
17
+ FEATURES = %i(bars circles colors highlights given labels marks void
18
+ explanations hints linked_clues nodir_clues final_answer
19
+ misses)
20
+
21
+ IPUZ_VERSION = "http://ipuz.org/v2"
22
+ IPUZ_KIND = "http://ipuz.org/crossword#1"
23
+
24
+ # ipuz field => XWord field
25
+ METADATA = {
26
+ "title" => :title, "author" => :author, "editor" => :editor,
27
+ "copyright" => :copyright, "publisher" => :publisher,
28
+ "publication" => :publication, "url" => :url, "uniqueid" => :id,
29
+ "intro" => :preamble, "notes" => :notes, "explanation" => :explanation,
30
+ "annotation" => :annotation, "date" => :date, "difficulty" => :difficulty,
31
+ "origin" => :origin, "charset" => :charset
32
+ }
33
+
34
+ DIRECTIONS = {"Across" => :across, "Down" => :down}
35
+ SIDES = {"T" => :top, "R" => :right, "B" => :bottom, "L" => :left}
36
+
37
+ # Clue fields copied as they are
38
+ CLUE_FIELDS = %w(label enumeration explanation answer hints image type tags
39
+ highlight)
40
+
41
+ def read(data)
42
+ # some sites serve ipuz as JSONP, wrapped in ipuz(...)
43
+ data = data.strip.sub(/\Aipuz\((.*)\)\s*;?\z/m, '\1')
44
+ begin
45
+ json = ::JSON.parse(data)
46
+ rescue ::JSON::ParserError => e
47
+ raise PuzzleFormatError, "Invalid JSON: #{e.message}"
48
+ end
49
+ check("Expected a JSON object") { json.is_a?(Hash) }
50
+ check("Not an ipuz file") { json["version"].to_s.start_with?("http://ipuz.org/") }
51
+ kinds = Array(json["kind"])
52
+ check("Only ipuz crosswords are supported") {
53
+ kinds.any? {|k| k.to_s.start_with?("http://ipuz.org/crossword")}
54
+ }
55
+ @block = (json["block"] || "#").to_s
56
+ @empty = (json["empty"] || 0).to_s
57
+ @styles = json["styles"].is_a?(Hash) ? json["styles"] : {}
58
+
59
+ xw = XWord.new
60
+ dims = json["dimensions"]
61
+ check("dimensions must give a width and height") {
62
+ dims.is_a?(Hash) && [dims["width"], dims["height"]].all? {|i| i.is_a?(Integer) && i > 0}
63
+ }
64
+ xw.width, xw.height = dims["width"], dims["height"]
65
+ METADATA.each {|k, f| xw[f] = json[k].to_s if json[k]}
66
+
67
+ numbers = read_grid(xw, json["puzzle"], json["solution"])
68
+ read_zones(xw, json["zones"])
69
+ read_labels(xw, numbers)
70
+ read_clues(xw, json["clues"])
71
+ read_answers(xw, json)
72
+ xw.misses = json["misses"].transform_values(&:to_s) if json["misses"].is_a?(Hash)
73
+ xw
74
+ end
75
+
76
+ def write(xw)
77
+ xw.number
78
+ h = {"version" => IPUZ_VERSION, "kind" => [IPUZ_KIND]}
79
+ METADATA.each {|k, f| h[k] = xw[f] if xw[f]}
80
+ h["dimensions"] = {"width" => xw.width, "height" => xw.height}
81
+ h["puzzle"] = xw.solution.each_with_index.map do |row, y|
82
+ row.each_with_index.map {|cell, x| write_cell(xw, x, y, cell)}
83
+ end
84
+ solution = xw.solution.map {|row| row.map {|cell| write_solution(cell)}}
85
+ if solution.flatten.any? {|s| s.is_a?(String) && s != "#"}
86
+ h["solution"] = solution
87
+ end
88
+ clues = write_clues(xw)
89
+ h["clues"] = clues unless clues.empty?
90
+ h["showenumerations"] = true if xw.all_clues.any?(&:enumeration)
91
+ write_answers(xw, h)
92
+ h["misses"] = xw.misses if xw.misses && !xw.misses.empty?
93
+ format_json(h)
94
+ end
95
+
96
+ private
97
+
98
+ # Reading
99
+
100
+ def block?(v)
101
+ v.to_s == @block
102
+ end
103
+
104
+ def empty?(v)
105
+ v.to_s == @empty
106
+ end
107
+
108
+ # A number given as a string ("12") is still a number
109
+ def clue_number(v)
110
+ v.is_a?(String) && v =~ /\A\d+\z/ ? v.to_i : v
111
+ end
112
+
113
+ # Fills in xw.solution and returns {[x, y] => clue number from the grid}
114
+ def read_grid(xw, puzzle, solution)
115
+ check("puzzle must be a list of #{xw.height} rows of #{xw.width} cells") {
116
+ grid?(xw, puzzle)
117
+ }
118
+ check("solution must be a list of #{xw.height} rows of #{xw.width} cells") {
119
+ solution.nil? || grid?(xw, solution)
120
+ }
121
+ numbers = {}
122
+ xw.solution = puzzle.each_with_index.map do |row, y|
123
+ row.each_with_index.map do |p, x|
124
+ value, style, given = p.is_a?(Hash) ? [p["cell"], p["style"], p["value"]] : [p, nil, nil]
125
+ cell = Cell.new
126
+ if value.nil?
127
+ cell.solution = :void
128
+ elsif block?(value)
129
+ cell.solution = :black
130
+ else
131
+ numbers[[x, y]] = clue_number(value) unless empty?(value)
132
+ cell.solution = solution ? read_solution(solution[y][x]) : :null
133
+ if given.is_a?(String) && !given.empty?
134
+ cell.given = true
135
+ cell.solution = read_letter(given) if cell.solution == :null
136
+ end
137
+ end
138
+ apply_style(xw, x, y, cell, style)
139
+ cell
140
+ end
141
+ end
142
+ numbers
143
+ end
144
+
145
+ def grid?(xw, g)
146
+ g.is_a?(Array) && g.length == xw.height &&
147
+ g.all? {|row| row.is_a?(Array) && row.length == xw.width}
148
+ end
149
+
150
+ # A CrosswordValue from the solution grid -> Cell#solution
151
+ def read_solution(v)
152
+ v = v["value"] if v.is_a?(Hash)
153
+ v = v.first if v.is_a?(Array)
154
+ if v.nil? || empty?(v)
155
+ :null
156
+ elsif block?(v)
157
+ :black
158
+ else
159
+ read_letter(v.to_s)
160
+ end
161
+ end
162
+
163
+ def read_letter(s)
164
+ s.length == 1 ? s : Rebus.new(s)
165
+ end
166
+
167
+ def style_spec(style)
168
+ style = @styles[style] if style.is_a?(String)
169
+ style.is_a?(Hash) ? style : {}
170
+ end
171
+
172
+ def apply_style(xw, x, y, cell, style)
173
+ s = style_spec(style)
174
+ cell.circle = true if s["shapebg"] == "circle"
175
+ cell.highlight = true if s["highlight"]
176
+ cell.color = s["color"].to_s if s["color"]
177
+ if s["barred"].is_a?(String)
178
+ s["barred"].chars.map {|c| SIDES[c.upcase]}.compact.each {|side| xw.set_bar(x, y, side)}
179
+ end
180
+ if s["mark"].is_a?(Hash)
181
+ cell.marks = cell.marks.merge(s["mark"].transform_values(&:to_s))
182
+ end
183
+ end
184
+
185
+ # Zones apply a style to a group of cells
186
+ def read_zones(xw, zones)
187
+ return unless zones.is_a?(Array)
188
+ zones.each do |z|
189
+ next unless z.is_a?(Hash)
190
+ group_cells(xw, z).each {|x, y| apply_style(xw, x, y, xw.solution[y][x], z["style"])}
191
+ end
192
+ end
193
+
194
+ def group_cells(xw, g)
195
+ cells = g["cells"].is_a?(Array) ? g["cells"] : []
196
+ if g["rect"].is_a?(Array) && g["rect"].length == 4
197
+ x1, y1, x2, y2 = g["rect"]
198
+ cells += (y1..y2).flat_map {|y| (x1..x2).map {|x| [x, y]}}
199
+ end
200
+ cells.select {|x, y| in_grid?(xw, x, y)}
201
+ end
202
+
203
+ def in_grid?(xw, x, y)
204
+ x.is_a?(Integer) && y.is_a?(Integer) &&
205
+ (0...xw.width).cover?(x) && (0...xw.height).cover?(y)
206
+ end
207
+
208
+ # ipuz gives every clue number in the grid. Where they differ from the
209
+ # standard numbering, the square gets a label. (If the grid has no numbers
210
+ # at all, use the standard numbering.)
211
+ def read_labels(xw, numbers)
212
+ return if numbers.empty?
213
+ n = 1
214
+ xw.lights.map {|l| [l.x, l.y]}.uniq.each do |x, y|
215
+ given = numbers[[x, y]]
216
+ if given == n
217
+ n += 1
218
+ else
219
+ xw.solution[y][x].label = given.to_s
220
+ end
221
+ end
222
+ end
223
+
224
+ def read_clues(xw, clues)
225
+ return unless clues.is_a?(Hash)
226
+ across, down, nodir = [], [], []
227
+ clues.each do |key, list|
228
+ next unless list.is_a?(Array)
229
+ dir = DIRECTIONS[key.to_s.split(":").first]
230
+ parsed = list.map {|c| read_clue(xw, c, dir)}
231
+ case dir
232
+ when :across then across += parsed
233
+ when :down then down += parsed
234
+ else nodir += parsed
235
+ end
236
+ end
237
+ xw.across_clues = place_clues(xw, across, :across)
238
+ xw.down_clues = place_clues(xw, down, :down)
239
+ xw.nodir_clues = nodir
240
+ end
241
+
242
+ def read_clue(xw, c, dir)
243
+ case c
244
+ when Array
245
+ Clue.new(c[1].to_s, number: clue_number(c[0]))
246
+ when Hash
247
+ numbers = c["numbers"].is_a?(Array) ? c["numbers"] : [c["number"]].compact
248
+ clue = Clue.new(c["clue"] && c["clue"].to_s)
249
+ clue.number = clue_number(numbers.first)
250
+ clue.linked = numbers.drop(1).map {|n| ClueRef.new(clue_number(n))} +
251
+ refs(c["continued"])
252
+ clue.references = refs(c["references"])
253
+ clue.cells = group_cells(xw, c)
254
+ CLUE_FIELDS.each {|f| clue.send(:"#{f}=", c[f]) unless c[f].nil?}
255
+ clue.enumeration = clue.enumeration.to_s if clue.enumeration
256
+ clue.hints = Array(clue.hints).map(&:to_s)
257
+ clue.tags = Array(clue.tags).map(&:to_s)
258
+ clue
259
+ else
260
+ Clue.new(c.to_s)
261
+ end
262
+ end
263
+
264
+ def refs(list)
265
+ return [] unless list.is_a?(Array)
266
+ list.select {|r| r.is_a?(Hash)}.map do |r|
267
+ ClueRef.new(clue_number(r["number"]), DIRECTIONS[r["direction"].to_s.split(":").first])
268
+ end
269
+ end
270
+
271
+ # Match clues to the grid by number. If a clue can't be placed, keep the
272
+ # clues in the order given.
273
+ def place_clues(xw, clues, dir)
274
+ return clues if clues.empty?
275
+ lights = xw.lights.select {|l| l.direction == dir}
276
+ by_number = clues.group_by {|c| c.number.to_s}
277
+ placed = lights.map {|l| (by_number.delete(l.number.to_s) || []).first}
278
+ return clues unless by_number.empty? && clues.length == placed.compact.length
279
+ lights.zip(placed).map {|l, c| c || Clue.new(number: l.number)}
280
+ end
281
+
282
+ def read_answers(xw, json)
283
+ answers = Array(json["answers"] || json["answer"])
284
+ enums = Array(json["enumerations"] || json["enumeration"])
285
+ n = [answers.length, enums.length].max
286
+ return if n == 0
287
+ xw.questions = (0...n).map do |i|
288
+ Question.new(nil, enums[i] && enums[i].to_s, answers[i] && answers[i].to_s)
289
+ end
290
+ end
291
+
292
+ # Writing
293
+
294
+ # Pretty-printed JSON, with each grid row and each clue on a line of its
295
+ # own
296
+ def format_json(h)
297
+ compact = {}
298
+ placeholder = lambda do |rows, indent|
299
+ key = "@@#{compact.length}@@"
300
+ compact[key] = [rows, indent]
301
+ key
302
+ end
303
+ h = h.dup
304
+ %w(puzzle solution).each {|k| h[k] = placeholder.(h[k], 4) if h[k]}
305
+ if h["clues"]
306
+ h["clues"] = h["clues"].transform_values {|list| placeholder.(list, 6)}
307
+ end
308
+ out = ::JSON.pretty_generate(h)
309
+ compact.each do |key, (rows, indent)|
310
+ lines = rows.map {|r| " " * indent + ::JSON.generate(r)}
311
+ out = out.sub("\"#{key}\"") { "[\n" + lines.join(",\n") + "\n" + " " * (indent - 2) + "]" }
312
+ end
313
+ out + "\n"
314
+ end
315
+
316
+ def write_cell(xw, x, y, cell)
317
+ return nil if cell.void?
318
+ value =
319
+ if cell.black?
320
+ "#"
321
+ elsif cell.label
322
+ cell.label.empty? ? 0 : clue_number(cell.label)
323
+ else
324
+ cell.number || 0
325
+ end
326
+ style = write_style(xw, x, y, cell)
327
+ given = cell.given && cell.light? && letter(cell)
328
+ return value unless style || given
329
+ h = {"cell" => value}
330
+ h["style"] = style if style
331
+ h["value"] = given if given
332
+ h
333
+ end
334
+
335
+ def write_style(xw, x, y, cell)
336
+ s = {}
337
+ s["shapebg"] = "circle" if cell.circle
338
+ s["highlight"] = true if cell.highlight
339
+ s["color"] = cell.color.sub(/\A#(\h{6})\z/, '\1') if cell.color
340
+ # each bar is written once, on the square to its left or above it
341
+ bars = ""
342
+ bars << "R" if xw.bar?(x, y, :right)
343
+ bars << "B" if xw.bar?(x, y, :bottom)
344
+ s["barred"] = bars unless bars.empty?
345
+ s["mark"] = cell.marks unless cell.marks.empty?
346
+ s.empty? ? nil : s
347
+ end
348
+
349
+ def letter(cell)
350
+ cell.rebus? ? cell.solution.solution : cell.solution
351
+ end
352
+
353
+ def write_solution(cell)
354
+ case cell.solution
355
+ when :void then nil
356
+ when :black then "#"
357
+ when :null then 0
358
+ else letter(cell)
359
+ end
360
+ end
361
+
362
+ def write_clues(xw)
363
+ out = {}
364
+ {"Across" => :across, "Down" => :down}.each do |key, dir|
365
+ lights = xw.lights.select {|l| l.direction == dir}
366
+ clues = xw.send(:"#{dir}_clues")
367
+ next if clues.compact.empty?
368
+ out[key] = lights.each_with_index.map {|l, i| write_clue(clues[i] || Clue.new, l.number, dir)}
369
+ end
370
+ unless xw.nodir_clues.empty?
371
+ out["Clues"] = xw.nodir_clues.map {|c| write_clue(c, nil, nil)}
372
+ end
373
+ out
374
+ end
375
+
376
+ def write_clue(clue, number, dir)
377
+ text = clue.text.to_s
378
+ if text.empty? && clue.parent
379
+ p = clue.parent
380
+ text = "See #{p.number} #{DIRECTIONS.key(p.direction || dir)}".strip
381
+ end
382
+ h = {}
383
+ h["number"] = number.is_a?(String) && number.empty? ? nil : number
384
+ h["clue"] = text
385
+ CLUE_FIELDS.each do |f|
386
+ v = clue.send(f)
387
+ h[f] = v unless v.nil? || v == []
388
+ end
389
+ h["continued"] = write_refs(clue.linked, dir) unless clue.linked.empty?
390
+ h["references"] = write_refs(clue.references, dir) unless clue.references.empty?
391
+ h["cells"] = clue.cells unless clue.cells.empty?
392
+ h.compact!
393
+ h.keys == %w(number clue) ? [number, text] : h
394
+ end
395
+
396
+ def write_refs(refs, dir)
397
+ refs.map do |r|
398
+ {"direction" => DIRECTIONS.key(r.direction || dir) || "Clues", "number" => r.number}
399
+ end
400
+ end
401
+
402
+ def write_answers(xw, h)
403
+ finals = (xw.questions || []).reject(&:text)
404
+ return if finals.empty?
405
+ answers = finals.map(&:answer)
406
+ enums = finals.map(&:enumeration)
407
+ if finals.length == 1
408
+ h["answer"] = answers[0] if answers[0]
409
+ h["enumeration"] = enums[0] if enums[0]
410
+ else
411
+ h["answers"] = answers if answers.any?
412
+ h["enumerations"] = enums if enums.any?
413
+ end
414
+ end
415
+ end
416
+
417
+ end # module Pangrid
@@ -37,8 +37,8 @@ class Json < Plugin
37
37
  rows: xw.height,
38
38
  cols: xw.width,
39
39
  cells: cells,
40
- across: xw.across_clues,
41
- down: xw.down_clues
40
+ across: xw.across_clues.map(&:to_s),
41
+ down: xw.down_clues.map(&:to_s)
42
42
  }
43
43
 
44
44
  ::JSON.generate(h)
@@ -18,7 +18,7 @@ module Pangrid
18
18
  ydim = xw.height * scale + 2
19
19
  png = ChunkyPNG::Image.new(xdim, ydim, ChunkyPNG::Color::TRANSPARENT)
20
20
  xw.each_cell_with_coords do |x, y, cell|
21
- c = cell.black? ? black : white
21
+ c = cell.light? ? white : black
22
22
  png.rect(
23
23
  x * scale, y * scale, (x + 1) * scale, (y + 1) * scale,
24
24
  grey, c) # stroke, fill
@@ -7,12 +7,12 @@ QXW_GRID_ERROR = "Could not read grid from .qxw file"
7
7
  class Qxw < Plugin
8
8
 
9
9
  DESCRIPTION = "QXW grid reader (rectangular grids only)"
10
- FEATURES = [:bars]
10
+ FEATURES = [:bars, :void]
11
11
 
12
12
  # Square lines have the format
13
13
  # SQ <x> <y> <bars> <merge> <flags> <char>
14
14
  # bars: bit 0 = bar on the right edge, bit 1 = bar on the bottom edge
15
- # flags: bit 0 = block
15
+ # flags: bit 0 = block, bit 3 = cutout (not part of the grid)
16
16
  def read_squares(lines)
17
17
  lines.select {|x| x =~ /^SQ /}.map do |line|
18
18
  parts = line.scan(/\w+/)
@@ -24,28 +24,23 @@ class Qxw < Plugin
24
24
 
25
25
  def read_black(xw, squares)
26
26
  squares.each do |col, row, _, flags|
27
- next if flags & 1 == 0
27
+ solution = flags & 8 != 0 ? :void : flags & 1 != 0 ? :black : nil
28
+ next unless solution
28
29
  xw.solution[row] ||= []
29
- xw.solution[row][col] = Cell.new(solution: :black)
30
+ xw.solution[row][col] = Cell.new(solution: solution)
30
31
  end
31
32
  end
32
33
 
33
- # Each bar is stored once, on the square to its left or above it; record
34
- # it on both squares it separates.
34
+ # qxw stores each bar once, as the right or bottom edge of a square, just
35
+ # as XWord#bars does. Bars next to blocks or voids are dropped.
35
36
  def read_bars(xw, squares)
36
- add = lambda do |col, row, side|
37
- cell = xw.solution[row] && xw.solution[row][col]
38
- cell.borders |= [side] if cell
39
- end
40
37
  squares.each do |col, row, bars, _|
41
38
  next if xw.boundary?(col, row)
42
39
  if bars & 1 != 0 && !xw.boundary?(col + 1, row)
43
- add.(col, row, :right)
44
- add.(col + 1, row, :left)
40
+ xw.set_bar(col, row, :right)
45
41
  end
46
42
  if bars & 2 != 0 && !xw.boundary?(col, row + 1)
47
- add.(col, row, :bottom)
48
- add.(col, row + 1, :top)
43
+ xw.set_bar(col, row, :bottom)
49
44
  end
50
45
  end
51
46
  end
@@ -1,3 +1,3 @@
1
1
  module Pangrid
2
- VERSION='0.7.0'
2
+ VERSION='1.0.0'
3
3
  end