Beispiel #1
0
def checkProblem(problem_id):
    problem = db_session.query(Problem).get(problem_id)
    form = request.form
    messages = []
    total = len(problem.requirements)
    correct = 0.0
    for req in problem.requirements:
        cond = req.condition
        try:
            if check_answer(cond,form):
                correct += 1
            else:
                messages.append(req.comment)
        except:
                return jsonify(errors = ["Please check the input!"])
    rate = int((correct/total)*100) if total != 0 else 100
    need_new = True
    for up in current_user.problems:
        if up.problem == problem:
            up.rate = rate
            need_new = False
            uproblem = up
            break
    if need_new:
        uproblem = UserProblem(rate=rate)
        uproblem.problem = problem
        current_user.problems.append(uproblem)
    trial = Trial()
    trial.rate = rate
    for key in request.form.keys():
        trial.answers.append(Answer(field=key,value=request.form[key]))
    uproblem.trials.append(trial)
    db_session.commit()
    return jsonify(messages = messages,rate = rate)
Beispiel #2
0
def main():

    if version_info < REQ_VERSION:
        print("Python version too low! Please use", REQ_VERSION, "or later.")

    test_cases = read_test_cases()

    for test_case in test_cases:
        start = time.time()
        answer = "This puzzle is not solvable."
        queue = PriorityQueue()
        visited = set()

        if len(argv) < 2 or argv[2].strip().to_lower() != "no_check=true":
            if not has_answer(test_case):
                print(time.time() - start, answer)
                continue

        """
        The queue follows the order
            total cost, level, matrix, answer
        for all elements """
        queue.put((0, 0, test_case, ""))

        while not queue.empty():
            _, level, matrix, current_answer = queue.get()

            if level > 50:
                break

            if check_answer(matrix):
                answer = current_answer
                break

            permutations = calculate_permutations(matrix)

            for permutation, letter in permutations:
                # A tuple is necessary for storing in a set since it is immutable
                permutation_tuple = tuplize(permutation)
                if permutation_tuple not in visited:
                    heuristic_cost = calculate_heuristic(permutation)
                    visited.add(permutation_tuple)
                    queue.put((heuristic_cost+level+1,
                               level+1,
                               permutation,
                               current_answer + letter
                               ))

        print(time.time() - start, answer)
Beispiel #3
0
def main():
    if version_info < REQ_VERSION:
        print("Python version too low! Please use", REQ_VERSION, "or later.")
        exit(1)

    test_cases = read_test_cases()

    for test_case in test_cases:
        start = time.time()
        answer = "This puzzle is not solvable."
        visited = set()
        queue = Queue()

        if len(argv) < 2 or argv[2].strip().to_lower() != "no_check=true":
            if not has_answer(test_case):
                print(time.time() - start, answer)
                continue

        queue.put((0, test_case, ""))

        while not queue.empty():
            level, matrix, current_answer = queue.get()

            # A tuple is necessary for storing in a set since it is immutable
            matrix_tuple = tuplize(matrix)

            if matrix_tuple not in visited:
                visited.add(matrix_tuple)
            else:
                continue

            if level > 50:
                break

            if check_answer(matrix):
                answer = current_answer
                break

            permutations = calculate_permutations(matrix)

            for permutation, letter in permutations:
                permutation_tuple = tuplize(permutation)
                if permutation_tuple not in visited:
                    queue.put((level + 1,
                               permutation,
                               current_answer + letter
                               ))

        print(time.time() - start, answer)
Beispiel #4
0
def solve(grid, output, heuristic):

    if version_info < REQ_VERSION:
        print("Python version too low! Please use", REQ_VERSION, "or later.")

    test_case = grid

    start = time.time()
    answer = "This puzzle is not solvable."
    queue = PriorityQueue()
    visited = set()

    if not has_answer(test_case):
        print("TIME: " + str(time.time() - start),
              "   ---   ANSWER: " + str(answer))
        return
    """
    The queue follows the order
        total cost, level, matrix, answer
    for all elements """
    queue.put((0, 0, test_case, ""))
    while not queue.empty():
        _, level, matrix, current_answer = queue.get()

        if level > 50:
            break

        if check_answer(matrix, output):
            answer = current_answer
            break

        permutations = calculate_permutations(matrix)

        for permutation, letter in permutations:
            # A tuple is necessary for storing in a set since it is immutable
            permutation_tuple = tuplize(permutation)
            if permutation_tuple not in visited:
                heuristic_cost = calculate_heuristic(permutation, output,
                                                     heuristic)
                visited.add(permutation_tuple)
                queue.put((heuristic_cost + level + 1, level + 1, permutation,
                           (current_answer + letter)))

    print("TIME: " + str(time.time() - start),
          "   ---   ANSWER: " + str(answer))
    print("Emulating answer ...")
    return answer
Beispiel #5
0
def riddles():
    '''
    If someone tries to load page without a username in session cookie
    send them to the homepage to pick one
    '''
    if "username" not in session:
        return redirect("/")
    username = session["username"]
    if "score" not in session:
        # On first load, score won't be in cookie yet, so add it now
        session["score"] = 0
    score = session["score"]
    with open("data/scores.json") as scores_file:
        scores = json.load(scores_file)
    if request.method == "GET":
        '''
        GET will occur only on initial load, so set some initial game
        progress variables in session cookie, and then render first
        riddle
        '''
        session["score"] = 0
        # Attempts tracks how many times user has tried to answer riddle
        session["attempts"] = 0
        next_riddle = get_next_riddle(RIDDLES, None)
        return render_template(
                "game.html", 
                username=username, 
                riddle=next_riddle, 
                progress=0, 
                score=session["score"], 
                hiscores=scores)
    if request.method == "POST":
        '''
        After initial load, user enters their answer in a form and submits
        which is sent back to this view via POST request. Check whether
        the answer was correct and then render the relevant data.
        '''
        answer = request.form["answer"]
        progress = int(request.form["progress"])
        current_riddle = RIDDLES[progress]
        if not check_answer(current_riddle, answer):
            '''
            Answer was incorrect, user has ATTEMPTS_PER_RIDDLE attempts to 
            answer, and then they are sent onto the next riddle. 
            '''
            session["attempts"] += 1
            message = """Sorry, your answer '%s' was incorrect. 
                        You have %s attempt left.""" % (
                            answer, 
                            (ATTEMPTS_PER_RIDDLE - session["attempts"]))
            if session["attempts"] >= ATTEMPTS_PER_RIDDLE:
                next_riddle = get_next_riddle(RIDDLES, progress)
                if next_riddle == None:
                    # No more riddles, so the game is over
                    return redirect("/gameover")
                progress += 1
                current_riddle = next_riddle
                session["attempts"] = 0
                message = """Sorry, your answer '%s' was incorrect and 
                            you ran out of attempts. Try the next 
                            riddle below.""" % answer
            return render_template(
                    "game.html", 
                    username=username, 
                    riddle=current_riddle, 
                    progress=progress, 
                    incorrect=True, 
                    message=message, 
                    answer=answer, 
                    score=score, 
                    hiscores=scores)
        else:
            '''
            Answer was correct, increment score by POINTS_PER_RIDDLE and
            then load next riddle.
            '''
            session["score"] = score + POINTS_PER_RIDDLE
            next_riddle = get_next_riddle(RIDDLES, progress)
            if next_riddle == None:
                # No more riddles, so the game is over
                return redirect("/gameover")
            progress += 1
            current_riddle = next_riddle
            # Reset number of attempts for next riddle
            session["attempts"] = 0
            message = "Correct! You have added %s %s to your score" % (
                        POINTS_PER_RIDDLE, 
                        "point" if POINTS_PER_RIDDLE == 1 else "points")
            return render_template(
                    "game.html", 
                    username=username, 
                    riddle=current_riddle, 
                    progress=progress, 
                    last_correct=True, 
                    message=message,
                    score=session["score"], 
                    hiscores=scores)
    # If neither GET or POST requests brought us here, use this as fallback
    return redirect("/")
Beispiel #6
0
def handle_answer(request):
    """
    分析答案
    """

    result = {"status": 0, "data": {}}
    paper_id = request.POST.get('paper_id', '0')
    answer_str = request.POST.get('answer', '')
    answer = utils.convert_to_list(answer_str)
    try:
        paper = Paper.objects.get(id=paper_id)
    except (Paper.DoesNotExist, ValueError), e:
        return HttpResponse(simplejson.dumps(result))
    
    if not utils.check_answer(answer):    
        return HttpResponse(simplejson.dumps(result))
    #验证防刷机制
    uni_mark = request.COOKIES.get(settings.COOKIE_KEY, "")
    if not uni_mark:
        return HttpResponse(simplejson.dumps(result))
    start_datetime = cache.get(uni_mark, None)
    if not start_datetime:
        return HttpResponse(simplejson.dumps(result))
    interval_seconds = (datetime.datetime.now() - start_datetime).seconds
    if interval_seconds < (paper.get_questions_count() * 1) or interval_seconds > ANSWER_MAX_HOUR * 60 * 60:
        return HttpResponse(simplejson.dumps(result))
        
    # 获取数据库的数据
    correct_answer = paper.answer_orders
    score_list = paper.score
Beispiel #7
0
 def test_empty_answer(self):
     self.assertFalse(check_answer(RIDDLES[7], ""),
                      "Empty answer was not marked as empty")
Beispiel #8
0
 def test_incorrect_answer(self):
     self.assertFalse(check_answer(RIDDLES[5], "incorrect"),
                      "Incorrect answer was not marked as incorrect")
Beispiel #9
0
 def test_correct_answer(self):
     self.assertTrue(check_answer(RIDDLES[3], "lawsuit"),
                     "Correct answer was checked as incorrect")
Beispiel #10
0
 def test_check_answer_false(self):
     not_ans = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],
                [13, 14, 0, 15]]
     assert not utils.check_answer(not_ans)
Beispiel #11
0
 def test_check_answer_true(self):
     ans = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]]
     assert utils.check_answer(ans)