Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
104
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Appendix A

color: #FF0000; text-decoration: underline;

}

a:hover{

color: #CCCCCC; text-decoration: underline;

}

CODE:

loadImage = function (args) { args = args.split(“,”);

field[args[0]].loadMovie(args[1]);

};

var field = this.createTextField(“field1”, 1, 20, 20, 300, 0); field.autoSize = true;

field.wordWrap = true; field.multiline = true; field.html = true;

var myStyles:TextField.StyleSheet = new TextField.StyleSheet();

myStyles.onLoad = function(success:Boolean):Void { if (success) {

field.styleSheet = myStyles;

}

trace(“ok”);

field.htmlText = “<p>This is some text with an image tag.<img id=’imageTag1’ ; src=’imgTag.swf’ width=’100’ height=’100’/> Press <a ; href=’asfunction:loadImage,imageTag1,image.jpg’><u>this link</u></a> to ;

control some action script within it.</p><div>Hello div.</div>”; };

myStyles.load(“styles.css”);

Exercise 4 Solution

loadImage = function (args) { args = args.split(“,”);

field[args[0]].loadMovie(args[1]);

};

var field = this.createTextField(“field1”, 1, 20, 20, 300, 0); field.autoSize = true;

field.wordWrap = true; field.multiline = true; field.text = “This is a test”;

boldButton.onRollOver = function() {

begin = Selection.getBeginIndex(); end = Selection.getEndIndex();

};

boldButton.onRelease = function() {

var format = field.getTextFormat(begin,end); format.bold = true; field.setTextFormat(begin, end, format); Selection.setFocus(field); Selection.setSelection(begin, end);

};

738

Exercise Answers

Chapter 19

Exercise 1 Solution

var b1 = this.createEmptyMovieClip(“button1”, 1); b1.onRollOver = function() {

if (this.loaded == true) { this.defaultState._visible = false;

}

};

b1.onRollOut = function() { if (this.loaded == true) {

this.defaultState._visible = true;

}

};

var clip1 = b1.createEmptyMovieClip(“defaultState”, 1); var clip2 = b1.createEmptyMovieClip(“overState”, 0);

var mcOnLoadHandler:Object = new Object(); mcOnLoadHandler.num = 0; mcOnLoadHandler.states = 2;

mcOnLoadHandler.onLoadInit = function(clip_mc:MovieClip) { this.num++;

if (this.num == this.states) { clip_mc._parent.loaded = true;

}

};

var mcLoader:MovieClipLoader = new MovieClipLoader(); mcLoader.addListener(mcOnLoadHandler); mcLoader.loadClip(“logo.gif”, clip1); mcLoader.loadClip(“logo_red.gif”, clip2);

Exercise 2 Solution

var mySound:Sound = new Sound();

var soundControl = this.createEmptyMovieClip(“clip1”, 1); soundControl.func1000 = function() {

trace(“firstEvent”);

};

soundControl.func2000 = function() { trace(“secondEvent”);

};

soundControl.watchSound = function() { trace(mySound.position);

if (mySound.position>1000 && this.func1000.fired != true) { this.func1000.fired = true;

this.func1000();

}

if (mySound.position>2000 && this.func2000.fired != true) { this.func2000.fired = true;

this.func2000();

}

};

mySound.onLoad = function(success) { if (success) {

offset = getTimer();

soundControl.watcher = setInterval(soundControl, “watchSound”, 5);

739

Appendix A

}

};

mySound.loadSound(“myTrack.mp3”, true);

Exercise 3 Solution

this.createEmptyMovieClip(“microphone_mc”, this.getNextHighestDepth()); var myMic_mic:Microphone = Microphone.get(); myMic_mic.setUseEchoSuppression(true); microphone_mc.attachAudio(myMic_mic);

level.mode = “manual”; arrayhappy = [];

arrayhappy.push(“I’m so happy to see you dave.”); arrayhappy.push(“It’s suddenly like a party.”); arrayhappy.push(“It’s always nice to have company.”); arrayhappy.push(“Is this music?”); arrayhappy.push(“What a world!”);

arraysad = [];

arraysad.push(“I’m feeling kind of lonely dave.”); arraysad.push(“How about a nice game of chess?”); arraysad.push(“There is a solitude of space, A solitude of sea...”); micLevel = function () {

level.setProgress(myMic_mic.activityLevel, 100);

if (myMic_mic.activityLevel>40) { startTime = getTimer();

trace(arrayhappy[random(arrayhappy.length)]);

}

var now = getTimer()-startTime; if (now>60000 && now<60020) {

trace(arraysad[random(arraysad.length)]);

}

if (now>80000 && now<80020) { trace(arraysad[random(arraysad.length)]);

}

if (now>100000 && now<100020) { trace(arraysad[random(arraysad.length)]);

}

};

startTime = 0;

this.listen = setInterval(this, “micLevel”, 10);

Chapter 20

Exercise 1 Solution

function watchload() {

if (videoClip._currentframe == 1) { videoClip.gotoAndStop(1);

}

var loaded = videoClip.getBytesLoaded()+videoClip.getBytesLoaded();

var total = videoClip.getBytesTotal()+videoClip.getBytesTotal(); if (loaded/total>.3 && loaded>10) {

if (mySound.position == 0) { mySound.start();

}else{

740

Exercise Answers

var percentPlayed = mySound.position/mySound.duration; videoClip.gotoAndStop(int(videoClip._totalframes*percentPlayed));

}

}

}

videoClip = createEmptyMovieClip(“clip1”, this.getNextHighestDepth()); videoClip.loadMovie(“movie.swf”);

mySound = new Sound(); mySound.loadSound(“mySoundTrack.mp3”, true); mySound.stop();

go = setInterval(_root, “watchload”, 10);

Exercise 2 Solution

mySound = new Sound(); mySound.loadSound(“mySound.mp3”, false); var theCamFeed:Camera = Camera.get(); var myCamera:Video = holder.myCamera; myCamera.smoothing = true; myCamera.attachVideo(theCamFeed);

watchFeed = setInterval(this, “rotate”, 1); theCamFeed.setMotionLevel(20, .5);

theCamFeed.onActivity = function(active) { if (active == true) {

_root.mySound.setVolume(theCamFeed.activityLevel); _root.mySound.start();

} else {

trace(“motion stopped”);

}

};

Chapter 21

Exercise 1 Solution

Add text such as the following to a text file:

var1=a|var2=b|var3=c|var3=d

Add the following ActionScript to a new Flash document saved in the same directory as the text file. In this example it’s assumed that the text file is called myData.txt.

var variables:Object = new Object(); var myVars:LoadVars = new LoadVars();

myVars.onData = function(str:String):Void { var data:Array = str.split(“|”);

var item:Array;

for(var i:Number = 0; i < data.length; i++) { item = data[i].split(“=”); variables[item[0]] = items[1];

}

};

myVars.load(“myData.txt”);

741

Appendix A

Exercise 2 Solution

Add text such as the following to a text file:

<a href=”http://www.adobe.com”>Adobe</a>

Add the following ActionScript to a new Flash document saved in the same directory as the text file. In this example it’s assumed that the text file is called myHTMLData.txt.

this.createTextField(“myText”, 1, 0, 0, 400, 400); myText.html = true;

var myVars:LoadVars = new LoadVars(); myVars.onData = function (str:String):Void {

myText.htmlText = str;

};

myVars.load(“myHTMLData.txt”);

Chapter 22

Exercise 1 Solution

All of these will fail silently.

Exercise 2 Solution

<?xml version=”1.0” encoding=”ISO-8859-1”?> <channels>

<Station identification=”104.1” url=”www.someurl.com/1041”> <Name>

Rock And Roll Oldies! </Name>

<Desc>

Music great with hot chocolate! </Desc>

</Station>

<Station identification=”98.6” url=”www.someurl.com/986”> <Name>

Rock and Roll </Name>

<Desc>

Music for waiting for Godot! </Desc>

</Station>

<Station identification=”102.5” url=”www.someurl.com/1025”> <Name>

Electronic Madness! </Name>

<Desc>

Arigato Rules! </Desc> </Station>

<Station identification=”107.9” url=”www.someurl.com/1079”> <Name>

742

Exercise Answers

Electronic Madness 2! <Name>

<Desc>

Thunder Dome! </Desc> </Station>

</channels>

You don’t add the URL as a node, but as an attribute because a URL is unlikely to have child considerations.

Exercise 3 Solution

stations = new XML(); stations.ignoreWhite = true; stations.onLoad = function(success) {

var out = []; if (success) {

var main = this.firstChild;

for (var i in main.childNodes) { var node = main.childNodes[i]; var outRecord = out[i]={};

outRecord.id = node.attributes.identification; outRecord.url = node.attributes.url;

for (var j in node.childNodes) {

var nodeNameStr = node.childNodes[j].nodeName.toLowerCase(); if (nodeNameStr == “name”) {

outRecord.name = node.childNodes[j].firstChild.toString();

}

if (nodeNameStr == “desc”) {

outRecord.desc = node.childNodes[j].firstChild.toString();

}

}

}

}

stations = out;

};

stations.load(“stations.xml”);

Exercise 4 Solution

valueOne=This is a test string.|valueTwo=This is another test string.|valueThree=and another just for good measure. pipeFile = new LoadVars();

pipeFile.onData = function(str) { str = str.split(“|”);

for (var i in str) {

var pair = str[i].split(“=”);

this[pair[0]] = pair[1];

}

var ok = false; if (str) {

ok = true;

}

pipeFile.onLoad(ok);

743

Appendix A

};

pipeFile.onLoad = function(success){ trace(this.valueOne);

}

pipeFile.load(“pipes.txt”);

Chapter 23

Exercise 1 Solution

Create one SWF file called controls.swf containing two button components labeled “Play” and “Pause” and with instance ids playButton and pauseButton. You can use animation.swf from the last Chapter 10 Try It Out exercise as a placeholder.

controls.swf

var commandLocalConnection = new LocalConnection();

var buttonListener:Object = new Object(); buttonListener.click = function(eventHandle:Object)

{

switch (eventHandle.target._name)

{

case “playButton”:

commandLocalConnection.send(“commandChannel”, “controlPlayback”,

“play”);

break;

case “pauseButton”:

commandLocalConnection.send(“commandChannel”, “controlPlayback”, ; “pause”);

break;

}

}

playButton.addEventListener(“click”, buttonListener); pauseButton.addEventListener(“click”, buttonListener);

animationHolder.swf

this.createEmptyMovieClip(“animationHolder”, this.getNextHigherDepth()); animationHolder.loadMovie(“animation.swf”);

var commandLocalConnection:LocalConnection = new LocalConnection(); commandLocalConnection.controlPlayback = function(commandString:String)

{

switch(commandString)

{

case “play”: animationHolder.play(); break;

case “pause”: animationHolder.stop(); break;

}

};

commandLocalConnection.connect(“commandChannel”);

744

Exercise Answers

index.html

<html>

<head>

<title>animationHolder</title>

</head>

<body bgcolor=”#ffffff”> <object

classid=”clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” codebase=”http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/;

swflash.cab#version=8,0,0,0”

width=”300”

height=”50”

id=”animationHolder”

align=”middle”>

<param name=”allowScriptAccess” value=”sameDomain” /> <param name=”movie” value=”controls.swf” />

<param name=”quality” value=”high” /> <param name=”bgcolor” value=”#ffffff” /> <embed src=”controls.swf”

quality=”high”

bgcolor=”#ffffff”

width=”300”

height=”50”

name=”animationHolder”

align=”middle”

allowScriptAccess=”sameDomain” type=”application/x-shockwave-flash” pluginspage=”http://www.macromedia.com/go/getflashplayer” />

</object> <br /> <object

classid=”clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” codebase=”http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/;

swflash.cab#version=8,0,0,0”

width=”550”

height=”400”

id=”animationHolder”

align=”middle”>

<param name=”allowScriptAccess” value=”sameDomain” /> <param name=”movie” value=”animationHolder.swf” /> <param name=”quality” value=”high” />

<param name=”bgcolor” value=”#ffffff” /> <embed src=”animationHolder.swf”

quality=”high”

bgcolor=”#ffffff”

width=”550”

height=”400”

name=”animationHolder”

align=”middle”

allowScriptAccess=”sameDomain” type=”application/x-shockwave-flash” pluginspage=”http://www.macromedia.com/go/getflashplayer” />

</object>

</body>

</html>

745

Appendix A

Exercise 2 Solution

The following code assumes that there is a text field called usernameField and a drop-down menu called languageDropDown.

var loginDataSharedObject:SharedObject = SharedObject.getLocal(“loginData”); if (loginDataSharedObject.data.username != undefined)

{

usernameField.text = loginDataSharedObject.data.username;

}

if (loginDataSharedObject.data.language != undefined)

{

for (var i:Number = 0; i < languageDropDown.length; i++)

{

if (languageDropDown.getItemAt(i).data == loginDataSharedObject.data.language)

{

languageDropDown.selectedIndex = i; break;

}

}

}

var buttonListener:Object = new Object(); buttonListener.click = function()

{

loginDataSharedObject.data.username = usernameField.text; loginDataSharedObject.data.language = languageDropDown.selectedItem.data; myPersistentObject.flush();

trace(“Setting username: “ + usernameField.text);

trace(“Setting language: “ + languageDropDown.selectedItem.data);

}

loginButton.addEventListener(“click”, buttonListener);

Chapter 24

Exercise Solution

ActionScript

import flash.external.ExternalInterface; import mx.controls.Button;

import mx.controls.Label; import mx.controls.TextInput;

var windowName:String = “myWindow”;

var windowFeatures:String = “toolbar=no,address=no”;

// Set up the width and height fields and labels this.createClassObject(Label, “urlLabel”, this.getNextHighestDepth(), ;

{_x:10, _y:13}); urlLabel.text = “URL:”;

this.createClassObject(TextInput, “urlInput”, this.getNextHighestDepth(), ; {_x:60, _y:10, _width:300});

746

Exercise Answers

urlInput.text = “http://www.macromedia.com/”;

// Set up the open window button

this.createClassObject(Button, “openWindowButton”, this.getNextHighestDepth(), ; {_x:10, _y:40});

openWindowButton.label = “Open Window”;

// Set up the close window button

this.createClassObject(Button, “closeWindowButton”, this.getNextHighestDepth(), ; {_x:125, _y:40});

closeWindowButton.label = “Close Window”;

// Handle the open window button

var openWindowHandler:Object = new Object(); openWindowHandler.click = function()

{

ExternalInterface.call(“openWindow”, urlInput.text, windowName, ; windowFeatures);

//Alternately:

//getURL(“javascript:openWindow(‘“ + urlInput.text +”’, ‘“ + windowName + ;

“‘, ‘“ + windowFeatures + “‘);”);

}

openWindowButton.addEventListener(“click”, openWindowHandler);

// Handle the close window button

var closeWindowHandler:Object = new Object(); closeWindowHandler.click = function()

{

ExternalInterface.call(“closeWindow”);

//Alternately:

//getURL(“javascript:closeWindow()”);

}

closeWindowButton.addEventListener(“click”, closeWindowHandler);

HTML/JavaScript

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” ; “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”> <head>

<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1” /> <title>exercise 1</title>

<script type=”text/javascript”> var windowHandle = null;

function openWindow(destinationURL, windowName, windowFeatures)

{

windowHandle = window.open(destinationURL, windowName, windowFeatures); windowHandle.focus();

}

function closeWindow()

{

windowHandle.close();

}

</script>

</head>

747