예제 #1
0
파일: views.py 프로젝트: 96tm/MathQuiz
def profile(user_id):
    return render_template(
        "profile.html",
        username=database.fetch_user_name(user_id),
        difficulty=database.fetch_user_difficulty(user_id),
        startedDate=database.fetch_user_joined_date(user_id),
        gamesPlayed=database.fetch_user_games_started(user_id),
        gamesCompleted=database.fetch_user_games_completed(user_id),
        easyScore=database.fetch_user_score(user_id, question.Difficulties.EASY),
    )
예제 #2
0
파일: views.py 프로젝트: 96tm/MathQuiz
def quiz(typee):
    # convert string types to internal enums
    difficulty = question.Difficulties[session["difficulty"].upper()]
    type = question.Types[typee.upper()]
    if type == question.Types.ALL:
        type = random.choice(list(question.Types))
        # looks ugly but we don't want to accidently get ourselves into a
        # semi infinite loop where we always choose Type.ALL do we?
        if type == question.Types.ALL:
            type = question.Types.ADDSUB

    startTime = time()
    try:
        correctlyAnswered = int(session["correctlyAnswered"])
        incorrectlyAnswered = int(session["incorrectlyAnswered"])
        startTime = float(session["startTime"])
    except KeyError:
        # force a new quiz
        session["quizId"] = -1

    previousAnswer, userAnswer, userAnswerCorrect = None, None, None
    scoring = []

    # number of questions remaining in quiz
    # if we still have to ask questions of the user
    timeRemaining = 30 - (time() - startTime)

    if "quizId" not in session or session["quizId"] == -1:
        quizId = session["quizId"] = database.create_quiz(type)
        startTime = session["startTime"] = time()
        timeRemaining = 30
        correctlyAnswered = session["correctlyAnswered"] = 0
        incorrectlyAnswered = session["incorrectlyAnswered"] = 0

    elif timeRemaining >= 0:
        # if we have already started the quiz
        try:
            previousAnswer = session["previousQuestionAnswer"]
            userAnswer = int(request.form["result"])
            userAnswerCorrect = previousAnswer == userAnswer

            score = question.score(difficulty, userAnswerCorrect)

            # calculate streak bonus
            streakLength = database.calculate_streak_length(session["userId"], session["quizId"])
            streakScore = 0 if streakLength < 3 else 5 + streakLength
            score += streakScore
            if streakScore != 0:
                scoring.append("Streak of %d. %d bonus points!" % (streakLength, streakScore))

            database.quiz_answer(
                session["userId"], session["quizId"], previousAnswer, userAnswer, userAnswerCorrect, score
            )

            scoring.append("Score so far: %d points!" % database.cumulative_quiz_score(session["quizId"]))
            if userAnswerCorrect:
                correctlyAnswered += 1
            else:
                incorrectlyAnswered += 1
        except (ValueError, KeyError):
            flash("Please enter a number as an answer")

    if timeRemaining >= 0:
        q = question.generateQuestion(type, difficulty)
        session["previousQuestionAnswer"] = q.answer

        response = make_response(
            render_template(
                "quiz.html",
                question=str(q),
                scoring=scoring,
                timeRemaining=int(timeRemaining),
                answered=userAnswer is not None,  # has the user answered this question
                correct=userAnswerCorrect,
            )
        )
    else:
        # calculate score
        numberAnswered = correctlyAnswered + incorrectlyAnswered

        oldHighScore = database.fetch_user_score(session["userId"], difficulty)
        oldLeaderboardPosition = database.fetch_user_rank(session["userId"], difficulty)
        score = database.quiz_complete(difficulty, session["quizId"], correctlyAnswered, numberAnswered)
        newLeaderboardPosition = database.fetch_user_rank(session["userId"], difficulty)
        leaderboardJump = None
        if oldLeaderboardPosition is not None and newLeaderboardPosition is not None:
            leadboardJump = newLeaderboardPosition - oldLeaderboardPosition

        # reset quiz
        session["quizId"] = -1

        newDifficulty = False
        # if user answered > 80% of answers correctly and answered > 10 correctly increase difficulty level
        if numberAnswered >= 8 and (float(correctlyAnswered) / numberAnswered) > 0.8:
            newDifficulty = question.Difficulties.index(session["difficulty"].upper()) + 1
            # don't go over max difficulty (hard)
            if newDifficulty < len(question.Difficulties):
                database.set_user_difficulty(session["userId"], newDifficulty)
                newDifficulty = question.Difficulties[newDifficulty].lower()

        response = make_response(
            render_template(
                "quizComplete.html",
                correct=userAnswerCorrect,
                numberCorrect=correctlyAnswered,
                newDifficulty=newDifficulty,
                oldHighScore=oldHighScore,
                score=score,
                leaderboardJump=leaderboardJump,
                total=correctlyAnswered + incorrectlyAnswered,
            )
        )

    # persist changes to session
    session["correctlyAnswered"] = correctlyAnswered
    session["incorrectlyAnswered"] = incorrectlyAnswered

    return response