2
\$\begingroup\$

I finally have a working version of my quiz web/game app. I used C# ASP.NET MVC with Entity Framework and JavaScript/Jquery. Would you guys mind taking a look at my code and make suggestions/improvements and also rate my app overall? I wish I could deploy a demo somewhere but I have no money for azure.

This is basically a browser game app similar to a traditional quiz in which you must answer questions about different topics and at the end it displays how many questions you got right. The nice feature here is that there's a countdown to answer all questions so you can skip a specific question you can't remember atm and leave it for later.

Full code on pastebin.com.

Index.cshtml

@model Pasapalabra.Models.Question

@{
    ViewBag.Title = "Pasapalabra";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<!-- Letters -->
<div id="letters" class="lettersDiv text-center">
    <span id="A">A</span>
    <span id="B">B</span>
    <span id="C">C</span>
    <span id="D">D</span>
    <span id="E">E</span>
    <span id="F">F</span>
    <span id="G">G</span>
    <span id="H">H</span>
    <span id="I">I</span>
    <span id="J">J</span>
    <span id="K">K</span>
    <span id="L">L</span>
    <span id="M">M</span>
    <span id="N">N</span>
    <span id="O">O</span>
    <span id="P">P</span>
    <span id="Q">Q</span>
    <span id="R">R</span>
    <span id="S">S</span>
    <span id="T">T</span>
    <span id="U">U</span>
    <span id="V">V</span>
    <span id="W">W</span>
    <span id="X">X</span>
    <span id="Y">Y</span>
    <span id="Z">Z</span>
</div>

<!-- Start Game Button -->
<div class="row startGameBtnDiv">
    <div class="text-center">
        <button id="startGameBtn" class="btn btn-primary btn-lg center-block startGameBtn">Play</button>
    </div>
</div>

<!-- While game is running -->
<div id="game" class="hidden gameRunning">

    <!-- Question's description and input field -->
    <div class="row">
        <div class="col-lg-12 text-center">
            <h2 id="letter">Loading...</h2>
            <h3 id="description">Loading...</h3>
            <input id="inputWord" class="inputWord form-control" type="text" name="inputWord" autocomplete="off" placeholder="Guess the word" />
            <button id="sendAnswerBtn" class="btn btn-primary btn-lg sendAnswerBtn">OK</button>
            <button id="pasapalabraBtn" class="btn btn-secondary btn-lg pasapalabraBtn">Pasapalabra</button>
        </div>
    </div>
</div>

<!-- Results -->
<div id="finalGameScore" class="hidden finalGameScore">
    <div class="row">
        <div class="col-lg-12 text-center">
            <h2>You guessed correctly:</h2>
            <h3><span id="score">0</span> out of 26 words.</h3>
            <button id="backToMainPageBtn" class="btn btn-primary btn-lg backToMainPageBtn">Back to main page</button>
        </div>
    </div>
</div>

@section scripts
{
    <script>

        $(document).ready(function () {

            // Variables
            var startPage = true;
            var gameOn = false;
            var score = 0;
            var letterPosition = -1;
            var questions = [];
            const asciiOfA = 65;
            var timer = 0;

            // Function to get questions from database
            function getQuestions() {
                return $.ajax({
                    url: '/Questions/GetQuestions',
                    type: 'GET',
                    dataType: 'json',
                    success: function (data) {
                        return data;
                    },
                    error: function (error) {
                        alert("An unexpected error occurred. Please reload the page.");
                    }
                });
            }

            // Initializes questions variable with database data when GetQuestions() is called
            $.when(getQuestions()).then(function (data) {
                if (data != null) {
                    questions = data;
                } else {
                    alert("An unexpected error occurred. Please reload the page.");
                }
            });

            // Keyboard accessibility
            $(document).keypress(function (e) {
                if (e.which == 13) {
                    if (gameOn) {
                        checkAnswer();
                    } else {
                        if (startPage) {
                            play();
                        } else {
                            backToMainPage();
                        }
                    }
                }
                if (e.which == 32) {
                    if (gameOn) {
                        pasapalabra();
                    }
                }
            });

            // Buttons
            $("#startGameBtn").click(function () {
                play();
            });
            $("#sendAnswerBtn").click(function () {
                checkAnswer();
            });
            $("#pasapalabraBtn").click(function () {
                pasapalabra();
            });
            $("#backToMainPageBtn").click(function () {
                backToMainPage();
            });

            // Start Game
            function play() {
                getQuestions();
                startTimer();
                gameOn = true;
                startPage = false;
                $(".startGameBtnDiv").remove();
                $('#game').removeClass("hidden");
                isGameOn();
            }

            // Game logic
            function isGameOn() {

                // Get all questions that haven't been answered yet
                var questionsLeft = questions.filter(function (question) {
                    return question.IsCorrect == null;
                })

                // If there are questions left in array, show next question
                if (questionsLeft.length !== 0) {
                    showQuestion(questionsLeft[0]);
                    letterPosition = getLetterPosition(questionsLeft[0]);
                }

                // Otherwise, game over
                else {
                    gameOver();
                }
            }

            // Returns array position of current question
            function getLetterPosition(question) {
                var pos;
                for (var i = 0; i < questions.length; i++) {
                    if (questions[i].Letter === question.Letter) {
                        pos = i;
                        break;
                    }
                }
                return pos;
            }

            // Show current question
            function showQuestion(question) {
                $("#letter").html(question.ContainsOrStartsWithLetter + " " + question.Letter);
                $("#description").html(question.Description);
                $("#inputWord").val('');
                $("#inputWord").focus();
            }

            // Check if answer is correct
            function checkAnswer() {

                // Get player's input
                var inputWord = $("#inputWord").val();

                // Clean up input
                inputWord = inputWord.trim();
                inputWord = inputWord.toLowerCase();

                // Get answered question from array of questions
                var answeredQuestion = questions[letterPosition];

                // Get span of answered question's letter
                var letter = "";
                for (var i = asciiOfA; i < questions.length + asciiOfA; i++) {
                    if (String.fromCharCode(i) == answeredQuestion.Letter) {
                        letter = String.fromCharCode(i);
                    }
                }
                var spanOfLetter = $('#' + letter);

                // If player's guessed word is correct, make span green and increase score
                if (inputWord === answeredQuestion.RightAnswer.toLowerCase()) {
                    answeredQuestion.IsCorrect = true;
                    spanOfLetter.addClass('correctLetter');
                    score++;
                }

                // Otherwise make span red
                else {
                    answeredQuestion.IsCorrect = false;
                    spanOfLetter.addClass('incorrectLetter');
                }

                // Continue game if there are questions left
                isGameOn();
            }

            // Skip to next question
            function pasapalabra() {

                // Push skipped question to the end of the array of questions
                var skippedQuestion = questions.splice(letterPosition, 1)[0];
                questions.push(skippedQuestion);

                // Continue game
                isGameOn();
            }

            // Display score result when game is over
            function gameOver() {
                gameOn = false;
                stopTimer();
                $('#score').html(score);
                $('#game').addClass('hidden');
                $('#finalGameScore').removeClass('hidden');
            }

            // Reload page if back to main page
            function backToMainPage() {
                window.location.reload();
            }

            // Starts countdown
            function startTimer() {

                // Timer at 3 minutes
                var minutes = 3;
                var seconds = 0;
                var timeLimit = minutes * 60 + seconds;

                timer = setInterval(function () {

                    // Countdown
                    timeLimit--;

                    // If timer reaches 0, game over
                    if (timeLimit <= 0) {
                        gameOver();
                    }

                    // Minutes display
                    minutes = Math.floor(timeLimit / 60);
                    if (minutes < 10) {
                        minutes = "0" + minutes;
                    }

                    // Seconds display
                    seconds = timeLimit % 60;
                    if (seconds <= 30) {
                        $("#timer").addClass("redTimer");
                    }
                    if (seconds < 10) {
                        seconds = "0" + seconds;
                    }

                    // Display timer on the browser
                    $("#timer").html(minutes + ":" + seconds);
                }, 1000);
            }

            // Stops countdown
            function stopTimer() {
                clearInterval(timer);
            }
        });

    </script>
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.