I have a set of examples that I always love to implement whenever I learn a new framework/language/technology. One of them is a Guessing Game. The application will generate a random number between 1 and 100. The user will play the game till he guesses the number correct. The screenshots for the game looks like below:
The UI of the application present inside the body tag is given below.
<body> <h1>Welcome to the guessing game. Enter a number between 1 and 100.</h1> <p> Enter your guess <input type="text" id="guessTB"> <br/> <input type="button" value="Guess" id="guessBTN"> <br/> <h3 id="messageH3"></h3> <h3 id="attemptsH3"></h3> </p> </body>
Let’s implement this game using Backbone.js. In my earlier post on Backbone I had discussed the basics of model, collection and view. We’ll use them to implement the guessing game.
Let’s define a model called GuessingGame with target, attempts and message attributes. ‘target’ attributes will get initialized to a random number between 1 and 100. The GuessingGame model will have a play method that has the core logic of the application. The GuessingGame model is shown below.
var GuessingGame = Backbone.Model.extend({ defaults : { target : 0, attempts : 0, message : null }, initialize : function(){ var target = Math.floor(Math.random()*100); this.set({"target":target}); }, play : function(guess){ var target = this.get("target"); var attempts = this.get("attempts"); var message = null; attempts++; if(guess > target) message = "Aim Lower"; if(guess < target) message = "Aim Higher"; if(guess == target) message = "You have got it!!!"; this.set({"message":message}); this.set({"attempts":attempts}); } });
In the document load function let’s create an instance of GuessingGame model. You’ll also create a View ‘GameView’. The GameView will have the event handler for the button click event. The onload function with the above logic is shown below:
$(function(){ var game1 = new GuessingGame(); var GameView = Backbone.View.extend({ el : $("body"), events : { "click #guessBTN" : "play" }, play : function(){ game1.play(parseInt($("#guessTB").val())); $("#messageH3").html(game1.get("message")); $("#attemptsH3").html("Attempts: " + game1.get("attempts")); } }); var gameView = new GameView(); });
There we go!!! I have not done things like validations etc., to keep it simple. GuessingGame is a kind of application that gives you the confidence to proceed to the next level of learning a new tool.
[…] 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 […]