예제 #1
0
def create_all_solved_boards_async():
    """Starts a search for all the solutions for a given board.
    ---
    post:
        tags:
          - Solved Boards
        summary: Starts a search for all the solutions for a given board
                 (may take a while).
        requestBody:
            description: The board to be solved and the max. number of solutions to return.
            required: true
            content:
              application/json:
                schema: SolveAllSchema
        responses:
            202:
              description: The search has been started. The url for querying the
                           search progress is returned in the "location" header
                           of the response.
            400:
              description: Error detail in "message".
    """
    global job_info
    global job_info_lock
    board = lsdk.Board()
    try:
        body = request.get_json()
        board = lsdk.Board(body["board"])  # Board to solve
        max_solutions = body["maxSolutions"]
    except Exception as e:
        raise (InvalidUsage("Bad request: {}".format(str(e)), 400))

    executor = get_executor()

    # Invokes the solving worker giving a unique id to index the
    # corresponding future. This unique id will then be passed to the
    # solving status endpoint so it knows which future to query.
    location_value = ""
    current_job_id = str(uuid.uuid4())
    with job_info_lock:
        info = {"progress_percent": 0.0, "num_solutions": 0, "cancel": False}
        job_info[current_job_id] = info
    executor.submit_stored(current_job_id, solve_board_worker, board,
                           max_solutions, current_job_id)

    location_value = url_for('api.get_solve_status', job_id=current_job_id)
    response = current_app.response_class(status=202)
    response.headers["Location"] = location_value
    return response
예제 #2
0
def get_board_status():
    """Retrieves the status of a given board (the board goes in JSON format in the body).
    ---
    post:
        tags:
          - Boards
        summary: Retrieves the status of a given board.
        requestBody:
            description: The board to be evaluated
            required: true
            content:
              application/json:
                schema: BoardSchema
        responses:
            200:
              description: The status of the board.
              content:
                application/json:
                  schema: BoardStatusSchema
            400:
              description: Error detail in "message".
    """
    try:
        body = request.get_json()
        b = lsdk.Board(body["board"])
        invalid_positions = b.getInvalidPositions()
        d = {
            "isValid": b.isValid,
            "isEmpty": b.isEmpty,
            "isComplete": b.isComplete,
            "invalidPositions": [(p[0], p[1]) for p in invalid_positions]
        }
        return jsonify(d)
    except Exception as e:
        raise (InvalidUsage("Bad request: {}".format(str(e)), 400))
예제 #3
0
def create_one_solved_board():
    """Finds one solution for a given board (if possible).
    ---
    post:
        tags:
          - Solved Boards
        summary: Returns one solution for a given board.
        requestBody:
            description: The board to be solved
            required: true
            content:
              application/json:
                schema: BoardSchema
        responses:
            200:
              description: A solution for the given board
              content:
                application/json:
                  schema: SolvedBoardSchema
            400:
              description: Error detail in "message".
    """
    s = lsdk.Board()  # Board to hold the solution
    result = lsdk.SolverResult.NO_ERROR

    try:
        body = request.get_json()
        b = lsdk.Board(body["board"])  # Board to solve
        solver = lsdk.Solver()
        result = solver.solve(b, s)
    except Exception as e:
        raise (InvalidUsage("Bad request: {}".format(str(e)), 400))

    if result == lsdk.SolverResult.NO_ERROR:
        return jsonify({"board": [v for v in s]})
    else:
        raise (InvalidUsage("Not solvable: {}".format(result), 400))
예제 #4
0
def gen_board_worker(difficulty_level):
    """Generates a board with the given difficulty_level.
    Returns a dictionary with the following keys:
    . "gen_result": one of the values of GeneratorResult
    . "gen_board": the generated board if any
    . "start_time"
    . "finish_time"
    """
    start_time = time.time()

    gen_board = lsdk.Board()
    gen_result = lsdk.GeneratorResult.NO_ERROR

    gen = lsdk.Generator()

    asyncGenCompleted = False

    # Handler for generation finished: captures the results.
    def on_gen_finished(result, board):
        nonlocal asyncGenCompleted
        asyncGenCompleted = True
        nonlocal gen_result
        gen_result = result
        nonlocal gen_board
        gen_board = board

    gen.asyncGenerate(
        difficulty_level,
        None,  # Does nothing on progress
        on_gen_finished)
    while not asyncGenCompleted:
        time.sleep(0.1)

    finish_time = time.time()

    # Set future result
    fut_result = {
        # GenerationResult is not JSON serializable.
        # That's the reason for the str explicit conversion.
        "status": str(gen_result),
        # Board is not JSON serializable.
        # That's the reason for the list compreheension
        "board": [val for val in gen_board],
        "gen_time": finish_time - start_time
    }

    return fut_result
예제 #5
0
import py_libsudoku as lsdk
import time

asyncGenComplete = False
genBoard = lsdk.Board()


def onGenProgress(currentStep, totalSteps):
    print("    .... asyncGenerate at step {} of {}".format(
        currentStep, totalSteps))


def onGenFinished(result, board):
    global genBoard
    genBoard = board
    global asyncGenComplete
    asyncGenComplete = True
    print()
    print(".... asyncGenerate finished: {}".format(result))


gen = lsdk.Generator()

print("Will generate board with Hard difficulty ...")

gen.asyncGenerate(lsdk.PuzzleDifficulty.HARD, onGenProgress, onGenFinished)

while not asyncGenComplete:
    time.sleep(0.1)

print("Generated board: {}".format(genBoard))
예제 #6
0
import py_libsudoku

clear_board = py_libsudoku.Board()

print("clear_board = {}".format(clear_board))

print("Is clear_board empty? {}".format(clear_board.isEmpty))

print("Is clear_board valid? {}".format(clear_board.isValid))

print("Is clear_board complete? {}".format(clear_board.isComplete))

print()
print()

one_to_nine = py_libsudoku.Board([1, 2, 3, 4, 5, 6, 7, 8, 9])

print("one_to_nine = {}".format(one_to_nine))

print("Is one_to_nine valid? {}".format(one_to_nine.isValid))

print()
print()

one_to_nine_cpy = py_libsudoku.Board(one_to_nine)

print("one_to_nine_cpy = {}".format(one_to_nine_cpy))

print("Is one_to_nine equal to its copy? {}".format(
    one_to_nine == one_to_nine_cpy))
예제 #7
0

def onSolverFinished(result, solvedBoards):
    global asyncSolveComplete
    asyncSolveComplete = True
    print()
    print("asyncSolveForGood finished: {}".format(result))
    print("Found {} solution(s):".format(len(solvedBoards)))
    for b in solvedBoards:
        print()
        print("{}".format(b))


solvable_one_solution = lsk.Board([
    0, 0, 6, 0, 0, 8, 5, 0, 0, 0, 0, 0, 0, 7, 0, 6, 1, 3, 0, 0, 0, 0, 0, 0, 0,
    0, 9, 0, 0, 0, 0, 9, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 8, 0, 0, 4, 0, 0, 5, 3,
    0, 0, 0, 0, 1, 0, 7, 0, 5, 3, 0, 0, 0, 0, 5, 0, 0, 6, 4, 0, 0, 0, 3, 0, 0,
    1, 0, 0, 0, 6, 0
])

solution = lsk.Board()

solver = lsk.Solver()

print("Board to be solved - 'solvable_one_solution': {}".format(
    solvable_one_solution))

print("Looking for solution ...")

result = solver.solve(solvable_one_solution, solution)
if result == lsk.SolverResult.NO_ERROR:
    print("... solution found: {}".format(solution))