0
public class Hangman extends Sprite {
    private var textDisplay:TextField;

    private var phrase:String = "Recycled" 
    private var phrase:String = "Stamped"
    private var phrase:String = "grandpa"

"What I want to do here is to randomise the "phrase:String", so that the phrase outcome will be either recycled, stamped or grandpa.

    private var shown:String;
    private var numWrong:int;

    public function Hangman() {
        // create a copy of text with _ for each letter
        shown = phrase.replace(/[A-Za-z]/g,"_");
        numWrong = 0;

        ...codes*
    }

    public function pressKey(event:KeyboardEvent) {
        // get letter pressed
        var charPressed:String = (String.fromCharCode(event.charCode));

        // loop through nd find matching letters
        var foundLetter:Boolean = false;
        for(var i:int=0;i<phrase.length;i++) {
            if (phrase.charAt(i).toLowerCase() == charPressed) {
                // match found, change shown phrase
                shown = shown.substr(0,i)+phrase.substr(i,1)+shown.substr(i+1);
                foundLetter = true;
            }
        }

        // update on-screen text
        textDisplay.text = shown;

        // update hangman
        if (!foundLetter) {
            numWrong++;
            character.gotoAndStop(numWrong+1);
        }
    }
}

 }

I hope someone can help me on this one. Thank you.

1 Answer 1

1

You cannot have the same variable being instantiated with the same name... if you want, use an array to keep the possible words...

var phrase:Array = [ "Recycled", "Stamped", "grandpa", ...];

Then, use a Random function to select a number from 0, up to array size, then use that word...

var word = phrase[Math.floor(Math.random()*phrase.length)];
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your help! I did it, and the bracket should be squared bracket instead of curly bracket. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.