My quick and dirty attemp at this reddit daily programming challenge
http://www.reddit.com/r/dailyprogrammer/comments/pii6j/difficult_challenge_1/
It has a bug or two but gets the job done.
/**
* Copyright IStillLikeFlash ( http://wonderfl.net/user/IStillLikeFlash )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/68af
*/
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;
import com.bit101.components.HBox;
import com.bit101.components.Label;
import com.bit101.components.PushButton;
import com.bit101.components.VBox;
public class GuessMyNumber extends Sprite {
private var container:VBox;
private var guessLabel:Label;
private var optionsContainer:HBox;
private var numberOfGuesses:int = 0;
private var guess:int = 0;
private var min:int = 1;
private var max:int = 100;
public function GuessMyNumber() {
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function addedToStageHandler(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
container = new VBox();
addChild(container);
var title:Label = new Label(container);
title.text = "Choose a number between 1 and 100 and I will try to guess it";
var ready:PushButton = new PushButton(container);
ready.label = "Ready";
ready.addEventListener(MouseEvent.CLICK, readyClickHandler);
}
private function readyClickHandler(event:MouseEvent):void
{
var button:PushButton = PushButton(event.currentTarget);
button.removeEventListener(MouseEvent.CLICK, readyClickHandler);
container.removeChild(button);
guessLabel = new Label(container);
addOptions();
makeGuess();
}
private function addOptions():void
{
optionsContainer = new HBox(container);
var yes:PushButton = new PushButton(optionsContainer);
yes.label = "yes";
yes.addEventListener(MouseEvent.CLICK, yesClickHandler);
var higher:PushButton = new PushButton(optionsContainer);
higher.label = "higher";
higher.addEventListener(MouseEvent.CLICK, higherClickHandler);
var lower:PushButton = new PushButton(optionsContainer);
lower.label = "lower";
lower.addEventListener(MouseEvent.CLICK, lowerClickHandler);
}
private function yesClickHandler(event:MouseEvent):void
{
guessLabel.text = "I found your number in " + numberOfGuesses.toString() + " guesses";
container.removeChild(optionsContainer);
}
private function higherClickHandler(event:MouseEvent):void
{
min = guess + 1;
makeGuess();
}
private function lowerClickHandler(event:MouseEvent):void
{
max = guess - 1;
makeGuess();
}
private function makeGuess():void
{
numberOfGuesses++;
guess = ((max + min) / 2);
guessLabel.text = "Is your number " + guess.toString();
}
}
}