Spaces:
Sleeping
Sleeping
File size: 14,953 Bytes
67acd34 | 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | #!/usr/bin/env python3
"""
Simple script to verify if a puzzle ASCII state is solved.
Supports: bridges, undead, galaxies, pattern, loopy
Usage:
# From stdin
python verifier.py bridges < ascii_state.txt
python verifier.py undead < ascii_state.txt
# From command line argument
python verifier.py bridges "3|.|2\n..."
python verifier.py undead "G: 3 V: 1 Z: 6\n\n 2 3 1 1 \n..."
python verifier.py galaxies "+-+-+\n|o o|\n+-+-+\n|o o|\n+-+-+\n"
python verifier.py loopy " x x x - x \nx x0x |3| x\n..."
# With escape sequences
echo "3|.|2\n..." | python verifier.py bridges
echo "G: 3 V: 1 Z: 6\n\n..." | python verifier.py undead
echo "+-+-+\n|o o|\n..." | python verifier.py galaxies
"""
import sys
import argparse
import warnings
from rlp.puzzle import Puzzle
from rlp.ascii_parser import parse_ascii_bridges, check_bridges_structural_validity, parse_ascii_undead, check_undead_structural_validity, parse_ascii_galaxies, check_galaxies_structural_validity, parse_ascii_pattern, parse_ascii_loopy
def verify_ascii_state(puzzle, ascii_text: str, problem_ascii: str = None) -> str:
"""
Verify if an ASCII puzzle state is solved.
Args:
puzzle: Puzzle instance (must be initialized with new_game())
ascii_text: ASCII representation of puzzle state
problem_ascii: Optional ASCII representation of the original problem state.
When provided, checks that pre-filled cells haven't been modified.
For bridges: checks islands haven't moved/changed.
For galaxies: checks dots haven't moved/removed.
Returns:
str: "SOLVED" if the state is solved, "NOT SOLVED" otherwise
Raises:
Exception: If verification fails
"""
puzzle_type = puzzle.puzzle_name
try:
if puzzle_type == "bridges":
# Warn if problem_ascii not provided
if problem_ascii is None:
warnings.warn(
"verify_ascii_state called for bridges without problem_ascii. "
"Startboard modification check will be skipped.",
UserWarning
)
# First check structural validity (includes island modification check if problem_ascii provided)
if not check_bridges_structural_validity(str(ascii_text), problem_ascii=problem_ascii):
# Structurally invalid (broken lines, modified clues, etc.)
return "NOT SOLVED"
# Parse ASCII with Python parser
state_dict = parse_ascii_bridges(str(ascii_text))
# Load state dict
loaded_state_ptr = puzzle.load_state_dict(state_dict)
# Get free_game function
me = puzzle.fe.contents.me.contents
game = me.ourgame.contents
free_game_func = game.free_game
try:
# Check if solved (completed flag)
is_solved = loaded_state_ptr.contents.completed
if is_solved:
return "SOLVED"
else:
return "NOT SOLVED"
finally:
# Free the loaded state
if loaded_state_ptr:
free_game_func(loaded_state_ptr)
elif puzzle_type == "undead":
# First check structural validity
if not check_undead_structural_validity(str(ascii_text)):
# Structurally invalid (missing header, no grid, invalid format, etc.)
return "NOT SOLVED"
# Use new pipeline: parse → load → check
# Parse ASCII with Python parser
state_dict = parse_ascii_undead(str(ascii_text))
# Load state dict
loaded_state_ptr = puzzle.load_state_dict(state_dict)
# Get free_game function
me = puzzle.fe.contents.me.contents
game = me.ourgame.contents
free_game_func = game.free_game
try:
# Check if solved (undead only has 'solved' field, not 'completed')
is_solved = loaded_state_ptr.contents.solved
if is_solved:
return "SOLVED"
else:
return "NOT SOLVED"
finally:
# Free the loaded state
if loaded_state_ptr:
free_game_func(loaded_state_ptr)
elif puzzle_type == "galaxies":
# Warn if problem_ascii not provided
if problem_ascii is None:
warnings.warn(
"verify_ascii_state called for galaxies without problem_ascii. "
"Startboard modification check will be skipped.",
UserWarning
)
# First check structural validity (includes dot modification check if problem_ascii provided)
if not check_galaxies_structural_validity(str(ascii_text), problem_ascii=problem_ascii):
# Structurally invalid (invalid dimensions, dots modified, etc.)
return "NOT SOLVED"
# Use new pipeline: parse → load → check
# Parse ASCII with Python parser
state_dict = parse_ascii_galaxies(str(ascii_text))
# Load state dict
loaded_state_ptr = puzzle.load_state_dict(state_dict)
# Get free_game function
me = puzzle.fe.contents.me.contents
game = me.ourgame.contents
free_game_func = game.free_game
try:
# Check if solved (galaxies uses 'completed' field)
is_solved = loaded_state_ptr.contents.completed
if is_solved:
return "SOLVED"
else:
return "NOT SOLVED"
finally:
# Free the loaded state
if loaded_state_ptr:
free_game_func(loaded_state_ptr)
elif puzzle_type == "pattern":
# Use new pipeline: parse → load → check
# Parse ASCII with Python parser
state_dict = parse_ascii_pattern(str(ascii_text))
# Load state dict
loaded_state_ptr = puzzle.load_state_dict(state_dict)
# Get free_game function
me = puzzle.fe.contents.me.contents
game = me.ourgame.contents
free_game_func = game.free_game
try:
# Check if solved (pattern uses 'completed' field)
is_solved = loaded_state_ptr.contents.completed
if is_solved:
return "SOLVED"
else:
return "NOT SOLVED"
finally:
# Free the loaded state
if loaded_state_ptr:
free_game_func(loaded_state_ptr)
elif puzzle_type == "loopy":
# Use new pipeline: parse → load → check
# IMPORTANT: Early dimension check to prevent segfaults
# Creating temp puzzle instances for each unique dimension causes segfaults
# after ~20 instances. Validate dimensions BEFORE calling parse_ascii_loopy
# to avoid creating temp puzzles for invalid/malformed ASCII.
expected_dimensions = {(5, 5), (7, 7), (10, 10)} # easy, medium, hard
# Pre-check dimensions without creating any puzzle instances
try:
ascii_str = str(ascii_text)
if ascii_str.endswith('\n'):
lines = ascii_str[:-1].split('\n')
else:
lines = ascii_str.split('\n')
content_lines = [line for line in lines if line.strip() or len(line) > 0]
H = len(content_lines) if len(content_lines) > 0 else len(lines)
max_W_content = max((len(line) for line in lines), default=0)
if max_W_content == 0:
return "NOT SOLVED"
W = max_W_content + 1
if (H - 1) % 2 != 0:
H += 1
# Check valid dimension format
if (W - 2) % 2 != 0 or (H - 1) % 2 != 0:
return "NOT SOLVED"
w = (W - 2) // 2
h = (H - 1) // 2
if w < 1 or h < 1:
return "NOT SOLVED"
# Reject unexpected dimensions to prevent temp puzzle creation
if (w, h) not in expected_dimensions:
return "NOT SOLVED"
except Exception:
return "NOT SOLVED"
try:
# Parse ASCII with Python parser, passing existing puzzle instance to avoid creating temp ones
state_dict = parse_ascii_loopy(str(ascii_text), grid_type=0, puzzle_instance=puzzle)
except ValueError as e:
# Check if this is a dimension validation error (model mistake in response format)
error_msg = str(e)
if any(keyword in error_msg for keyword in [
"Invalid canvas width",
"Invalid canvas height",
"Invalid dimensions",
"Dimension mismatch"
]):
# Model made a mistake in the response format - treat as NOT SOLVED
return "NOT SOLVED"
else:
# Other ValueError - might indicate a bug, re-raise
raise
# Load state dict
loaded_state_ptr = puzzle.load_state_dict(state_dict)
# Get free_game function
me = puzzle.fe.contents.me.contents
game = me.ourgame.contents
free_game_func = game.free_game
try:
# Check if solved (loopy uses 'solved' field)
is_solved = loaded_state_ptr.contents.solved
if is_solved:
return "SOLVED"
else:
return "NOT SOLVED"
finally:
# Free the loaded state
if loaded_state_ptr:
free_game_func(loaded_state_ptr)
else:
# For other puzzles, fall back to old method
is_solved = puzzle.check_ascii_solved(str(ascii_text))
if is_solved:
return "SOLVED"
else:
return "NOT SOLVED"
except ValueError as e:
# Check if this is a dimension validation error from parsing (model mistake)
error_msg = str(e)
if any(keyword in error_msg for keyword in [
"Invalid canvas width",
"Invalid canvas height",
"Invalid dimensions",
"Dimension mismatch",
"Invalid grid width",
"Invalid grid height"
]):
# Model made a mistake in the response format - treat as NOT SOLVED
return "NOT SOLVED"
else:
# Other ValueError - might indicate a bug, re-raise
raise
except Exception as e:
# Other unexpected errors - re-raise with context
raise Exception(f"Failed to check puzzle state: {e}") from e
def main():
"""Read ASCII state and check if solved."""
parser = argparse.ArgumentParser(
description='Verify if a puzzle ASCII state is solved',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python verifier.py bridges "3|.|2\\n..."
python verifier.py undead "G: 3 V: 1 Z: 6\\n\\n 2 3 1 1 \\n..."
python verifier.py galaxies "+-+-+\\n|o o|\\n..."
echo "..." | python verifier.py bridges
"""
)
parser.add_argument(
'puzzle_type',
choices=['bridges', 'undead', 'galaxies', 'pattern', 'loopy'],
help='Type of puzzle to verify'
)
parser.add_argument(
'ascii_text',
nargs='?',
help='ASCII representation of puzzle state (if not provided, read from stdin)'
)
parser.add_argument(
'--arg',
default=None,
help='Puzzle initialization argument (e.g., "5x5deL" for bridges, "4x4" for undead)'
)
parser.add_argument(
'--problem',
default=None,
help='Original problem ASCII state (for checking startboard modifications)'
)
args = parser.parse_args()
# Read ASCII input
if args.ascii_text:
# ASCII state provided as command line argument
ascii_text = args.ascii_text
# Convert escape sequences like \n to actual newlines
# This handles cases where user passes "text\nmore" from command line
ascii_text = ascii_text.encode().decode('unicode_escape')
else:
# Read from stdin
ascii_text = sys.stdin.read()
if not ascii_text.strip():
print("Error: No ASCII state provided", file=sys.stderr)
sys.exit(1)
# Determine puzzle initialization argument if not provided
if args.arg is None:
if args.puzzle_type == "bridges":
args.arg = '5x5deL' # Default for bridges
elif args.puzzle_type == "undead":
args.arg = '4x4' # Default for undead
elif args.puzzle_type == "galaxies":
args.arg = '4x4' # Default for galaxies
elif args.puzzle_type == "pattern":
args.arg = '5x5' # Default for pattern
elif args.puzzle_type == "loopy":
args.arg = '5x5t0' # Default for loopy (5x5 square grid)
# Create puzzle instance
puzzle = Puzzle(args.puzzle_type, arg=args.arg, headless=True)
puzzle.new_game() # Initialize the game structure
try:
# Process problem ASCII if provided
problem_ascii = None
if args.problem:
problem_ascii = args.problem.encode().decode('unicode_escape')
# Verify the ASCII state
result = verify_ascii_state(puzzle, ascii_text, problem_ascii=problem_ascii)
print(result)
sys.exit(0 if result == "SOLVED" else 1)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
import traceback
traceback.print_exc()
sys.exit(1)
finally:
# Clean up puzzle instance
import gc
gc.collect()
del puzzle
gc.collect()
if __name__ == "__main__":
main()
|