ch01.txt

来自「ActionScript3.0 Cookbook范例源代码」· 文本 代码 · 共 983 行 · 第 1/2 页

TXT
983
字号
    ====================================// Check if it is a weekend.if ((current.getDay() == 0) || (current.getDay() == 6) ) {  trace ("Why are you working on a weekend?");}        ====================================// Check to see if the name is not Bruce.if (!(userName == "Bruce")) {  trace ("This application knows only Bruce's birthday.");}        ====================================if (userName != "Bruce") {  trace ("This application knows only Bruce's birthday.");}        ====================================// Check to see if a sprite is visible. If so, display a// message. This condition is shorthand for _sprite.visible == trueif (_sprite.visible) {  trace("The sprite is visible.");}        ====================================// Check to see if a sprite is invisible (not visible). If so, // display a message. This condition is shorthand for // _sprite.visible != true or _sprite.visible == false.if (!_sprite.visible) {  trace("The sprite is invisible. Set it to visible before trying this action.");}        ====================================// Check to see if the name is neither Bruce nor Joey. (This could// also be rewritten using two inequality operators and a logical// AND.)if (!((userName == "Bruce") || (userName == "Joey"))) {  trace ("Sorry, but only Bruce and Joey have access to this application.");}        ====================================for (var i:int = 0; i < 10; i++) {  // Display the value of i.  trace(i);}        ====================================for (initialization; test; update) {  statement body}        ====================================for (var i:int = 0; i < 1000; i++) {  trace(i);}trace ("That's the end.");        ====================================for (var i:int = 0, j:int = 10; i < 10; i++, j--) {  trace("i is " + i);  trace("j is " + j);}        ====================================for (var i:int = 1; i <= 3; i++) {  for (var j:int = 1; j <= 2; j++) {    trace(i + " X " + j + " = " + (i * j));  }}        ====================================1 X 1 = 11 X 2 = 22 X 1 = 22 X 2 = 43 X 1 = 33 X 2 = 6        ====================================for (var i:int = 1; i <= 3; i++) {  for (var j:int = 1; j <= 3; j++) {    for (var k:int = 1; k <= 3; k++) {      trace(i + " X " + j + " X " + k + " = " + (i * j * k));    }  }}        ====================================// Count backward from 10 to 1.for (var i:int = 10; i > 0; i--) {  trace(i);}// Display a sequence of square roots.for (var i:Number = 50000; i > 2; i = Math.sqrt(i)) {  trace(i);}        ====================================for (var i:int = 0; i < 20; i++) {  _sprite.x += 10;}        ====================================var timer:Timer = new Timer(delay, repeatCount);        ====================================package {    import flash.display.Sprite;    import flash.events.TimerEvent;    import flash.utils.Timer;        public class ExampleApplication extends Sprite {        // Declare and initialize a variable to store the value        // of the previous timer reading.        private var _PreviousTime:Number = 0;                public function ExampleApplication() {            var tTimer:Timer = new Timer(500, 10);            tTimer.addEventListener(TimerEvent.TIMER, onTimer);            tTimer.start();        }                private function onTimer(event:TimerEvent):void {            // Output the difference between the current timer value and            // its value from the last time the function was called.            trace(flash.utils.getTimer() - _PreviousTime);            _PreviousTime = flash.utils.getTimer();         }    }}        ====================================package {    import flash.display.Sprite;    import flash.events.TimerEvent;    import flash.utils.Timer;        public class ExampleApplication extends Sprite {        private var _square:Sprite;        private var _circle:Sprite;                        public function ExampleApplication() {            // Create the two sprites and draw their shapes            _square = new Sprite();            _square.graphics.beginFill(0xff0000);            _square.graphics.drawRect(0, 0, 100, 100);            _square.graphics.endFill();            addChild(_square);            _square.x = 100;            _square.y = 50;                        _circle = new Sprite();            _circle.graphics.beginFill(0x0000ff);            _circle.graphics.drawCircle(50, 50, 50);            _circle.graphics.endFill();            addChild(_circle);            _circle.x = 100;            _circle.y = 200;                        // Create the two timers and start them            var squareTimer:Timer = new Timer(50, 0);            squareTimer.addEventListener(TimerEvent.TIMER, onSquareTimer);            squareTimer.start();                        var circleTimer:Timer = new Timer(100, 0);            circleTimer.addEventListener(TimerEvent.TIMER, onCircleTimer);            circleTimer.start();        }                // Define the two handler methods        private function onSquareTimer(event:TimerEvent):void {            _square.x++;        }                private function onCircleTimer(event:TimerEvent):void {            _circle.x++;        }    }}        ====================================               accessModifier function functionName ():ReturnDataType {  // Statements go here.}        ====================================                 functionName();        ====================================package {    import flash.display.Sprite;    public class ExampleApplication extends Sprite    {        public function ExampleApplication() {            for(var i:int=0;i<10;i++) {                drawLine();            }        }            private function drawLine():void {            graphics.lineStyle(1, Math.random() * 0xffffff, 1);            graphics.moveTo(Math.random() * 400, Math.random() * 400);            graphics.lineTo(Math.random() * 400, Math.random() * 400);        }    }}        ====================================public static function showMessage( ):void {    trace("Hello world");}        ====================================ExampleApplication.showMessage();        ====================================private function average (a:Number, b:Number, c:Number):void {  trace("The average is " + (c + b + c)/3);}        ====================================// Define the function such that it expects two parameters: a and b.private function average(a:Number, b:Number):Number {  return (a + b)/2;}        ====================================// When you invoke the function, pass it two arguments, such as // 5 and 11, which correspond to the a and b parameters. var averageValue:Number = average(5, 11);        ====================================// There is no need to specify the parameters to accept when using the // arguments array.private function average():Number {  var sum:Number = 0;  // Loop through each of the elements of the arguments array, and   // add that value to sum.  for (var i:int = 0; i < arguments.length; i++) {    sum += arguments[i];  }  // Then divide by the total number of arguments  return sum/arguments.length;}// You can invoke average() with any number of parameters. var average:Number = average (1, 2, 5, 10, 8, 20);        ====================================private function sampleFunction ():void {  return;  trace("Never called");}// Called from within another method:sampleFunction();// Execution continues here after returning from the sampleFuction() invocation        ====================================private function checkPassword (password:String):void {  // If password is not "SimonSays", exit the function.  if (password != "SimonSays") {    return;  }  // Otherwise, perform the rest of the actions.  showForm ("TreasureMap");}// This method call uses the wrong password, so the // function exits.checkPassword("MotherMayI");// This method call uses the correct password, so the function // shows the TreasureMap form.checkPassword("SimonSays");        ====================================private function sampleMethod ():void {  return "some value";  // This causes the compiler to generate an error.}        ====================================private function average (a:Number, b:Number):Number {  return (a + b)/2;}        ====================================var playerScore:Number = average(6, 10);trace("The player's average score is " + playerScore);        ====================================trace("The player's average score is " + average(6, 10));        ====================================average(6, 10);        ====================================throw new Error("A general error occurred.");        ====================================try {  trace("This code is about to throw an error.");  throw new Error("A general error occurred.");  trace("This line won't run");}catch (errObject:Error) {  trace("The catch block has been called.");  trace("The message is: " + errObject.message);}        ====================================This code is about to throw an error.The catch block has been called.The message is: A general error occurred.        ====================================private function displayMessage(message:String):void {  if(message == undefined) {    throw new Error("No message was defined.");  }  trace(message);}try {  trace("This code is about to throw an error.");  displayMessage();  trace("This line won't run");}catch (errObject:Error) {  trace("The catch block has been called.");  trace("The message is: " + errObject.message);}        ====================================This code is about to throw an error.The catch block has been called.The message is: No message was defined.        ====================================// Define a function that draws a rectangle within a specified spriteprivate function drawRectangle(sprite:Sprite, newWidth:Number, newHeight:Number):void {  // Check to see if either of the specified dimensions are not   // a number. If so, then thrown an error.  if(isNaN(newWidth) || isNaN(newHeight)) {    throw new Error("Invalid dimensions specified.");  }  // If no error was thrown, then draw the rectangle.  sprite.graphics.lineStyle(1, 0, 1);  sprite.graphics.lineTo(nWidth, 0);  sprite.graphics.lineTo(nWidth, nHeight);  sprite.graphics.lineTo(0, nHeight);  sprite.graphics.lineTo(0, 0);}        ====================================try {  // Attempt to draw two rectangles within the current sprite.   // In this example it is assumed that the variables for the dimensions   // are retreiving values from user input, a database, an XML file,   // or some other datasource.  drawRectangle(this, widthA, heightA);  drawRectangle(this, widthB, heightB);}catch(errObject:Error) {  // If an error occurs, clear any rectangles that were drawn from   // the sprite. Then display a message to the user.  this.graphics.clear();  tOutput.text = "An error occurred: " + errObject.message;}        ====================================//Without using finally:private function displayMessage(message:String):void {  try {    if(message == undefined) {      throw new Error("The message is undefined.");    }    trace(message);  }  catch (errObject:Error) {    trace(errObject.message);  }  trace("This is the last line displayed.");}//With finally:private function displayMessage(message:String):void {  try {    if(message == undefined) {      throw new Error("The message is undefined.");    }    trace(message);  }  catch (errObject:Error) {    trace(errObject.message);  }  finally {    trace("This is the last line displayed.");  }}        ====================================//Without using finally:private function displayMessage(message:String):void {  try {    if(message == undefined) {      throw new Error("The message is undefined.");    }    trace(message);  }  catch (errObject:Error) {    trace(errObject.message);    return;  }  // This line won’t run if an error is caught.  trace("This is the last line displayed.");}//With finally:private function displayMessage(message:String):void {  try {    if(message == undefined) {      throw new Error("The message is undefined.");    }    trace(message);  }  catch (errObject:Error) {    trace(errObject.message);    return;  }  finally {    // This runs, even if an error is caught.    trace("This is the last line displayed.");  }}        ==================

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?