Number Guessing Game
Part 1: Setting up the Interface
Step 1: On your game page, rename the first layer to "interface"
Step 2: On your interface layer, create a game title
Step 3 – Creating a dynamic text field that will allow us to display messages to the viewer
Step 5 – Creating an input box where the user will enter their guess
Step 6 – Create buttons
function init():void {
//Display a begining message in the message_txt dynamic text field.
beginMessage="Welcome to my number guessing game. Please enter a number between 1 and 100.";
message_txt.text=beginMessage;
}
init();
______________________________
Step 7 - Making Sure the buttons work - Adding an Event Listener
guess_btn.addEventListener(MouseEvent.CLICK, yourGuess);
function yourGuess(event:MouseEvent): void{
trace("Your Guess Button Pressed");
}
Step 9 - Repeat for the New Game Button
______________________________
Step 10 - Enabling the Guess Button and Disabling the "Play Again" Button
function init():void {
....
....
// Initally disables the "play again" button, and enables the guess button
playagain_btn.enabled =false;
guess_btn.enabled = true;
}
Step 11 - Restricting the allowable input
// Restrict the input so that only numbers 0 - 9 can be entered into the input / guess box
input_txt.restrict="0-9";
// Clear the input text field
input_txt.text="";
Step 2: On your interface layer, create a game title
- Be sure that the title is created using static text.
Step 3 – Creating a dynamic text field that will allow us to display messages to the viewer
- After you have creating the dynamic text box and positioned it on the stage, be sure to give it an instance name. For example: message_txt
- Note the dotted line that appears around the text box you have created.
- Format the font and text size accordingly: Example: Arial size 18pt, aligned center
- In the timeline, create a new layer named "actions"
- In the action palette / window, enter the following code
//Declares variables
var beginMessage:String; //Display a beginning message in the message_txt dynamic text field. - Text the scene / project and check your message.
- If your text is a pile of gibberish of missing characters or unreadable symbols, you will likely need to embed the character font into the program.
- Press the embed button and embed the following character glyphs: Uppercase, lowercase, numerals and punctuation.
- Retest the scene / project and things should be ok.
beginMessage="Welcome to my number guessing game. Please enter a number between 1 and 100."; message_txt.text=beginMessage;
Step 5 – Creating an input box where the user will enter their guess
- Select the Text tool (T) with input text and drag an input text field below the dynamic text field. Make sure your input text field has enough room for five characters. Select the option ‘Show border around text’ which displays a black border around the input text field. If you don't do this, your text box will likely be invisible against your background.
- You might also want to set the paragraph behavior to 'single line' and changed the 'Max Char' to 5 which will prevent more than five characters appearing. (You might need to change this later if you have larger limits in your final game)
- Give your input text field the instance name: input_txt.
Step 6 – Create buttons
- Create two buttons on the stage below the input text field.
- One of the buttons should have the name “Guess” and the other with the name “Play Again”
- Give the buttons the following instance names respectively: guess_btn and playagain_btn
- In a few minutes we will test the buttons to make sure they work.
- Now that our interface is roughly done, lets get started on the game coding.
- When we first start the game, we have a set of things that we want to happen initially before the game begins.
- To get things started, underneath your variables declaration section add the following code
function init():void {
}
- Notice that right now there is nothing in it. So let's move our existing code into the function
function init():void {
//Display a begining message in the message_txt dynamic text field.
beginMessage="Welcome to my number guessing game. Please enter a number between 1 and 100.";
message_txt.text=beginMessage;
}
- When you run / test your program, you will see that our welcoming message no longer appears.
- This is because we have not yet run the init() function. We need to add a procedural or function call.
- Let's add one right below the init() function that we just created.
init();
- When you run your program / scene now, you will discover that our initial message is again displaying.
______________________________
Step 7 - Making Sure the buttons work - Adding an Event Listener
- First we need to add an event listener.
- Event listeners basically let specific code run whenever a certain event happens, such as you pressing a button, moving the mouse, or if you want to create an infinite loop to run your code over and over again (necessary for most games).
- Event listeners are essentially the ears of your program. You tell them what to listen for, and when they hear it they shout out to the rest of the program.
You create event listeners by typing: addEventListener and then specifying what type of event you are waiting for (mouse click, key press, etc) and what you want the program to do once it “hears” this event.
guess_btn.addEventListener(MouseEvent.CLICK, yourGuess);
- Let’s break it down:
guess_btn
tells the program what button to add the event listener to
- addEventListener()
tells the program we are creating an event handler. Whatever is inside the parentheses will describe what it does.
- MouseEvent
is the broad category of which type of events it is listening for. Another category we could use is “KeyboardEvent” (for pressing keyboard keys)
.CLICK
is the specific event we are listening for, within that broad category. In our case this will go off every time the user clicks their mouse. The period before CLICK is just part of the syntax.
- yourGuess
is the actual message the event listener will broadcast to the program. The comma before it is used to separate different parts of the code within parentheses. The program knows that everything before the first comma is the type of event it is listening for, and everything after the comma is what the program will do once the event happens. The name I chose “yourGuess” is actually the name of a function that this code will activate when the guess button is actually pressed
- Below all the code that we have already written, create a function called "yourGuess". All we want the function to do at this point is let us know that we have pressed the button.
function yourGuess(event:MouseEvent): void{
trace("Your Guess Button Pressed");
}
Step 9 - Repeat for the New Game Button
______________________________
Step 10 - Enabling the Guess Button and Disabling the "Play Again" Button
- When we start each game, we want to make sure that the user has to play the game to the end before they press the button to "Play Again". So... we want to inactivate the button temporarily
- Underneath your variables declaration section add the following code to our existing code (note the .... represent the other code that we already have in the init() function
function init():void {
....
....
// Initally disables the "play again" button, and enables the guess button
playagain_btn.enabled =false;
guess_btn.enabled = true;
}
- When you run / test your program, you will see that when you pass over the "Play Again" button, the browser hand is no longer visible.
- Unfortunately, when you press the "Play Again" button, our trace message about the button being pressed still appears. This is because the eventListener for the button is still active.
- So how can we fix this a couple of ways:
- simply remove the eventListenter temporarily by changing the word "add" to "remove
playagain_btn.removeEventListener(MouseEvent.CLICK, playAgain); - Change the text message to say something like: "Please finish this game before starting a new game"
Step 11 - Restricting the allowable input
- The guess entered by the user can only be numbers that contain the digits 0 - 9
- Test or run your program and see what happens when you press different keys on the keyboard.
- You should notice that any character (letter, symbol, or number) can be pressed. You should also note that you aren't able to enter more than five characters without pressing the delete or backspace key to change your input.
- Solution: We need to prompt the program to ignore any other characters (letters or symbols) that the user might type into the "input_txt" box.
- Enter the following code within the init() function after the code that we have previously entered.
// Restrict the input so that only numbers 0 - 9 can be entered into the input / guess box
input_txt.restrict="0-9";
- We also want to make sure that when a game starts for the first time or that a new game is started that any text in the "input.txt" box is cleared automatically.
- To see what I mean, in your Flash Program, type "Hello World" into the input.txt box and then test your program.
- You will notice that the message appears in the text input box. Strange that it accepts more than 5 characters until you try to change the text in the box.
- Enter the following code within the init() function after the code that we have previously entered.
// Clear the input text field
input_txt.text="";
- Test or run your program and you will see that the message "Hello World" is no longer displayed.
- You are probably asking... what is the big deal. Why not leave the text box blank to begin with.
- Hmmm... easy explanation. From my point of view, I normally type text in the box so that I can set the text attributes such as font size, font face, colour, and emphasis. IF I don't do this initially, sometimes I have had the unfortunate situation where I think the text box is working properly. When in reality my text is either white so it is actually invisible, or so large that it just won't fit in the text box I have created on the screen.
- So my fix... enter "Hello World" so I can see what the font would look like, and then in the init() function clear my text
Part 2: Getting the Game Started
Step 1 - Having the computer generate the number that the user will be guessing
var beginMessage:String;
var number:uint;
number = Math.floor(Math.random()*100 + 1);
trace("The number is:",number);
Step 2 - Getting the User's Guess
guess = uint(input_txt.text);
trace("Your guess is: ", guess);
______________________________
Step 3 - Having messages appear in the message box instead of using trace commands
Step 4 - Evaluating the Player's Guess and Providing the user with hints for their next guess
- Before we get started, we need to declare a variable that will store the value of the number generated by the computer
- In the variable declaration section at the top of your action script, add the following variable
var beginMessage:String;
var number:uint;
- Please notice the spelling of uint, it is not "unit"
- In our init() function we need to add the following code that will generate the number:
number = Math.floor(Math.random()*100 + 1);
trace("The number is:",number);
- The trace seems odd, but we initially need to have the computer display the number that the user is trying to guess.
- We do this so that we can know what the number is while we are testing the program out. How else would we know if the too low, too high, or guessed correctly?
- Once we know the program hints are working properly, we can then remove the trace so that it is not visible while the game is being played. All we have to do is comment it out by putting // right before it
// trace("The number is:",number);
Step 2 - Getting the User's Guess
- Now that we know the number the user is trying to guess, we need to get the user's actual guess
- Assuming that the user has entered a number into the input box, we need the user to press the "Guess" button. You might want to change your prompt.
- Once the "Guess" button is pressed, we need the computer to take the data that has been entered in the input text box and convert it into an integer value that is then stored as a variable.
- In the yourGuess() function, enter the following code. Note that I have chosen to name my new variable "guess" and that I declared it in my variable section (you should know how to create or declare a variable by now.... hint: just like the random number we did in step 1)
guess = uint(input_txt.text);
trace("Your guess is: ", guess);
- I did a trace command to make sure that the variable is being read by the computer and stored properly. Once I know it is working properly, I will comment it out.
- Test your program and see what happens when you enter a few guesses and press the the "Guess" button each time.
______________________________
Step 3 - Having messages appear in the message box instead of using trace commands
- We have been using the trace function up to this point in time to communicate if something like a button is working or to display additional information to the user such as what the random number is.
- It is time to start making use of that message text box we created.
- To see what I mean, let's get rid of the that trace that we used to make sure the computer was getting our guess and replace it with something like this:
message_txt.text ="Your guess of " +guess +" is totally amazing!" ; - Test the program, enter a guess, press the guess button and you will see the message that displays your number.
- Sometimes, we don't want to replace the text that was already in the box. We simply want to add to it. Both of the following methods would work:
message_txt.appendText ("Thanks. ");
message_txt.text += "Lots more to say! Stay Tuned!";
- Add both lines to your code and see what happens.
- Wow...all that text appears on one long line
Your guess of 15 is totally amazing! Thanks. Lots more to say! Stay Tuned! - If you want to move things to a new line, you need to make use of the escape sequence \n
- For instance, the following code:
message_txt.text ="Your guess of " +guess +" is totally amazing! " ;
message_txt.appendText ("Thanks. ");
message_txt.text += "\nLots more to say! \n\nStay Tuned!";
Produces the following output in the display:
Your guess of 15 is totally amazing! Thanks.
Lots more to say!
Stay Tuned!
Step 4 - Evaluating the Player's Guess and Providing the user with hints for their next guess
- In this step, you will need to compare the user's guess to the actual number generated by the computer and provide appropriate hints to guide their next guess.
- For instance if the computer's number was 15, and the user guessed 5, you might offer a message such as:
"Your guess of 5 was too small. Please try again." - If the user then offered a guess of 25, you might offer a message such as:
"Your guess of 25 was too big. Please try again." - Don't forget about displaying a message if the they guess the correct number.
- Make uses of traces or the text box as you go to make sure everything is working.
- The inequalities you can make use of include:
> greater than
< less than
>= greater than or equal to
<= less than or equal to
== equal to
(Be careful that you don't just use one = sign. This changes the value or the assignment of the variable rather than testing for equality)
- I am going to leave you alone for this part, other than to offer you a brief explanation of if..else statements. Good Luck!
if..else statements
The structure of a basic if statement is as follows:
if (condition)
{
statement;
statement;
}
if (condition)
{
statement;
statement;
}
Examples:
if (number > 7) trace ("Bigger than 7 sends you to heaven"); if (age >= 16) { trace ("You are old enough to drive."); trace ("I sure hope you will be a safe driver!"); } |
Sometimes, we want something to happen only if multiple conditions hold true
if ((mark > 73) && (mark < 86)) trace ("Assigned letter grade is a B"); Sometimes, we want to have something happen under totally different conditions (In other words, if any one of the conditions is true) if ((age < 13) || (age > 19)) { trace ("Who are you trying to fool"); trace ("You definitely aren't a teenager); } |
The structure of a basic if..else statement is as follows:
if (condition) { statement; statement; } else { statement; statement; } |
Example:
if (age >=16) trace ("You are old enough to drive!"); else { trace ("Lucky for us... you will have to wait a while!"); trace (16 - age, "years of safety ahead of us!"); } |
Part 3: Yeah... Victory. They finally guessed the number!
- Yeah victory. I am going to assume that all of your high/low hints are finally working correctly and that we can consider what to do when the user or player finally guesses the correct number.
- Yes... we congratulated them, but now we want to give them the option to play another game or round.
- If you recall, way back in Step 10 or part 1, we disabled the "Play Again" button. Time to put it back in play.
- I could tell you step by step what to do, but it is time to let you try to work it through on you your own.
- To make sure you are moving in the right direction, here are a few things you should probably do.
|
At this point, your game should look something like this: Be Warned... Mine looks kind of rough and ugly. That should inspire you to use your flash skills to make your interface look a whole lot appealing.
Part 4: Where to go from here! Count the Guesses
- Create the code that would keep track of how many guesses the user has made and at the end of the game congratulates the player for not only guessing the number, but also tells them how many tries it took.
- Make uses of traces or the message text box as you go to make sure everything is working. Don't leave yourself blind as to what is going on.
- To increase or increment a variable by 1, do one of the following, they mean the same thing:
donuts = donuts + 1;
donuts += 1;
donuts++
- To increase or increment a variable by a value other than 1, do one of the following, they mean the same thing:
donuts = donuts +5;
donuts += 5;
At this point, your game should look something like this: Once again be warned... Mine still looks ugly. Yours should look way more fun and entertaining.
Part 5: Limiting the maximum number of guesses allowed
- Your task is to try limiting the maximum number of guesses in the game.
- You should display a message (or use a text box) to display the number of guesses left.
- If the correct answer is guessed, or the number of guesses is used up then an appropriate message should be displayed to the player. For example:
Congrutations! You took 5 guesses to figure out that the number was 83.
Sorry! But you ran out of guesses before you figured out the number was 83. Better luck next time. - Make uses of traces or the message text box as you go to make sure everything is working. Don't leave yourself blind as to what is going on.
- What you have so far, might be something like this.
Part 6: Be creative and complicate things more
- When the user enters the number, what happens when the number entered is totally out of range? (For example, enter a number between 1 and 100 and the user enters 105)
- Levels of complexity by changing the range of numbers (1 - 100), (1 -1000)
- Levels of complexity by changing the maximum number of allowed guesses
- Independence where user chooses the minimum and maximum values of the range and the total of allowed guesses
- Having a special screen or frame that displays when the user wins (fireworks) or when they lose (sad face)
- Rather than just "Play Again" button, you could have a button to end the session. If this is the case. Don't forget to say thanks and goodbye to your player.
- ???????