Print Shortlink

GuessingGame using KnockOut and jQuery

Back to bread and butter :), Guessing Game. This time using KnockOut.js and jQuery. The screen shots for the Guessing Game can be found in one of my earlier posts. You can read the introductory post about KnockOut.js here.

The Game.js contains the game JSON object with the logic to play the game.

//Game.js
var game = {
    target: Math.floor((Math.random() * 101)),
    attempts: 0,
    message: "",
    gameOver: false,
    play: function (guess) {
        this.attempts++;
        if (guess > this.target)
            this.message = "Aim lower";
        else if (guess < this.target)
            this.message = "Aim higher";
        else {
            this.message = "You have got it!!!";
            this.gameOver = true;
        }
    },
    reinitialize: function () {
        this.target = Math.floor((Math.random() * 101));
        this.attempts = 0;
        this.message = "";
        this.gameOver = false;
    }
};

The GameViewModel.js created using KnockOut is shown below.

//GameViewModel.js
var gameViewModel = {
    guess: ko.observable("0"),
    message: ko.observable(""),
    attempts: ko.observable(""),
    reinitialize: function () {
        this.message("");
        this.attempts("");
        this.guess("0");
    },
    play: function () {
        game.play(this.guess());
        this.message(game.message);
        this.attempts("Attempts: " + game.attempts);
        if (game.gameOver) {
            var playAgain = window.confirm("Do you want to play again?");
            if (playAgain) {
                game.reinitialize();
                this.reinitialize();
            }
            else
                window.close();
        }
    }
};

And the guessingGame.html file that contains the UI and the scripts included. It also contains the code for binding the view model.

<!DOCTYPE html>
<html>
<head>
    <script src="jquery-1.7.2.js"></script>
    <script src="knockout-2.1.0.js"></script>
    <script src="Game.js"></script>
    <script src="GameViewModel.js"></script>
    <script>
        $().ready(function () {
            ko.applyBindings(gameViewModel);
        });
    </script>
</head>
<body>  
    <h1>Welcome to the Guessing game.</h1>
    Enter your guess <input type="text" id="guessText" data-bind="value:guess"/>
    <input type="button" value="Guess" id="guessBtn" data-bind="click:play"/>
    <h1 id="attemptsH1" data-bind="text:attempts"></h1>
    <h1 id="messageH1" data-bind="text:message"></h1>
</body>
</html>

Leave a Reply