Fill in the Blank

Actionscript:
  1. var story:String = "Fill in the _____.";
  2.  
  3.  
  4. var txt:TextField = new TextField();
  5. txt.defaultTextFormat = new TextFormat("Georgia", 20);
  6. txt.width = stage.stageWidth;
  7. txt.multiline = true;
  8. txt.wordWrap = true;
  9. txt.text = story;
  10. addChild(txt);
  11.  
  12. var alph:Array = "abcdefghijklmnopqrstuvwxyz".split("");
  13. var keys:Object = {};
  14. for (var i:int = 0; i<alph.length; i++){
  15.     keys[65 + i] = alph[i];
  16. }
  17. stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
  18. function onKeyPressed(evt:KeyboardEvent):void{
  19.      
  20.     if (evt.keyCode == Keyboard.ENTER){
  21.         story = "Fill in the _____.";
  22.         txt.text = story;
  23.     }
  24.    
  25.     for (var i:int = 0; i<story.length; i++){
  26.         if (story.charAt(i) == "_"){
  27.             var head:String = story.substr(0, i);
  28.             var tail:String = story.substr(i + 1);
  29.             var letter:String = keys[evt.keyCode];
  30.             if (!letter) return;
  31.             story = head + letter + tail;
  32.            
  33.             txt.text = story;
  34.            
  35.             break;
  36.         }
  37.     }
  38. }

I needed to do a fill in the blank for a personal project that I'm working on and this is what I came up with. Have a look at the swf here:

(you need to click first so you can type with the keyboard):
Fill in the blank

This entry was posted in TextField, UI and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. Posted June 4, 2010 at 8:10 am | Permalink

    Oh nice, it could be so useful :). Thank to share!

  2. Posted June 4, 2010 at 8:19 am | Permalink

    no problem, glad you like it.

  3. Shawn
    Posted June 4, 2010 at 9:43 am | Permalink

    Awesome. I’ve been looking for a good way to do this.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*