Print Shortlink

GuessingGame logic in Sencha Touch 2.0

It’s fun writing OO code Sencha Touch 2.0. Ext.define is used to define clases and Ext.create for creating objects. Ext.define has it’s own set of rules to define properties, constructors, methods etc. Here is an example of the favourite Guessing Game class written in Sencha Touch 2.0. The GuessingGame class that has the core logic sans the UI is shown below:


Ext.define("GuessingGame",{
	config : {
		target : 0,
		attempts : 0,
		message : "",
		gameOver : false
	},
	constructor : function(config){
		this.initConfig(config);
		this.setTarget(Math.floor(Math.random()*101));
	},
	play : function(guess){
		var target = this.getTarget();
		var attempts = this.getAttempts();
		var message = "";
		attempts++;
		if(guess > target)
			message = "Aim Lower";
		if(guess < target)
			message = "Aim Higher";
		if(guess == target)
		{
			message = "You have got it!!!";
			this.setGameOver(true);
		}
		this.setMessage(message);
		this.setAttempts(attempts);
	}
});

You can create an object of the GuessingGame class like

	var game = Ext.create("GuessingGame");
	game.play(50);
	alert(game.getMessage());
	// continue playing the game

Leave a Reply