def test_read_detects_empty_input(self): with self.assertRaises(ipuz.IPUZException) as cm: ipuz.read(None) self.assertEqual(str(cm.exception), "No valid JSON could be found") with self.assertRaises(ipuz.IPUZException) as cm: ipuz.read("") self.assertEqual(str(cm.exception), "No valid JSON could be found")
def test_crossword_v2(self): with open("fixtures/crossword_v2.ipuz") as f: data = f.read() output = ipuz.read(data) output_string = ipuz.write(output) second_output = ipuz.read(output_string) self.assertEqual(output, second_output)
def test_first_ipuz_file_with_json(self): with open("fixtures/first.ipuz") as f: data = f.read() output = ipuz.read(data) output_string = ipuz.write(output) second_output = ipuz.read(output_string) self.assertEqual(output, second_output)
def test_example_ipuz_file_with_jsonp(self): with open("fixtures/example.ipuz") as f: data = f.read() output = ipuz.read(data) output_string = ipuz.write(output, jsonp=True) second_output = ipuz.read(output_string) self.assertEqual(output, second_output)
def test_read_allows_jsonp_callback_function(self): result = ipuz.read("ipuz(" + json.dumps({ "version": "http://ipuz.org/v1", "kind": ["http://ipuz.org/invalid", ] }) + ")") self.assertEqual(result['version'], "http://ipuz.org/v1") result = ipuz.read("ipuz_callback_function(" + json.dumps({ "version": "http://ipuz.org/v1", "kind": ["http://ipuz.org/invalid", ] }) + ")") self.assertEqual(result['version'], "http://ipuz.org/v1")
def test_read_example_ipuz_fixture(self): with open('fixtures/ipuz/example.ipuz') as f: ipuz_dict = ipuz.read(f.read()) puzzle = crossword.from_ipuz(ipuz_dict) self.assertEqual(puzzle.meta.rights, "2011 Puzzazz") self.assertEqual(puzzle.empty, "0")
def test_to_puz_only_works_if_numbering_system_matches(self): with open('fixtures/ipuz/first.ipuz') as f: ipuz_dict = ipuz.read(f.read()) puzzle = crossword.from_ipuz(ipuz_dict) with self.assertRaises(crossword.CrosswordException): crossword.to_puz(puzzle)
def test_read_first_ipuz_fixture(self): with open('fixtures/ipuz/first.ipuz') as f: ipuz_dict = ipuz.read(f.read()) puzzle = crossword.from_ipuz(ipuz_dict) self.assertEqual(puzzle.width, 13) self.assertEqual(puzzle.height, 13) self.assertEqual(puzzle.meta.creator, "Arthur Wynne") self.assertEqual(puzzle.meta.date, "12/21/1913") self.assertEqual(puzzle.meta.title, "FUN's Word-Cross Puzzle") self.assertEqual( puzzle.clues.across["2-3"], "What bargain hunters enjoy" ) self.assertIsNone(puzzle.block) self.assertIsNone(puzzle.empty) self.assertEqual(puzzle.clues.down["1-32"], "To govern") self.assertEqual(puzzle[0, 0].puzzle, None) self.assertEqual(puzzle[0, 0].solution, None) self.assertEqual(puzzle[6, 0].puzzle, 1) self.assertEqual(puzzle[6, 0].solution, "R") puzzle[6, 0]['solution'] = "X" self.assertEqual(puzzle[6, 0].solution, "X") puzzle[6, 0].solution = "Y" self.assertEqual(puzzle[6, 0]['solution'], "Y") setattr(puzzle[6, 0], "solution", "Z") self.assertEqual(puzzle[6, 0].solution, "Z")
def test_to_puz_only_include_puz_specific_data(self): with open('fixtures/ipuz/example.ipuz') as f: ipuz_dict = ipuz.read(f.read()) puzzle = crossword.from_ipuz(ipuz_dict) puz_object = crossword.to_puz(puzzle) self.assertFalse(hasattr(puz_object, "kind"))
def test_read_first_ipuz_fixture(self): with open('fixtures/ipuz/first.ipuz') as f: ipuz_dict = ipuz.read(f.read()) puzzle = crossword.from_ipuz(ipuz_dict) self.assertEqual(puzzle.width, 13) self.assertEqual(puzzle.height, 13) self.assertEqual(puzzle.meta.creator, "Arthur Wynne") self.assertEqual(puzzle.meta.date, "12/21/1913") self.assertEqual(puzzle.meta.title, "FUN's Word-Cross Puzzle") self.assertEqual(puzzle.clues.across["2-3"], "What bargain hunters enjoy") self.assertIsNone(puzzle.block) self.assertIsNone(puzzle.empty) self.assertEqual(puzzle.clues.down["1-32"], "To govern") self.assertEqual(puzzle[0, 0].puzzle, None) self.assertEqual(puzzle[0, 0].solution, None) self.assertEqual(puzzle[6, 0].puzzle, 1) self.assertEqual(puzzle[6, 0].solution, "R") puzzle[6, 0]['solution'] = "X" self.assertEqual(puzzle[6, 0].solution, "X") puzzle[6, 0].solution = "Y" self.assertEqual(puzzle[6, 0]['solution'], "Y") setattr(puzzle[6, 0], "solution", "Z") self.assertEqual(puzzle[6, 0].solution, "Z")
def test_ipuz_export(): with tempfile.TemporaryDirectory() as temp: # Move to a temporary directory so we don't clog up anything important os.chdir(temp) # Generate a simple crossword as .puz gen = Genxword(auto=True, mixmode=False) gen.wlist([ 'land', 'successful', 'climb', 'yet', 'picture', 'traffic', 'skin', 'leadership', 'threaten', 'win' ], 10) gen.grid_size() gen.gengrid('test', 'z') with open('test.ipuz') as fp: # This does automatic validation ipuz.read(''.join(fp.read()))
def test_read_example_may_not_have_solution(self): with open('fixtures/ipuz/example.ipuz') as f: ipuz_dict = ipuz.read(f.read()) del ipuz_dict["solution"] puzzle = crossword.from_ipuz(ipuz_dict) self.assertEqual(puzzle[0, 0].puzzle, 1) self.assertEqual(puzzle[0, 0].solution, None)
def test_read_example_may_not_have_all_cells_defined(self): with open('fixtures/ipuz/example.ipuz') as f: ipuz_dict = ipuz.read(f.read()) ipuz_dict["puzzle"] = [row[:5] for row in ipuz_dict["puzzle"]] ipuz_dict["solution"] = [row[:5] for row in ipuz_dict["solution"]] puzzle = crossword.from_ipuz(ipuz_dict) self.assertEqual(puzzle[10, 10].puzzle, None) self.assertEqual(puzzle[10, 10].solution, None)
def test_read_example_may_not_have_clues(self): with open('fixtures/ipuz/example.ipuz') as f: ipuz_dict = ipuz.read(f.read()) del ipuz_dict["clues"]["Across"] del ipuz_dict["clues"]["Down"] puzzle = crossword.from_ipuz(ipuz_dict) self.assertEqual(list(puzzle.clues.across()), []) self.assertEqual(list(puzzle.clues.down()), [])
def test_write_to_ipuz_only_includes_empty_block(self): with open('fixtures/ipuz/example.ipuz') as f: ipuz_dict = ipuz.read(f.read()) puzzle = crossword.from_ipuz(ipuz_dict) puzzle.block = None puzzle.empty = None new_ipuz_dict = crossword.to_ipuz(puzzle) self.assertNotIn("empty", new_ipuz_dict) self.assertNotIn("block", new_ipuz_dict)
def test_read_and_write_round_trip(self): with open('fixtures/ipuz/example.ipuz') as f: ipuz_dict = ipuz.read(f.read()) puzzle = crossword.from_ipuz(ipuz_dict) new_ipuz_dict = crossword.to_ipuz(puzzle) for key, value in ipuz_dict.items(): self.assertEqual(value, new_ipuz_dict[key]) for key, value in new_ipuz_dict.items(): if key in ipuz_dict: self.assertEqual(value, ipuz_dict[key]) else: self.assertIsNone(value)
def viewer(ipuz_file_name, rendered_file_name): print('Converting "{}" to "{}"'.format(ipuz_file_name, rendered_file_name)) with open(ipuz_file_name) as puzzle_file: ipuz_dict = ipuz.read( puzzle_file.read()) # may raise ipuz.IPUZException puzzle = crossword.from_ipuz(ipuz_dict) with HtmlPage(rendered_file_name) as draw: draw.heading(1, 'Crossword example') draw.heading( 2, '{} by {}'.format(puzzle.meta['title'], puzzle.meta['publisher'])) # draw the empty crossword board with draw.crossword(puzzle.block) as grid: for row in puzzle: grid.add_row([(get_literal(cell.puzzle), ' ') for cell in row]) # container to hold clues with draw.column_container() as _: # disply ACROSS clues with draw.column() as _: draw.heading(3, 'ACROSS') for number, clue in puzzle.clues.across(): draw.line('{} {}'.format(number, clue)) # disply DOWN clues with draw.column() as _: draw.heading(3, 'DOWN') for number, clue in puzzle.clues.down(): draw.line('{} {}'.format(number, clue)) # draw solution draw.heading(2, 'Solution') with draw.crossword(puzzle.block) as grid: for row in puzzle: grid.add_row([(get_literal(cell.puzzle), cell.solution) for cell in row]) draw.rights(puzzle.meta['rights']) print('Done!')
for y, cols in enumerate(ip['puzzle']): for x, cell in enumerate(cols): if not isinstance(cell, dict): continue shapebg = cell.get('style', {}).get('shapebg') if shapebg == 'circle': np.markup().markup[y * np.width + x] = puz.GridMarkup.Circled # np.preamble = ip['intro'] np.save(output_file) def latin1ify(s): for search, replace in LATIN1_SUBS.items(): s = s.replace(search, replace) return s # Start with open(input_file) as x: idata = x.read() try: ip = ipuz.read(idata) except ipuz.IPUZException: print "Yuk." if output_file.endswith(".puz"): printBinary(ip) elif output_file.endswith(".txt"): printASCII(ip) else: print("output_file not puz or txt")
row_cellno=[] col_cellno=[] cellno=[] pencil=[] valid=[] gext=[] time=0 time_state=0 ifil = input('Enter a file name along with path: ') ofile_txt=ifil data_file = open(ifil,'r') data = data_file.read() data_file.close() # puzzle description read from the ipuz file is stored in the 'puzzle' instance try: puzzle = ipuz.read(data) except ipuz.IPUZException: print("Sorry, File corrupted") sys.exit(0) if 'block' in puzzle: block=puzzle['block'] else: block="#" if 'empty' in puzzle: empty=puzzle['empty'] try: empty=int(empty) except ValueError: pass else: empty=0
def parse_ipuz(contents, filename): rebus_shorthands = list("⚷⚳♇♆⛢♄♃♂♁♀☿♹♸♷♶♵♴♳⅘⅗⅖⅕♚♛♜♝♞♟⚅⚄⚃⚂⚁⚀♣♦♥♠+&%$@?*zyxwvutsrqponmlkjihgfedcba0987654321") # i need a .load to create the ipuz_dict, and then maybe i am home free ipuz_dict = ipuz.read(contents.decode("utf-8")) puzzle = crossword.from_ipuz(ipuz_dict) grid_dict = dict(list(zip(string.ascii_uppercase, string.ascii_uppercase))) xd = xdfile.xdfile('', filename) xd.set_header("Author", puzzle.meta.creator) xd.set_header("Editor", puzzle.meta.contributor) xd.set_header("Copyright", puzzle.meta.rights) dt = parse_date_from_filename(parse_pathname(filename).base) if dt: xd.set_header("Date", dt) xd.set_header("Notes", puzzle.meta.description) #xd.set_header("Postscript", "".join(x for x in puzobj.postscript if ord(x) >= ord(' '))) #xd.set_header("Preamble", puzobj.preamble) xd.set_header("Title", puzzle.meta.title) for r, row in enumerate(puzzle): rowstr = "" for c, cell in enumerate(row): if puzzle.block is None and cell.solution == '#': rowstr += xdfile.BLOCK_CHAR elif cell.solution == puzzle.block: rowstr += xdfile.BLOCK_CHAR elif cell.solution == ':': rowstr += xdfile.OPEN_CHAR elif cell == puzzle.empty: rowstr += xdfile.UNKNOWN_CHAR else: n = r * puzzle.width + c ch = cell.solution if ch not in grid_dict: if ch in rebus_shorthands: cellch = ch rebus_shorthands.remove(ch) warn("%s: unknown grid character '%s', assuming rebus of itself" % (filename, ch)) else: cellch = rebus_shorthands.pop() warn("%s: unknown grid character '%s', assuming rebus (as '%s')" % (filename, ch, cellch)) xd.set_header("Rebus", xd.get_header("Rebus") + " %s=%s" % (cellch, ch)) grid_dict[ch] = cellch rowstr += grid_dict[ch] xd.grid.append(rowstr) assert xd.size() == (puzzle.width, puzzle.height), "non-matching grid sizes" # clues answers = {} for posdir, posnum, answer in xd.iteranswers(): answers[posdir[0] + str(posnum)] = answer try: for number, clue in puzzle.clues.across(): cluenum = "A" + str(number) if cluenum not in answers: raise xdfile.IncompletePuzzleParse(xd, "Clue number doesn't match grid: " + cluenum) xd.clues.append((("A", number), decode(clue), answers.get(cluenum, ""))) # xd.append_clue_break() for number, clue in puzzle.clues.down(): cluenum = "D" + str(number) if cluenum not in answers: raise xdfile.IncompletePuzzleParse(xd, "Clue doesn't match grid: " + cluenum) xd.clues.append((("D", number), decode(clue), answers.get(cluenum, ""))) except KeyError as e: raise xdfile.IncompletePuzzleParse(xd, "Clue doesn't match grid: " + str(e)) return xd
def test_read_detects_invalid_ipuz_data(self): with self.assertRaises(ipuz.IPUZException) as cm: ipuz.read("this is wrong") self.assertEqual(str(cm.exception), "No valid JSON could be found")
def test_read_detects_non_string_input(self): with self.assertRaises(ipuz.IPUZException) as cm: ipuz.read(3) self.assertEqual(str(cm.exception), "No valid JSON could be found")
def test_read_detects_valid_json_but_not_dict_json(self): with self.assertRaises(ipuz.IPUZException) as cm: ipuz.read('["version", "kind"]') self.assertEqual(str(cm.exception), "No valid JSON could be found")
def validate_puzzle(self, json_data, expected_exception, **kwargs): with self.assertRaises(ipuz.IPUZException) as cm: ipuz.read(json.dumps(json_data), **kwargs) self.assertEqual(str(cm.exception), expected_exception)
def read_ipuz(f): data_file = open(f.loc,'r') data = data_file.read() data_file.close() try: puzzle = ipuz.read(data) except ipuz.IPUZException: master.withdraw() messagebox.showinfo("Sorry!", "File corrupted") sys.exit(0) # 'block' represents the shaded cells in the grid if 'block' in puzzle: block=puzzle['block'] else: block="#" # 'empty' represents the unshaded cells in the grid that does not hold any value currently if 'empty' in puzzle: empty=puzzle['empty'] try: empty=int(empty) except ValueError: pass else: empty=0 if 'title' in puzzle: title=puzzle['title'] else: title='title' if 'author' in puzzle: author=puzzle['author'] else: author='author' if 'copyright' in puzzle: cpyrt=puzzle['copyright'] else: cpyrt='copyright' if 'notes' in puzzle: notes=puzzle['notes'] else: notes='' # Across and Down cluelist if 'Across' in puzzle['clues'] and 'Down' in puzzle['clues']: for i in range(0,len(puzzle['clues']['Across'])): l=puzzle['clues']['Across'][i] if isinstance(l,dict): across.append(l['clue']) else: across.append(l[1]) acc=len(across) for i in range(0,len(puzzle['clues']['Down'])): l=puzzle['clues']['Down'][i] if isinstance(l,dict): down.append(l['clue']) else: down.append(l[1]) dwn=len(down) if isinstance(puzzle['dimensions']['height'],str): height=int(puzzle['dimensions']['height']) else: height=puzzle['dimensions']['height'] if isinstance(puzzle['dimensions']['width'],str): width=int(puzzle['dimensions']['width']) else: width=puzzle['dimensions']['width'] # solnblock represents the solution grid of the puzzle for i in range(0,height): solnblock.append([]) for j in range(0,width): if isinstance(puzzle['puzzle'][i][j],dict): solnblock[i].append(puzzle['puzzle'][i][j]['cell']) else: solnblock[i].append(puzzle['puzzle'][i][j]) if solnblock[i][j]==block or solnblock[i][j]=="null" or solnblock[i][j]==None: solnblock[i][j]="." else: if 'solution' in puzzle: if isinstance(puzzle['solution'][i][j],dict): solnblock[i][j]=puzzle['solution'][i][j]['value'].upper() else: solnblock[i][j]=puzzle['solution'][i][j].upper() else: solnblock[i][j]="-" f.title=title f.author=author f.cpyrt=cpyrt f.notes=notes f.width=width f.height=height f.solnblock=solnblock f.across=across f.down=down return f