as3 - trying to make a simple search box - actionscript-3

Hi guys im new to as3 but really love it so would like to continue my journey. Anyway, i am making this search "engine" for a school project and so far all i want it to do is take what the user searched for, search the text document i have for a match, then print it. I have tested the array and it does include the words in the text document so i dont know what im doing wrong. Thanks for any help <3
Heres my code:
import flash.net.URLRequest;
import flash.events.Event;
import flash.events.KeyboardEvent;
var search:Boolean = false;
var inputText:String;
var arrayResults:Array = new Array();
var array:Array = new Array();
var link:URLLoader = new URLLoader;
link.load(new URLRequest("GameList.txt"))
link.addEventListener(Event.COMPLETE, linkLoad)
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpControl)
addEventListener(Event.ENTER_FRAME, mainProgramLoop)
function mainProgramLoop(func:Event):void
{
if (search == true)
{
inputText = input.text
inputText = inputText.toUpperCase()
for (var i:int = 0; i < array.length; i++)
{
if (inputText == String(array[i]))
{
arrayResults.push(array[i])
trace(arrayResults)
}
}
}
}
function keyUpControl(func:KeyboardEvent):void
{
if (func.keyCode==Keyboard.ENTER)
{
search = true;
}
}
function linkLoad(func:Event):void
{
array = func.target.data.split(",")
}

Related

Making a reset placed objects button in Flash (as3)

I have a drag and drop project where everytime I click on a movieclip a clone is made that can be dragged. I would like to know how to make a button that can reset/remove the clones when the button is pressed.
This is what I got so far:
import flash.display.MovieClip;
var latestClone:MovieClip;
plus.addEventListener(MouseEvent.MOUSE_DOWN, onPlusPressed);
function onPlusPressed(event:MouseEvent):void
{
latestClone = new Plus();
latestClone.x = event.stageX;
latestClone.y = event.stageY;
addChild(latestClone);
latestClone.startDrag();
latestClone.addEventListener(MouseEvent.MOUSE_DOWN, latestClone.startDrag);
}
stage.addEventListener(MouseEvent.MOUSE_UP, onStageReleased);
function onStageReleased(event:MouseEvent):void
{
if(latestClone != null){
latestClone.stopDrag();
}
}
Add all of your clones in an array, and loop over the array and do a removeChild on each item in the array. So:
var items:Array = new Array();
....
addChild(latestClone);
items.push(latestClone);
....
var resetButton:SimpleButton = new SimpleButton();
//set your button properties here
resetButton.addEventListener(MouseEvent.CLICK, onResetClicked);
addChild(resetButton);
function onResetClicked(e:MouseEvent):void
{
reset();
}
function reset():void
{
for (var i:uint = 0; i < items.length; i ++)
{
removeChild(items[i]);
items[i] = null;
}
items = new Array();
}
Hope this helps.
just declare container variable like so:
var clone_container:Sprite = new Sprite();
put all clones inside,than u can clear it up very easely:
while(clone_container.numChildren > 0){
clone_container.removeChildAt(0);
}
that's all..
I found the solution to my question by testing several possibilities with the code that was posted + searching other questions.
This is the code that worked:
import flash.display.MovieClip;
import flash.events.MouseEvent;
var latestClone:MovieClip;
plus.addEventListener(MouseEvent.MOUSE_DOWN, onPlusPressed);
function onPlusPressed(event:MouseEvent):void
{
latestClone = new Plus();
latestClone.x = event.stageX;
latestClone.y = event.stageY;
addChild(latestClone);
latestClone.startDrag();
latestClone.addEventListener(MouseEvent.MOUSE_DOWN,onClonedPlusPressed);
}
function onClonedPlusPressed(event:MouseEvent):void{
latestClone = MovieClip(event.currentTarget);
latestClone.startDrag();
}
stage.addEventListener(MouseEvent.MOUSE_UP, onStageReleased);
function onStageReleased(event:MouseEvent):void
{
if(latestClone != null){
latestClone.stopDrag();
items.push(latestClone);
}
}
resetButton.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
function fl_MouseClickHandler(event:MouseEvent):void
{
}
var items:Array = new Array();
resetButton.addEventListener(MouseEvent.CLICK, onResetClicked);
addChild(resetButton);
function onResetClicked(e:MouseEvent):void
{
reset();
}
function reset():void
{
for (var i:uint = 0; i < items.length; i ++)
{ items[i].removeEventListener(MouseEvent.MOUSE_DOWN,onClonedPlusPressed);
if(items[i].parent) items[i].parent.removeChild(items[i]);
items[i] = null;
}
items = new Array()
}
you most add an array and push object into this,
your solution:
import flash.display.MovieClip;
import flash.events.Event;
var latestClone:MovieClip;
plus.addEventListener(MouseEvent.MOUSE_DOWN, onPlusPressed);
var plusArray:Array = new Array();
resetbtn.addEventListener(MouseEvent.CLICK,resetFunc);
function resetFunc(e:Event)
{
for (var i=0; i<plusArray.length; i++)
{
removeChild(plusArray[i]);
}
plusArray = new Array()
}
function onPlusPressed(event:MouseEvent):void
{
latestClone = new Plus();
latestClone.x = event.stageX;
latestClone.y = event.stageY;
plusArray.push(latestClone);
addChild(plusArray[plusArray.length-1]);
plusArray[plusArray.length - 1].startDrag();
plusArray[plusArray.length - 1].addEventListener(MouseEvent.MOUSE_DOWN, plusArray[plusArray.length-1].startDrag);
}
stage.addEventListener(MouseEvent.MOUSE_UP, onStageReleased);
function onStageReleased(event:MouseEvent):void
{
if (latestClone != null)
{
latestClone.stopDrag();
}
}
Good luck

Remove all created symbols from stage

I don't usually do this, but i'm lost here.
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
var first_tile:colors;
var second_tile:colors;
var pause_timer:Timer;
var game_timer:Timer;
var colordeck:Array = new Array(1,1,2,2,3,3,4,4,5,5,6,6);
function color_match() {
game_timer = new Timer(10000,1);
for (x=1; x<=4; x++) {
for (y=1; y<=3; y++) {
var random_card = Math.floor(Math.random()*colordeck.length);
var tile:colors = new colors();
tile.col = colordeck[random_card];
colordeck.splice(random_card,1);
tile.gotoAndStop(7);
tile.x = ((x-1)*70)+30;
tile.y = ((y-1)*100)+30;
tile.addEventListener(MouseEvent.CLICK,tile_clicked);
game_timer.addEventListener(TimerEvent.TIMER_COMPLETE,end_game);
addChild(tile);
}
}
game_timer.start();
}
function tile_clicked(event:MouseEvent) {
var clicked:colors = (event.currentTarget as colors);
if (first_tile == null) {
first_tile = clicked;
first_tile.gotoAndStop(clicked.col);
}
else if (second_tile == null && first_tile != clicked) {
second_tile = clicked;
second_tile.gotoAndStop(clicked.col);
if (first_tile.col == second_tile.col) {
pause_timer = new Timer(1000,1);
pause_timer.addEventListener(TimerEvent.TIMER_COMPLETE,remove_tiles);
pause_timer.start();
}
else {
pause_timer = new Timer(1000,1);
pause_timer.addEventListener(TimerEvent.TIMER_COMPLETE,reset_tiles);
pause_timer.start();
}
}
}
function reset_tiles(event:TimerEvent) {
first_tile.gotoAndStop(7);
second_tile.gotoAndStop(7);
first_tile = null;
second_tile = null;
pause_timer.removeEventListener(TimerEvent.TIMER_COMPLETE,reset_tiles);
}
function remove_tiles(event:TimerEvent) {
removeChild(first_tile);
removeChild(second_tile);
first_tile = null;
second_tile = null;
pause_timer.removeEventListener(TimerEvent.TIMER_COMPLETE,remove_tiles);
}
function end_game(event:TimerEvent) {
}
This is a little colour matching game. Click two tiles, they dissappear if matched, or turn back to grey if not. The loop creates instances of colour, in randomly placed pairs, and sets them to frame 7 (grey colour).
I cant work out how to remove any remaining colour blocks when the game time hits zero. Everything i try is throwing errors. The idea is then to let people play again, or a win script.
You don't have to necessarily code it for me, i just need to understand the process! Thanks.
I believe the best way is to create a container, so you can add all tiles and manage them on the best way you decide to.
var tileContainer:Sprite = new Sprite();
addChild(tileContainer);
// instead of addChild(tile);
tileContainer.addChild(tile);
// to remove all tiles
tileContainer.removeChildren();

Struggling with Actionscript computeSpectrum and beat detection

I am trying to understand the values given back to me from the computeSpectrum method. I want to work with the lower frequencies pick out the bass drum of a track. The numbers I am getting back from the byteArray make no sense. For example, it says that the value is 0 when there is clearly a sound playing. What am I missing here...I do know beat detection is not easy and have looked at most of the posts here on the subject...It's just that the numbers that are returned to me make no sense, can somebody explain them to me? Thanks in advance.
My Code:
import flash.display.Graphics;
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.net.URLRequest;
import flash.display.MovieClip;
var snd: Sound = new Sound();
var req: URLRequest = new URLRequest("mySong.mp3");
snd.load(req);
var channel: SoundChannel;
channel = snd.play();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
snd.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
const CHANNEL_LENGTH: int = 256;
const BUFFER_LENGTH: int = 512;
var bytes:ByteArray = new ByteArray();
function onEnterFrame(event: Event): void
{
SoundMixer.computeSpectrum(bytes, true, 0);
for (var i:int = 0; i < CHANNEL_LENGTH; i++) // channel_length = 256
{
var sampleValue:Number = bytes.readFloat() * 200;
var byteArrayIndex = bytes.position;
trace(byteArrayIndex, sampleValue);
}
}
function onPlaybackComplete(e:Event):void
{
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}
Nice to meet you again, I think I'm more understand your mind this time.
If you are going to check whether there exist a 'beat' at a specific time of the song;
I may suggest this method for reference:
import flash.events.Event;
var snd: Sound = new Sound();
var req: URLRequest = new URLRequest("mySong.mp3");
snd.load(req);
var channel: SoundChannel;
channel = snd.play();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
snd.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
// I want to specify which region of byteData is passing to my check function.
// this two value help me to extract the sample I need.
var checkLength:int = 20;
var checkStart:int = 0;
var theshold:Number = 0.5; // How big the value should I determine it is the 'beat'.
const CHANNEL_LENGTH: int = 256;
const BUFFER_LENGTH: int = 512;
var myArray:Array;
var bytes:ByteArray = new ByteArray();
function onEnterFrame(event: Event): void
{
SoundMixer.computeSpectrum(bytes, true, 0);
myArray = [];
for (var i:int = checkStart; i < checkLength; i+=8) // extract the sample
{
var sampleValue:Number = bytes.readFloat();
myArray.push(sampleValue);
}
if( CheckBeat( myArray ))
{
trace("here maybe a beat!!", getTimer());
}
}
function CheckBeat(valueArray:Array):Boolean // check the whether 'beat' exist
{
var meanValue:Number = valueArray[0];
for(var i:int = 1; i < valueArray.length; i++)
{
meanValue = (meanValue + valueArray[i])/2;
}
return meanValue > theshold;
}
function onPlaybackComplete(e:Event):void
{
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}
But this method is just an Estimation, and not accurate enough at all.

RSS gallery as3

Here is my case - I have 10 movie clips on the view and in every movie clip I need to have a loaded picture that RSS. I've managed to get the first one loaded but I need the other 9 as well. Any ideas?
import com.adobe.xml.syndication.generic.FeedFactory;
import com.adobe.xml.syndication.generic.IFeed;
import com.adobe.xml.syndication.generic.IItem;
import flash.display.MovieClip;
import flash.events.MouseEvent;
var rss:XML;
var rss_url:URLRequest = new URLRequest("http://btvnews.bg/lbin/rss.php?section_id=16105?pic_size=300x158");
var rssLoader:URLLoader = new URLLoader(rss_url);
rssLoader.addEventListener(Event.COMPLETE, rssLoaded);
var rssCount;
var rssCounter = 0;
var l = new Loader();
var loaderContext:LoaderContext;
loaderContext= new LoaderContext();
loaderContext.securityDomain=SecurityDomain.currentDomain;
loaderContext.checkPolicyFile = true;
Security.loadPolicyFile('http://img.bg.sof.cmestatic.com/crossdomain.xml');
function rssLoaded(e:Event):void
{
rss = XML(rssLoader.data);
var curImage = rss.channel.item[0].enclosure. # url;
l.load(new URLRequest(curImage));
l.contentLoaderInfo.addEventListener(Event.COMPLETE,doneIt);
function doneIt(e:Event)
{
var bit:Bitmap = e.target.content;
if (bit != null)
{
bit.smoothing = true;
}
}
placer.addChild(l);
After your rss load as you have loaded one images put a for loop for the item
for(var i=0; i < rss.channel.item.length;i++)
{
var img = rss.channel.item[i].enclosure. # url;
//rest of the code to load the image and adding to stage
}

Issue with sharedObject usage / loading data

The main goal of my code is to create a 3x3 grid and when you click a cell from that grid you cant click it again even if you close the fla and load it again.
Something like a shop where the 1st row is level1 of the upgrade and the columns are the other levels.
There are also 2-3 other things that it does -> every cell of the grid has 4 mouseStates.
Also at the 1st load of the FLA you create the 3x3 grid and you can click only on the elements in the 1st row.(you cant get Speed 2 if you didnt have Speed1 before that.)
So you can click the 2nd element of a column only if the 1st element of the same column has been clicked before.
The same goes for the 3rd element of the column -> it can be clicked only if the 2nd was clicked before.
But im having trouble with the logic after loading the fla for the 2nd time.
To be more specific :
It is changing the mouseOver/out states on the elements that were clicked before(which is good (cause i want to see that)), but it is leting me click only the 1st row.And since Im loading the clickedBefore buttons and removing the mouseEvent.CLICK from them, I cant click some of them if i haven`t clicked them at the 1st load of the fla.
I have 2 classes: Main
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.getDefinitionByName;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.Graphics;
import flash.display.Bitmap;
import flash.display.SimpleButton;
import flash.net.SharedObject;
public class Main extends Sprite
{
private var elementRow:int = 0;
private var elementCol:int = 0;
private var myClassImage_Arr:Array = new Array();//this contains the different mouseState Images in Class data.
private var myBitmapNames_Arr:Array = ["speed1_", "speed2_", "speed3_",
"time1_", "time2_", "time3_",
"turbo1_", "turbo2_", "turbo3_",];
//------------------------------------------
private var index:int = 0;
private var col:int = 3;
private var row:int = 3;
//------------------------------------------
private var savedData:SharedObject = SharedObject.getLocal("ZZZ_newWAY_nextButton+imageChange_7");
private var buttonThatHaveBeenClicked_Arr:Array = [];
private var myButtons_Arr:Array = [];
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
for (var i:int = 0; i < col; i++)
{
var lastRowElement:BitmapButton = null;
for (var j:int = 0; j < row; j++)
{
for (var k:int = 0; k < 4; k++)//4states of mouse
{
var cls:Class = Class(getDefinitionByName(myBitmapNames_Arr[index] + k));
myClassImage_Arr.push(cls);
}
var myImage_mc = new BitmapButton(myClassImage_Arr[0 + (index * 4)],
myClassImage_Arr[1 + (index * 4)],
myClassImage_Arr[2 + (index * 4)],
myClassImage_Arr[3 + (index * 4)], i, j);
myImage_mc.x = 100 + i * (myImage_mc.width + 10);
myImage_mc.y = 100 + j * (myImage_mc.height + 10);
myImage_mc.name = "myImage_mc" + index;
this.addChild(myImage_mc);
myButtons_Arr.push(myImage_mc)
myImage_mc.mouseEnabled = false;
myImage_mc.mouseChildren = false;
myImage_mc.buttonMode = false;
myImage_mc.addEventListener("send_SOS", onCustomClick);
if ( lastRowElement == null )
{
myImage_mc.mouseEnabled = true;
myImage_mc.mouseChildren = true;
myImage_mc.buttonMode = true;
}
else
{
lastRowElement.next_1 = myImage_mc;
}
lastRowElement = myImage_mc;
index++;
}
}
if(savedData.data.myArray == undefined) trace(" 1st time loading this game\n")
else if(savedData.data.myArray != undefined)
{
trace(" Game was played before\n")
buttonThatHaveBeenClicked_Arr = savedData.data.myArray;
var savedData_length:int = savedData.data.myArray.length;
trace("Buttons that have been clicked before: " + buttonThatHaveBeenClicked_Arr + "\n");
for (var m:int = 0; m < myButtons_Arr.length; m++)
{
var myButtons_ArrName:String = myButtons_Arr[m].name
for (var p:int = 0; p < savedData_length; p++)
{
if(myButtons_ArrName == savedData.data.myArray[p])
{
myButtons_Arr[m].alpha = 0.9
myButtons_Arr[m].buttonMode = false;
myButtons_Arr[m].removeEventListener("send_SOS", onCustomClick);
myButtons_Arr[m].myInsideBtn.upState = myButtons_Arr[m].image3
myButtons_Arr[m].myInsideBtn.overState = myButtons_Arr[m].image4
}
}
}
}
}
private function onCustomClick(ev:Event):void
{
trace(ev.target.name);
if (ev.target is BitmapButton)
{
var btn:BitmapButton = ev.currentTarget as BitmapButton;
if (btn.next_1 != null)
{
btn.next_1.mouseEnabled = true;
btn.next_1.mouseChildren = true;
btn.next_1.buttonMode = true;
}
btn.mouseChildren = false;
btn.buttonMode = false;
btn.removeEventListener("send_SOS", onCustomClick);
buttonThatHaveBeenClicked_Arr.push( btn.name );
savedData.data.myArray = buttonThatHaveBeenClicked_Arr;
savedData.flush();
savedData.close();
}
}
}
}
and BitmapButton
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.events.Event;
public class BitmapButton extends Sprite
{
public var next_1:BitmapButton = null;
//-----------------------------------
public var myInsideBtn:SimpleButton = new SimpleButton();
private var image1:Bitmap;
private var image2:Bitmap;
public var image3:Bitmap;
public var image4:Bitmap;
public var imageIsInRow:int;
public var imageIsInCol:int;
public function BitmapButton(active_OutState:Class, active_OverState:Class, notActive_OutState:Class, notActive_OverState:Class,col:int,row:int)
{
image1 = new Bitmap (new active_OutState() );
image2 = new Bitmap (new active_OverState() );
image3 = new Bitmap (new notActive_OutState() );
image4 = new Bitmap (new notActive_OverState() );
imageIsInRow = row;
imageIsInCol = col;
myInsideBtn.upState = image1;
myInsideBtn.overState = image2;
myInsideBtn.downState = myInsideBtn.upState;
myInsideBtn.hitTestState = myInsideBtn.overState;
addChild( myInsideBtn );
myInsideBtn.addEventListener(MouseEvent.CLICK, onClick);
}
private function onClick(ev:MouseEvent):void
{
myInsideBtn.upState = image3;
myInsideBtn.overState = image4;
var myNewEvent:Event = new Event("send_SOS");
this.dispatchEvent(myNewEvent);
trace("CLICK from inside the button");
}
}
}
ill also upload it to this link Grid_with_sharedObject with a zip.
and upload also Grod_before_Using_sharedObject if someone decides that he would help but the code is to messed up
If I'm reading your code correctly, I'd honestly say your problem is sequential. For whatever reason, the setting of the active and inactive rows is occurring BEFORE the data is actually being interpreted into the button states. As a result, the computer sees all buttons as off when it decides whether to make other rows clickable, and THEN updates the state of the buttons.
The easiest way to fix this, I think, would be to split the Main() function into a few sub functions, such as updateButtons() for the function that changes whether a row/button is clickable, and loadData() for the function the loads from the SharedObject. In Main(), put the calls to those functions. This will make Main() easier to work with, and you can call a function multiple times if necessary.
To solve your particular issue, you'd need to get the data for the buttons using the SharedObject FIRST (which obviously is working), and THEN update whether the other buttons are clickable.
A "soft-skills" tip for programming: when you run into a problem, grab a piece of paper, a pencil, and read through your code the way your computer would. Be the computer. Write down variables and their values when they change. Mark when functions are called. You'll spot a lot of errors this way.