Flash CS3 - Flash CS4

Free tutorials and scripts for all.
Actionscript 3.0

Changing TextField text color on programmatic textfields

This is a discussion on Changing TextField text color on programmatic textfields within the Actionscript 3.0 newbies forums, part of the Flash CS3 eng category; I'm working with the following code (and learning to change the functionality in various ways). What I would like ...


Go Back   Forum Flash CS3 Flash CS4 > English Forums > Flash CS3 eng > Actionscript 3.0 newbies

Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 14-08-08, 04:16
Junior Member
 
Join Date: Jan 2008
Posts: 21
Rep Power: 0
Pherankh is on a distinguished road
Question Changing TextField text color on programmatic textfields

I'm working with the following code (and learning to change the functionality in various ways). What I would like to do is change the color of the text to 0xFF0000 on click if the correct answer is chosen, or change the text color to 0x0000FF if it happens to be an incorrect choice. I think this involves setting setTextFormat for the textfields, but first I am having trouble figuring out how to specify the textfields (which are the grandchildren of the Sprite named "answerSprites ":

Code:
/* This code is from "ActionScript 3.0 Game Programming University" by Gary Rosenzweig
Copyright 2007
http://flashgameu.com
See the book or site for more information */

/*
The plan for sprites is to have one gameSprite that contains everything. Inside of that,
we'll have a questionSprite that holds all the elements of a single quiz question: a text
field for the question and other sprites for the answers. The answerSprites will contain
the text fields and Circle movie clips for each answer, which will be stored in their own
sprites. We don't need a class variable to reference those, however, because they will be neatly stored in the answerSprites sprite.

There is also a reference for the GameButton, so that when we create a button, we can
use this reference to remove it
*/

package {
    import flash.display.*;
    import flash.text.*;
    import flash.events.*;
    import flash.net.URLLoader;
    import flash.net.URLRequest;

    public class TriviaGame extends MovieClip {

        // question data
        private var dataXML:XML;

        // text formats
        private var questionFormat:TextFormat;
        private var answerFormat:TextFormat;
        private var scoreFormat:TextFormat;

        // text fields
        private var messageField:TextField;
        private var questionField:TextField;
        private var scoreField:TextField;

        // sprites and objects
        private var gameSprite:Sprite;
        private var questionSprite:Sprite;
        private var answerSprites:Sprite;
        private var gameButton:GameButton;

        // game state variables
        private var questionNum:int;
        private var correctAnswer:String;
        private var numQuestionsAsked:int;
        private var numCorrect:int;
        private var answers:Array;

        public function startTriviaGame() {

            // create game sprite
            gameSprite = new Sprite();
            addChild(gameSprite);

            // set text formats
            questionFormat = new TextFormat("Arial",24,0x330000,true,false,false,null,null,"center");
            answerFormat = new TextFormat("Arial",18,0x330000,true,false,false,null,null,"left");
            scoreFormat = new TextFormat("Arial",18,0x330000,true,false,false,null,null,"center");

            // create score field and starting message text
            scoreField = createText("",questionFormat,gameSprite,0,360,550);
            messageField = createText("Loading Questions...",questionFormat,gameSprite,0,50,550);

            // set up game state and load questions
            questionNum = 0;
            numQuestionsAsked = 0;
            numCorrect = 0;
            showScore();
            xmlImport();
        }
        // start loading of questions
        public function xmlImport() {
            var xmlURL:URLRequest = new URLRequest("trivia1.xml");
            var xmlLoader:URLLoader = new URLLoader(xmlURL);
            xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
        }
        // questions loaded
        public function xmlLoaded(event:Event) {
            dataXML  = XML(event.target.data);
            gameSprite.removeChild(messageField);
            messageField = createText("Get ready for the first question!",questionFormat,gameSprite,0,60,550);
            showGameButton("GO!");
        }
        // creates a text field
        public function createText(text:String, tf:TextFormat, s:Sprite, x,y: Number, width:Number):TextField {
            var tField:TextField = new TextField();
            tField.x = x;
            tField.y = y;
            tField.width = width;
            tField.defaultTextFormat = tf;
            tField.selectable = false;
            tField.multiline = true;
            tField.wordWrap = true;
            if (tf.align == "left") {
                tField.autoSize = TextFieldAutoSize.LEFT;
            } else {
                tField.autoSize = TextFieldAutoSize.CENTER;
            }
            tField.text = text;
            s.addChild(tField);
            return tField;
        }
        // updates the score
        public function showScore() {
            scoreField.text = "Number of Questions: "+numQuestionsAsked+"   Number Correct: "+numCorrect;
        }
        // ask player if they are ready for next question
        public function showGameButton(buttonLabel:String) {
            gameButton = new GameButton();
            gameButton.label.text = buttonLabel;
            gameButton.x = 220;
            gameButton.y = 300;
            gameSprite.addChild(gameButton);
            gameButton.addEventListener(MouseEvent.CLICK,pressedGameButton);
        }
        // player is ready
        public function pressedGameButton(event:MouseEvent) {
            // clean up question
            if (questionSprite != null) {
                gameSprite.removeChild(questionSprite);
            }
            // remove button and message
            gameSprite.removeChild(gameButton);
            gameSprite.removeChild(messageField);

            // ask the next question
            if (questionNum >= dataXML.child("*").length()) {
                gotoAndStop("gameover");
            } else {
                askQuestion();
            }
        }
        // set up the question
        public function askQuestion() {
            // prepare new question sprite
            questionSprite = new Sprite();
            gameSprite.addChild(questionSprite);

            // create text field for question
            var question:String = dataXML.item[questionNum].question;
            questionField = createText(question,questionFormat,questionSprite,0,60,550);

            // create sprite for answers, get correct answer and shuffle all
            correctAnswer = dataXML.item[questionNum].answers.answer[0];
            answers = shuffleAnswers(dataXML.item[questionNum].answers);

            // put each answer into a new sprite with a circle icon
            answerSprites = new Sprite();
            for (var i:int=0; i<answers.length; i++) {
                var answer:String = answers[i];
                var answerSprite:Sprite = new Sprite();
                var letter:String = String.fromCharCode(65+i);// A-D
                var answerField:TextField = createText(answer,answerFormat,answerSprite,0,0,450);
                var circle:Circle = new Circle();// from Library
                circle.letter.text = letter;
                answerSprite.x = 100;
                answerSprite.y = 150+i*50;
                answerSprite.addChild(circle);
                answerSprite.addEventListener(MouseEvent.CLICK,clickAnswer);// make it a button
                answerSprite.buttonMode = true;
                answerSprites.addChild(answerSprite);
            }
            questionSprite.addChild(answerSprites);
        }

        // take all the answers and shuffle them into an array
        public function shuffleAnswers(answers:XMLList) {
            var shuffledAnswers:Array = new Array();
            while (answers.child("*").length() > 0) {
                var r:int = Math.floor(Math.random()*answers.child("*").length());
                shuffledAnswers.push(answers.answer[r]);
                delete answers.answer[r];
            }
            return shuffledAnswers;
        }
        // player selects an answer
        public function clickAnswer(event:MouseEvent) {

            // get selected answer text, and compare
            var selectedAnswer = event.currentTarget.getChildAt(0).text;
            if (selectedAnswer == correctAnswer) {
                numCorrect++;
                messageField = createText("You got it!",questionFormat,gameSprite,0,140,550);
            } else {
                messageField = createText("Incorrect! The correct answer was:",questionFormat,gameSprite,0,140,550);
            }
            finishQuestion();
        }
        public function finishQuestion() {
            // remove all but the correct answer
            for (var i:int=0; i<4; i++) {
                answerSprites.getChildAt(i).removeEventListener(MouseEvent.CLICK,clickAnswer);
                if (answers[i] != correctAnswer) {
                    answerSprites.getChildAt(i).visible = false;
                } else {
                    answerSprites.getChildAt(i).y = 200;
                }
            }

            // next question
            questionNum++;
            numQuestionsAsked++;
            showScore();
            showGameButton("Continue");
        }
        // clean up sprites
        public function cleanUp() {
            removeChild(gameSprite);
            gameSprite = null;
            questionSprite = null;
            answerSprites = null;
            dataXML = null;
        }
    }
}
It looks like finishQuestion() would be the easiest spot to modify, but I just can't figure out how to iterate through the grandchildren of answerSprites, filter on TextFields, and set the text color.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

  #2 (permalink)  
Old 16-08-08, 02:26
Junior Member
 
Join Date: Jan 2008
Posts: 21
Rep Power: 0
Pherankh is on a distinguished road
Re: Changing TextField text color on programmatic textfields

I've finally gotten closer to the goal. The changes to the code below will turn the answer text green on click, but I really need it to happen within finishQuestion() (note the comments) when it is decided if the clicked answer is correct or incorrect:

Code:
        public function clickAnswer(event:MouseEvent) {
            // get selected answer text, and compare
            var selectedAnswer=event.currentTarget.getChildAt(0).text;
            if (selectedAnswer == correctAnswer) {
                numCorrect++;
                messageField=createText("Correct!",questionFormat,gameSprite,0,140,550);
            } else {
                messageField=createText("Incorrect! The correct answer was:",questionFormat,gameSprite,0,140,550);
            }
            finishQuestion();
            processChildren(answerSprites);
        }

        public function processChildren(answerSprites:DisplayObjectContainer):void {
            var CorrectColor:TextFormat = new TextFormat;
            var IncorrectColor:TextFormat = new TextFormat;
            CorrectColor.color = 0x85BB3D;
            IncorrectColor.color = 0xCF7E05;
            for (var i:int=0; i < answerSprites.numChildren; i++) {
                var thisChild:DisplayObject=answerSprites.getChildAt(i);
                // Tracing at this level shows entire hierarchy
                //trace(thisChild);
                if (thisChild is DisplayObjectContainer) {
                    processChildren(DisplayObjectContainer(thisChild));
                    // Tracing at this level shows first child level
                    //trace(thisChild);
                } else {
                    // Tracing at this level shows grandchild level
                    //trace(thisChild);
                    if (thisChild is TextField && thisChild.name != "letter") {
                        var txtfield:TextField=thisChild  as  TextField;
                        trace("I am a TextField and my name is: " + txtfield.name);
                        txtfield.setTextFormat(CorrectColor);
                    }
                }
            }
        }

        public function finishQuestion() {
            // remove all but the correct answer
            for (var i:int=0; i < answerSprites.numChildren; i++) {
                answerSprites.getChildAt(i).removeEventListener(MouseEvent.CLICK,clickAnswer);

                // Disable answers on user click:
                var disableAnswer:Sprite=Sprite(answerSprites.getChildAt(i));
                disableAnswer.buttonMode=false;
                disableAnswer.useHandCursor=false;

                if (answers[i] != correctAnswer) {
                    //CHANGE THE TEXT COLOR TO IncorrectColor
                } else {
                    //CHANGE THE TEXT COLOR TO CorrectColor
                }
            }
            // next question
            questionNum++;
            numQuestionsAsked++;
            showScore();
            showGameButton("Continue");
        }
Any ideas how to rewrite this?
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Reply

Bookmarks

« code problem? | Air »
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

Similar Threads

Thread Thread Starter Forum Replies Last Post
Color.interpolateColor - create color transition Flep Tutorials 2 27-10-08 15:19
Actionscript 3 Tween color change for text field problem samohtwerdna advanced Actionscript 3.0 0 02-10-08 02:47
Actionscript 2 Trying to change the color of Dynamic text Dakart Flash CS3 eng 0 18-07-08 20:49
dynamicly positioning TextFields shed Actionscript 3.0 newbies 6 16-11-07 17:28
Change Text color alexyz4 Flash CS3 eng 4 31-10-07 08:28


All times are GMT. The time now is 21:11.


Powered by vBulletin versione 3.7.4
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.2.0 RC4
Forum SiteMap


FlepStudio
by Filippo Lughi
P.IVA 03605860406