beginning game programming with flash chapter 8

Upload: vietk52

Post on 30-May-2018

234 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    1/21

    This page intentionally left blank

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    2/21

    High Scores Game

    n Use a SharedObject

    n Use arrays

    n Use a timer

    What Is a SharedObject?The SharedObject class available in the Flash environment is used to store small

    amounts of data on the client machine. It is very similar to a cookie, which is set

    on your local machine and whose value can be retrieved at a later time. The

    SharedObject is one way to have persistent data, which means the value saved inthis object continues to be accessible even after the program is closed, unlike

    variables in a program whose value is alive only as long as the program is open.

    Uses of a SharedObject

    There are many uses for a SharedObject. Some of these uses are:

    n A SharedObject can be used as a cookie to store data on the local machine.

    This data that is saved is accessible only to that single machine.

    n A SharedObject can be used to save data on a server. This data can be seen

    by many clients at one time. An example is a high-scores game where

    163

    chapter 8

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    3/21

    you can see the scores of different people and compare your score to their

    scores.

    n A SharedObject can be used to provide real-time data sharing among many

    clients. An example is where all the airline reservation agents can see thesame number of seats available for any given flight, and once a ticket is

    booked everybody has the updated data reflecting the total available seats.

    Limitations of the SharedObject include the following:

    n Sometimes .swf files are not allowed to write data to local SharedObjects.

    n Sometimes the local SharedObject may be deleted without your knowledge.

    For more information on SharedObjects, visit Adobe livedocs at http://livedocs.

    adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.html.

    In this chapter, we will only be looking at the first type of use, which is to savedata on your local machine. We will design a high scores game to show a

    SharedObject in action.

    E x e r c i s e 8 . 1

    Story LineThe main theme of this game is to mimic a high score feature, which is common in games. Thegame keeps track of scores of 10 individuals playing on the same machine. The scores are rankedfrom highest to lowest. The game requires that the player be able to click on an object thatappears at random places. The goal is for the player to click on the object as many times aspossible within 20 seconds. The number of clicks is saved in the SharedObject and is displayed thenext time the player opens the game.

    Storyboard

    This phase includes the logical flow of your game depicted pictorially. Figure 8.1 shows this

    process.

    Game Assets

    The graphics you need for this game are all going to be button symbols. You will need a Startbutton, an object (also a button type) that will be placed randomly at different positions, a ClearScores button, and a Play Again button. Use your imagination and create the three buttons (Start,Clear All, and Play Again). For the object, create a button with a fancy shape, such as a teddybear, a rabbit, an orange, or whatever you fancy. In this game, a dog biscuit will be used as theclickable object. Make sure you choose button type for these game assets when you create thenew symbols.

    164 Chapter 8 n High Scores Game

    http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.htmlhttp://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.htmlhttp://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.htmlhttp://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.html
  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    4/21

    What Is a SharedObject? 165

    Figure 8.1Storyboard flowchart.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    5/21

    Code Used in the Game

    This section presents the objects and code to be inserted in various layers and frames used in thegame. The code required for the game will be included in two frames, frame 1 and frame 2.

    Activity for Frame 1: Creating the Instructions Scene1. Create a new Flash document.

    2. Import (to the library) a few graphics you would like to use in the game. This book andthe accompanying CD have used graphics for a garden, a puppy, and a dog biscuit. Ofcourse, if you are creative, you can instead draw your own graphics in Photoshop or Flash.

    3. Select frame 1 and click on the stage.

    4. Choose any color you like for the background. You can also import any image to the libraryand use that as a background, as was done in this game. An image of a garden wasimported and then used as a background. See Figure 8.2.

    5. Use the Text tool and choose any font style that you like and type the following text to bedisplayed to the user. (Please note that you can customize the text to follow the themeof your game. In the figures provided, the game is themed around a puppy collecting treats.)

    Instructions:

    The goal of this game is to click on as many randomly appearing dog bones

    as you can in 20 seconds.

    The top 10 high scores will be displayed.

    6. Create a button of any shape. See Figure 8.3 for a sample. In keeping with the puppy theme,call the button btn_Fetch and type the word Fetch. Draw or import an image of apuppy paw. This is a fancy button, in that it has different colors for different states(you saw how to assign different colors to different states of a button in Chapter 2).The different colors for different states are intended just to create some visual effects.If you like to keep it simple, you neednt use different colors for different states.

    7. Drag the Text tool and draw a static text box. Type Please name your dog:.

    8. Drag the Text tool and draw a text box on the stage. Change the type of the text boxto Dynamic. Name this instance playerName_txt. Your screen should be similarto Figure 8.4.

    Code for the Instructions Scene

    Click on frame 1 and type the following code:

    stop();

    var pNam:String;

    enter_btn.addEventListener(MouseEvent.CLICK, enterGame);

    166 Chapter 8 n High Scores Game

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    6/21

    What Is a SharedObject? 167

    function enterGame(evt:MouseEvent) {

    pNam = playerName_txt.text;

    if (playerName_txt.text !="" && playerName_txt.text!="Enter Your Name") {

    nextFrame();

    } else {

    playerName_txt.text = "Enter Your Name";

    }

    }

    Layer 1, Frame 1

    These files were imported to thelibrary and then dragged onto thestage. All three will make up the

    background for the game.

    If you dont want to make acustom background, thats OK.

    You can still set up a defaultcolor as your background here.

    Figure 8.2Puppy game background.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    7/21

    168 Chapter 8 n High Scores Game

    Explanation of the Code

    This code has the usual stop() function. Next, the variable pNam is created to capture the value ofthe text typed into the dynamic text box playerName_txt when the player clicks on the Startbutton. An event listener is added to the Start button to recognize the mouse click event. Themouse click event then calls the function enterGame. The enterGame function assigns the value ofthe text in playerName_txt to the variable pNam. This function also checks to see if player-Name_txt is not equal to an empty string and does not contain the string Please name yourdog:. If the player entered a satisfactory name, the player is directed to frame 2. If not, a box

    displays the string Please name your dog: to alert the player to type a name for the puppy.

    Activity for Frame 2: Creating the Game Pieces Scene

    See Figure 8.5 before you start creating this scene so you have an idea of the stage layout.

    This frame is the actual frame where the game will be played. This frame also displays the score atthe end of the game.

    1. Click on frame 2 and insert a keyframe.

    2. Delete the text boxes and button from frame 1. In the puppy game, the picture of the puppy

    and the dog bone were also removed. These images were then replaced with a new image

    As you can see, this isthe buttons work area.

    This is the Up state for thisbutton. The Over image andthe Down image have minor

    differences from this one.

    Buttons have four states: Up,Over, Down, and Hit. Add akeyframe if you want to addan image to a button frame.

    These three imageswere imported andused in this button.

    Figure 8.3The Start button.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    8/21

    of a puppy and three instances of a bone pile. Again, these dont affect the game. They are just there to make the game more interesting.

    3. Drag the Text tool and draw a static text box. Type Go Fetch.

    4. Drag the Text tool and draw a dynamic text box. Give it the instance name pName_txt. SeeFigure 8.6.

    5. Drag the Text tool and draw a static text box. Type Score.

    6. Drag the Text tool and draw a dynamic text box. Give it the instance name pScore_txt.See Figure 8.7.

    7. Drag the Text tool and draw a static text box. Type Time.

    What Is a SharedObject? 169

    The instance name of

    the input text box is

    playerName_txt.

    Static text

    Static text Input text

    Figure 8.4Frame 1 completed.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    9/21

    8. Drag the Text tool and draw a dynamic text box. Give it the instance name pTime_txt. SeeFigure 8.8.

    9. Now we want to create two buttons for frame 2. Create a button called btn_Againand another button called btn_Clear. Use any shape you like for these buttons, or use thepreviously imported images from the library.

    10. The btn_Again button should include a text box with the text Fetch Again! in it.

    11. The btn_Clear button should include a text box with the text Clear Scores! in it.

    170 Chapter 8 n High Scores Game

    Frame 2

    The players name, the score,

    and the time remaining will be

    displayed in these text boxes.

    Place the two buttons down

    here so that they dont interferewith the game or the high score list.

    The right half of the stage is

    reserved for the high score list.

    As you can see a white semi-

    opaque box has been added inthe background so that the

    text is easier to read.

    The game is

    played in the lefthalf of the stage.

    Make sure that

    this area isnt too

    cluttered in yourgame.

    Figure 8.5Frame 2 layout.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    10/21

    12. Drag an instance of the btn_Again button to the stage. Give it the instance name pa_btn.See Figure 8.9.

    13. Drag an instance of the btn_Clear button to the stage. Give it the instance name cls_btn.See Figure 8.10.

    14. The last set of text boxes to be drawn on the stage will show the scores for the last10 players with their names. Drag the Text tool and draw a static text box and type PlayerName in it.

    What Is a SharedObject? 171

    The dynamic text

    boxs instancename is pName_txt.

    These are new background

    images. They only are used tomake frame 2 appear differently

    from frame 1. Its not necessary

    to do this if you dont want to.

    Frame 2

    Dynamictext box

    The players name will appear in

    the dynamic text box when

    the game is played.

    As you can see, this

    game imported two newimages, which were dragged

    to the stage in this frame.

    Static

    text box

    Figure 8.6

    Dynamic text box for Puppy Name.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    11/21

    15. Drag the Text tool and draw a static text box and type Score in it. See Figure 8.11.

    16. The next set of text boxes are the dynamic text boxes to display the names and scoresof the players. Drag the Text tool and draw a dynamic text box below the Name static textbox. Give it the instance name pn0.

    17. Repeat step 16 nine more times each time incrementing the instance name numberby 1. The last text box you add will have pn9 for its instance name. You will now havecreated a total of 10 dynamic text boxes for names. See Figure 8.12.

    18. Drag the Text tool and draw a dynamic text box below the Score static text box. Give it theinstance name ps0.

    19. Repeat step 18 nine more times. The last text box you add will have ps9 for itsinstance name. You will now have created a total of 10 dynamic text boxes for scores.See Figure 8.13.

    172 Chapter 8 n High Scores Game

    The dynamic text boxs instancename is pScore_txt.

    Statictext box

    Dynamic

    text box

    Figure 8.7Score.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    12/21

    20. Select Insert, New Symbol. This symbol is going to be the game piece that will be clicked onduring the game. Name this symbol btn_Bone and make sure it is of type Button.

    21. Draw some kind of object resembling a bone or a dog biscuit.

    22. Return to Scene 1 and drag one instance of btn_Bone to somewhere on the left half of thestage.

    23. Name this Instance scr_btn. See Figure 8.14. The caption for Figure 8.14 is The TargetObject because this is the target that should be clicked on to increment the score.

    Code for Frame 2 Click on Actions for frame 2 and type the following code:

    var score:Number=0;

    var rec_array:Array = new Array();

    var myTimer:Timer = new Timer(1000);

    What Is a SharedObject? 173

    The dynamic text boxs instance

    name is pTime_txt.

    Statictext box

    Dynamic

    text box

    Figure 8.8Time.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    13/21

    myTimer.addEventListener("timer", timedFunction);

    myTimer.start();

    pa_btn.visible = false;

    cls_btn.visible = false;

    pName_txt.text = pNam;

    cls_btn.addEventListener(MouseEvent.CLICK, clearScores);

    174 Chapter 8 n High Scores Game

    pa_btn btn_Again makes use ofthese three files. You can either

    import images to use in the button

    or draw your own images in Flash.

    Instance of

    btn_Again

    Frame 2

    Figure 8.9The Play Again button.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    14/21

    function clearScores(evt:MouseEvent):void {

    jso2.clear();

    gotoAndStop(1);

    }

    pa_btn.addEventListener(MouseEvent.CLICK, restart);

    function restart(evt:MouseEvent):void {

    myTimer.start();

    What Is a SharedObject? 175

    cls_btn is the instance

    name of the btn_Clear button.

    Instance of

    btn_Clear

    Figure 8.10The Clear Scores button.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    15/21

    scr_btn.addEventListener(MouseEvent.CLICK, incScr);

    pa_btn.visible = false;cls_btn.visible = false;

    }

    scr_btn.addEventListener(MouseEvent.CLICK, incScr);

    function incScr(evt:MouseEvent):void {

    scr_btn.x = 50+(Math.random()*200);

    scr_btn.y = 100+(Math.random()*200);

    pScore_txt.text = String(score++);

    }

    var jso2:SharedObject = SharedObject.getLocal("hsr");

    if (jso2.data.scrz!=null) {

    rec_array = jso2.data.scrz;

    }

    function hs2() {

    176 Chapter 8 n High Scores Game

    Static text boxes

    Figure 8.11Player name and score.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    16/21

    rec_array.push({pN: pName_txt.text, pS: Number(pScore_txt.text)});

    jso2.data.scrz = rec_array;jso2.flush();rec_array.sortOn("pS", Array.DESCENDING | Array.NUMERIC);

    if ( rec_array[0]!=null) {pn0.text = rec_array[0].pN;ps0.text = rec_array[0].pS;

    }if ( rec_array[1]!=null) {

    pn1.text = rec_array[1].pN;

    What Is a SharedObject? 177

    The final text box will have

    the instance name pn9.

    10 dynamic

    text boxes

    pn0

    pn2

    pn6

    pn4

    pn8

    pn1

    pn3

    pn7

    pn5

    pn9

    Figure 8.12Name list.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    17/21

    ps1.text = rec_array[1].pS;

    }

    if ( rec_array[2]!=null) {

    pn2.text = rec_array[2].pN;

    ps2.text = rec_array[2].pS;

    }

    if ( rec_array[3]!=null) {

    pn3.text = rec_array[3].pN;

    ps3.text = rec_array[3].pS;

    }

    if ( rec_array[4]!=null) {

    pn4.text = rec_array[4].pN;

    ps4.text = rec_array[4].pS;

    178 Chapter 8 n High Scores Game

    The final dynamic text box

    will have the instance name ps9.

    10 more dynamic

    text boxes

    ps0

    ps2

    ps6

    ps4

    ps8

    ps1

    ps3

    ps7

    ps5

    ps9

    Figure 8.13The score list.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    18/21

    }

    if ( rec_array[5]!=null) {

    pn5.text = rec_array[5].pN;

    ps5.text = rec_array[5].pS;

    }

    if ( rec_array[6]!=null) {

    pn6.text = rec_array[6].pN;

    ps6.text = rec_array[6].pS;

    }

    if ( rec_array[7]!=null) {

    What Is a SharedObject? 179

    Adjust the instances,

    opacity by resetingtheir Alpha property.

    Two instances

    of filters

    Move the filters

    behind the text byselecting Send Backward.

    New symbol filter

    of type graphic

    Figure 8.14The target object.

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    19/21

    pn7.text = rec_array[7].pN;

    ps7.text = rec_array[7].pS;

    }if ( rec_array[8]!=null) {

    pn8.text = rec_array[7].pN;

    ps8.text = rec_array[8].pS;

    }

    if ( rec_array[9]!=null) {

    pn9.text = rec_array[9].pN;

    ps9.text = rec_array[9].pS;

    }

    180 Chapter 8 n High Scores Game

    This is an instance ofbtn_Object. The puppy game

    refers to it as btn_Bone.

    Its instance namemust be scr_btn.

    The btn_Bone button wascreated using the dogbone.png image.

    You can import your own image or

    create a new image in Flash.

    Figure 8.15

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    20/21

    }

    function timedFunction(eventArgs:TimerEvent) {

    var tc:int= 31 - myTimer.currentCount;

    pTime_txt.text = tc.toString();if (myTimer.currentCount >30) {

    scr_btn.removeEventListener(MouseEvent.CLICK, incScr);

    myTimer.reset();

    myTimer.stop();

    hs2();

    pa_btn.visible = true;

    cls_btn.visible = true;

    score=0;

    pScore_txt.text = "0";

    }

    }

    Explanation of the Code We first create variables for score, an array (rec_array) to holdthe individual scores, and a timer that ticks every 1,000 milliseconds and add an event listenerto the timer, which calls a function (timedFunction) at every tick. The timer is started. Thevisible property of the two buttons (pa_btn and cls_btn) is set to false. The dynamic text boxpName_txt is assigned the value from the variable pNam.

    The rest of the code is set up as function calls upon button click events. A mouse click eventhandler is added to the cls_btn, which calls the clearScores function. The clearScoresfunction clears the SharedObject jso2 and takes the player to frame 1.

    A mouse click event handler is added to the pa_btn that calls the function restart(). Therestart() function starts the timer. It also adds a mouse click event listener to the scr_btn,which in turn calls the incScr function. Finally, the restart() function sets the visible propertyof the pa_btn and cls_btn to false.

    A mouse click event handler is added to the scr_btn (the object that will be clicked), which callsthe function incrScr(). The incrScr function positions the object at random x and y positions,which were generated by the random position. The value of the variable score is assigned to the

    text box pScore_txt.

    A variable jso of type SharedObject is created and is assigned the value saved in the local sharedobject hscr. The shared object has a data property to which objects of type Array, Number,Boolean, ByteArray, or XML can be assigned. In our example jso.data.scrz, the scrz is an arraythat keeps track of the names and scores of the players. This scrz array is assigned to the variablerec_array.

    The function hs2 basically populates the rec_array elements with values and sorts the array indescending order of numeric values. Each element of the rec_array has two fields, name (pN)and score (pS). The push method of the array is used to send the values from the pName._text

    and pScore_txt text boxes to the pN and pS fields. The jso.flush method is used to write the

    What Is a SharedObject? 181

  • 8/9/2019 Beginning Game Programming With Flash Chapter 8

    21/21

    content of the SharedObject to the local file, which in this case is the array object. An if conditionis used to check if each element of the array is not equal to null, and the data contained in thatelement is written to the corresponding text boxes, pn0 and ps0. This process is repeated until thelast elements of the array, [rec_array9].ps and rec_array[9].ps, have been checked, and the

    data is written to the corresponding text boxes, pn9 and ps9.The last function is the timedFunction, which will be called by the myTimer every 1,000milliseconds, which is the same as one second. This function has the variable tc set to 31, whichgets decremented every second, the numeric value provided by the currentCount (gives the totalnumber of times the timer has fired starting at 0) method of the timer object. This value isdisplayed to the player in pTime_txt, which is a dynamic text box. An if condition is used tocheck if the value of currentCount is greater than 30; if true, it does the following tasks:MouseEventevent.CLICK is removed from the object so it cannot be clicked anymore, the timer isreset, the timer is stopped, and the hs2 function is called. The Play Again (pa_btn) and ClearScores (cls_btn) buttons are set to false, the score is set to 0, and the text box used to display

    the score (pScore_txt) is also set to 0. That finishes the design and explanation of the code foryour high scores game. Test your game, save it, and enjoy it.

    Summary

    In this chapter we looked at the SharedObject, its purposes, and limitations. We

    also looked at managing persistent data through a SharedObject. Finally we

    looked at how to use the SharedObject for keeping track of high scores on an

    individual computer.

    Review Questions1. What are the purposes of a SharedObject?

    2. What are the limitations of a SharedObject?

    3. How can you use a SharedObject in a game?

    4. What are some types of objects that can be added to the data object in a

    SharedObject?

    Project

    1. Use the concepts presented in this chapter and add a SharedObject feature

    to the game in Chapter 5.

    2. Display the high scores for five players.

    182 Chapter 8 n High Scores Game