how to save array in array randomly - actionscript-3

I tried to show a random number in three movieclip boxes below(blue, yellow, red) when push button(grey box). to make random numbers I use math.ceil and I keep it in a var. I make 3 var (so I've 3 formula random number). after that, I want to call that 3 var into 3 new var randomly (hasil,hasil2,hasil3). last, i put the 3 new var into random dynamic text. the dynamic text is in three movieclip boxes.
these the formula random number
mtk = Math.ceil(Math.random()*10);
mtk1 = Math.ceil(Math.random()*20);
mtk2 = mtk+mtk1;
these the dynamic text
mc.jwb1.text = hasil.toString();
mc.jwb2.text = hasil2.toString();
mc.jwb3.text = hasil3.toString();
I tried to call the 3 var in 3 random numbers use 2 arrays, but I still confused about how to call them or you have better idea, Please tell me?
var mc:jwb = new jwb();
var mtk:Number;
var mtk1:Number;
var mtk2:Number;
var hasil:int;
var hasil2:int;
var hasil3:int;
btn.addEventListener(MouseEvent.CLICK, button);
function button(e:MouseEvent):void{
addChild(mc);
}
Batas_mc.addEventListener(Event.ENTER_FRAME, batas);
function batas(e:Event):void{
mc.x = 270;
mc.y = 130;
mtk = Math.ceil(Math.random()*10);
mtk1 = Math.ceil(Math.random()*20);
mtk2 = mtk+mtk1;
//Array object acak
var P:Array = [mtk, mtk1, mtk2];
var M:Array = [hasil, hasil2, hasil3];
while (M.length){
// Get the last MovieClip and remove it from the list.
var Batumc2:MovieClip = M.pop();
// Produce a random Point.
var anIndex:int = Math.random() * P.length;
var aPo = P[anIndex];
// Remove the selected Point from its list.
P.splice(anIndex, 1);
// Move the selected MovieClip to the selected Point coordinates.
Batumc2 = aPo;
}
mc.jwb1.text = hasil.toString();
mc.jwb2.text = hasil2.toString();
mc.jwb3.text = hasil3.toString();
}

Related

how to call just 2 value in array randomly specific location flash

I've 3 mc. I want to call 2 of them on stage randomly in specific locations. I don't know how to call them. I just tried with array. I think array is the best way but still confused.
this's code I tried :
import flash.geom.Point;
var Batumc:batu_mc = new batu_mc(); // creates a instance of the movieclip, i.e, an object
var Batumc1:L = new L();
var Pisangmc:pisang_mc = new pisang_mc();
var Batumc2:MovieClip = new MovieClip();
var Status:int = 0;
button.addEventListener(MouseEvent.CLICK, tombol);
function tombol(e:MouseEvent):void{
//addChild(Batumc);
//addChild(Batumc1);
//addChild(Pisangmc);
var P:Array = [new Point(80.2, 100), new Point(260, 100), new Point(430, 100)];
var M:Array = [Batumc, Batumc1, Pisangmc];
//random benda
var benda:int = Math.random()*M.length;
// Remove the selected benda from its list.
M.splice(benda, 1);
while (M.length){
// Get the last MovieClip and remove it from the list.
Batumc2 = M.pop();
trace(Batumc2);
// Produce a random Point.
var anIndex:int = Math.random() * P.length;
var aPo:Point = P[anIndex];
// Remove the selected Point from its list.
P.splice(anIndex, 1);
// Move the selected MovieClip to the selected Point coordinates.
Batumc2.x = aPo.x;
Batumc2.y = aPo.y;
addChild(Batumc);
addChild(Batumc1);
addChild(Pisangmc);
}
Status = 1;
}
button.addEventListener(Event.ENTER_FRAME, frame);
function frame(e:Event):void{
if(Status == 1 ){
removeChild(Batumc2);
Status = 0;
}
}
when i run this code, sometimes 3 mc appear again
I think the problem is with this line:
M[i] = P.splice(randomPos, 1);
You assign M[i] (array of mc) with value from P (array of points), so M[i] = array with point and not an mc.
If you want to avoid such issues you can use Vectors instead of arrays. Its more efficient and also must contain the type you declared.
Vector class Docs.
To use the vector, instead of:
var P:Array = [...];
var M:Array = [...];
Do:
var P:Vector.<Point> = new <Number>[...];
var M:Vector.<MovieClip> = new <MovieClip>[...];
And the rest is just like arrays (pop, push, slice, ...)
To remove item from M, just splice M, i don't understand why you need to iterate over M.
M.splice(randomPos, 1);
Try getDefinitionByName
var myClass:Class = getDefinitionByName("Class_Name") as Class;
var classInstance:MovieClip = new myClass as MovieClip;
addChild(classInstance);
You just have to determine the specific location in the array for the mc'c, beside that you can get the classes from the library like this;
var locations:Array = [{xpos:100, ypos:12} , {xpos:30, ypos:50} , {xpos:400, ypos:28}, ......];
for(var i:uint=0; i<YOUR_MCS_LENGTH; i++) {
var myClass:Class = getDefinitionByName("Batumc"+i) as Class;
var mc:MovieClip = new myClass as MovieClip;
mc.x = locations[i].xpos;
mc.y = locations[i].ypos;
}
I have followed your advice #Özgün Sandal, but I get this error
ReferenceError: Error #1065: Variable Batumc10 is not defined.
at global/flash.utils::getDefinitionByName()
at nyoba9_fla::MainTimeline/frame1()
this my code :
import flash.utils.getDefinitionByName;
import flash.geom.Point;
var Batumc:batu_mc = new batu_mc(); // creates a instance of the movieclip, i.e, an object
var Batumc1:L = new L();
var Pisangmc:pisang_mc = new pisang_mc();
var P:Array = [new Point(80.2, 100), new Point(260, 100), new Point(430, 100)];
var M:Array = [Batumc, Batumc1, Pisangmc];
for(var i:uint=0; i<M.length; i++) {
var myClass:Class = getDefinitionByName("Batumc1"+i) as Class;
var mc:MovieClip = new myClass as MovieClip;
// Produce a random Point.
var anIndex:int = Math.random() * P.length;
var aPo:Point = P[anIndex];
// Remove the selected Point from its list.
P.splice(anIndex, 1);
mc.x = aPo.x;
mc.y = aPo.y;
}
where's my fault?

can you explain me as3 randomly swap shapes' positions

I copy some code and want to use it but I don't understand. this code is about How to randomly swap shapes' positions in specific locations. anyone can explain in simple how this code works?
function randomSort(a:*, b:*):Number
{
if (Math.random() < 0.5) return -1;
else return 1;
}
// Push 12 positions as new Point() in an array.
var positions:Array = [ new Point(12, 42), new Point(43, 56), new Point(43,87) ]; // ...add 12 positions
var mcs:Array = [mc1, mc2, mc3]; // ...add 12 mcs
positions.sort(randomSort);
// link randomized position to MovieClips:
for (var i:int = 0, l:int = positions.length; i < l, i++ ) {
var mc:MovieClip = mcs[i];
var point:Point = positions[i];
mc.x = point.x;
mc.y = point.y;
}
There are two lists: MovieClips and Points. The provided script randomizes one of the lists, so each MovieClip get a random Point out of the given ones.
The idea of random-sorting could be confusing a bit. The Array.sort() method is intended to organize Array's elements on given criteria, but if you give a random-based criteria instead, the elements are mixed with no predefined order.
The other (and probably more understandable) way to do the thing is to match a fixed MovieClip to a random Point, then remove matched pair from the respective lists, then proceed until there are items left.
var P:Array = [new Point(12, 42), new Point(43, 56), new Point(43,87)];
var M:Array = [mc1, mc2, mc3];
// Do while there are items to process.
while (M.length)
{
// Get the last MovieClip and remove it from the list.
var aMC:MovieClip = M.pop();
// Produce a random Point.
var anIndex:int = Math.random() * P.length;
var aPo:Point = P[anIndex];
// Remove the selected Point from its list.
P.splice(anIndex, 1);
// Move the selected MovieClip to the selected Point coordinates.
aMC.x = aPo.x;
aMC.y = aPo.y;
}

Randomising array coordinates with no duplicates AS3

very new to this kind of thing so please bear with me.
So basically I have 4 buttons that I have put to the stage using the Actions panel. They all have set coordinates so every time I run my game, they are in the same place.
Now here's my issue, I want these buttons to randomise their positions using those coordinates, but I often get duplicates, meaning one button is on top of another.
Here is my code so far
var coordArray : Array = [
new Point(44,420),
new Point(270,420),
new Point(44,550),
new Point(270,550),
];
var pointRange:Number = 4;
var randomPoint:int = Math.random()*pointRange;
answerButtons.x = coordArray[randomPoint].x;
answerButtons.y = coordArray[randomPoint].y;
var pointRange_2:Number = 4;
var randomPoint_2:int = Math.random()*pointRange_2;
answerButtons_2.x = coordArray[randomPoint_2].x;
answerButtons_2.y = coordArray[randomPoint_2].y;
var pointRange_3:Number = 4;
var randomPoint_3:int = Math.random()*pointRange_3;
answerButtons_3.x = coordArray[randomPoint_3].x;
answerButtons_3.y = coordArray[randomPoint_3].y;
var pointRange_4:Number = 4;
var randomPoint_4:int = Math.random()*pointRange_4;
answerButtons_4.x = coordArray[randomPoint_4].x;
answerButtons_4.y = coordArray[randomPoint_4].y;
I have googled this profusely and I keep getting answers to do with the splice and shift methods. Is this the type of thing I need? I'm assuming I need a function that removes a point from the array after it is used.
Cheers.
Just remove the coordinate from the list when you pick it randomly using splice:
var coordinates:Vector.<Point> = new <Point>[
new Point(44, 420),
new Point(270, 420),
new Point(44, 550),
new Point(270, 550)
];
function positionAtRandomCoordinate(object:DisplayObject):void {
var index:int = Math.random() * coordinates.length;
var coordinate:Point = coordinates.splice(index, 1)[0];
object.x = coordinate.x;
object.y = coordinate.y;
}
positionAtRandomCoordinate(answerButtons);
positionAtRandomCoordinate(answerButtons_2);
positionAtRandomCoordinate(answerButtons_3);
positionAtRandomCoordinate(answerButtons_4);

Interaction isn't translating input Text to Strings

I'm in need of some help. To start with, what I have is an interaction where you fill out 5 text boxes in response to 2 questions. Each of the 5 answers must be filled out as input text and then checked against an array of acceptable responses when the done button is clicked. Also, there are two type differences in the fields. So the first three answer fields belong to a range of acceptable responses in the array: Type A and the next two questions to Type B. It's possible to fill out the correct responses in any order, so long as the typing is correct.
What I can't seem to figure out is why the textFields aren't translating to Strings.
import flash.text.TextField;
import flash.events.MouseEvent;
stop();
//*--------------------------------------------
//
// THINGS YOU CAN CHANGE
//
//*--------------------------------------------
var a_inputType:Array = new Array("Doggie Day Spa", "Deb's Dog Walking Service", "Pet Market", "Pampered Pet", "TLC Grooming"); //All recognized type responses, Type A listed before Type B
var n_typeA:Number = new Number(3); //Sets the range for Type A
//*--------------------------------------------
//
// PAGE SETUP
//
//*--------------------------------------------
var n_typeB:Number = new Number(a_inputType.length - n_typeA +1); //Finds the range of Type B
var a_testArray:Array = new Array(); //Holds push data from submit button
var a_correctArray:Array = new Array(); //Creates an array to run a final test against
for(var c = 0; c<=a_inputType.length-1; c++){ //Loop populates the array
a_correctArray.push(1);
}
var inputField1:TextField = new TextField(); //Creates the Text Fields
var inputField2:TextField = new TextField();
var inputField3:TextField = new TextField();
var inputField4:TextField = new TextField();
var inputField5:TextField = new TextField();
var txtString1:String = new String(); //Creates the strings for translating the input text
var txtString2:String = new String();
var txtString3:String = new String();
var txtString4:String = new String();
var txtString5:String = new String();
for(var f = 1; f<=a_inputType.length; f++){ //Assigns them properties, locations, and adds a listener for text
var fieldBuilder = "inputField"+f;
var fieldFinder = "txt_pos"+f;
addChild(this[fieldBuilder]);
this[fieldBuilder].border = false;
this[fieldBuilder].width = 290;
this[fieldBuilder].height = 25;
this[fieldBuilder].x = this[fieldFinder].x;
this[fieldBuilder].y = this[fieldFinder].y;
this[fieldBuilder].type = "input";
this[fieldBuilder].multiline = true;
this[fieldBuilder].text = "";
this[fieldBuilder].addEventListener(TextEvent.TEXT_INPUT, function (){
var stringBuilder = "txtString"+f;
this[stringBuilder] = this[fieldBuilder].text;
});
}
//*--------------------------------------------
//
// FUNCTIONS
//
//*--------------------------------------------
function SUBMIT(event:MouseEvent):void{
for(var t=1; t<=a_inputType.length; t++){ //Loop establishes checks for each String against an input type
if(t<=n_typeA){ //if/else divides the textfields into two ranges: typeA and typeB
checkTypeA(this["txtString"+t], a_inputType); //sends the array of correct responses and the captured String to checkTypeA
}else{
checkTypeB(this["txtString"+t], a_inputType); //sends the array of correct responses and the captured String to checkTypeB
}
}
var TEMPSELECT = a_testArray.toString(); //reduces the testArray recieving push data into a String
var TEMPCORRECT = a_correctArray.toString(); //reduces the correctArray from scene set-up into a String
if(TEMPSELECT == TEMPCORRECT){ //compares the strings and determines a trace response
trace("correct");
}else{
trace("incorrect");
}
}
function checkTypeA(value:String, arr:Array){ //Checks the String against all the array values within the specified range for type A
for (var a=1; a<=n_typeA; a++){ //determines the range
if (arr[a]==value){ //checks the value
a_testArray.push(1); //if true, generates a push value for a testArray to be checked later
}
}
}
function checkTypeB(value:String, arr:Array){
for (var b = n_typeA; b<=n_typeB; b++){
if (arr[b-1]==value){
a_testArray.push(1);
}
}
}
//*--------------------------------------------
//
// BUTTONS
//
//*--------------------------------------------
done_bttn.addEventListener(MouseEvent.CLICK, SUBMIT); //Launches the SUBMIT function when "Done" is pressed.
Upon further investigation I've noticed that the loop isn't terminating when it reaches 5. It keeps regurgitating TextFields over and over again with the same variable names and instancing. Because of this, the addChild is dumping input fields one on top of one another in the flash file (which makes editing a text field impossible since your always clicking on a new field positioned directly on top of the one you just edited).
The trace on the loop comes back like this:
inputField1
txt_pos1
inputField2
txt_pos2
inputField3
txt_pos3
inputField4
txt_pos4
inputField5
txt_pos5
inputField1
txt_pos1
inputField2
txt_pos2
inputField3
txt_pos3
inputField4
txt_pos4
inputField5
txt_pos5
inputField1
txt_pos1
inputField2
txt_pos2
and so on.... how can I stop this looping behavior. I've tried if/else breaking and that's not working.
The context of the this keyword changes when you call it from a local function. You can easily verify it if you add trace(this) to your anonymous function. It will trace out [object global]. Two solutions come to mind, store a reference of this in a variable:
var self:MovieClip = this;
for(var f = 1; f<=a_inputType.length; f++){
//...
this[fieldBuilder].addEventListener(TextEvent.TEXT_INPUT, function (){
var stringBuilder = "txtString"+f;
self[stringBuilder] = self[fieldBuilder].text;
});
}
Or declare a new function:
for(var f = 1; f<=a_inputType.length; f++){
//...
this[fieldBuilder].addEventListener(TextEvent.TEXT_INPUT, myFunction);
}
function myFunction(t:TextEvent){
var stringBuilder = "txtString"+f;
this[stringBuilder] = (t.target as TextField).text;
}

addCircle to existing movieclip, using name of clip from an array

I am currently building a project where I have a map with a number of ship and aircraft. What I am trying to achieve is to check the Line of Sight distance between them.
I have set up a LOS Calculator which checks the height of one platform and the height of a second platform then gives a response. That works fine.
I then wanted to addCircle based on the result from this calculator. So if the result was 10 it would draw a circle 10cm in radius. If the result was 100 then it would draw it at 100, you get the picture. This works.
My problem now is that I need to be able to click on one platform either before or after I have made the calculation and the .addCircle be added to that movieClip. I have set up an array to store the movieclips instance names and traced that. I have added a field on stage so that you can click on a platform and it will recognise the platform clicked. I am just lost as to how to get the circle into the movieClip that has been clicked.
I am very new to AS3 so this is starting todo my head in. Any help would be greatly appreciated.
The code I have is attached below. I hope I have inserted this properly. Thanks again
import flash.events.MouseEvent;
import flash.display.MovieClip;
stage.focus=ht1;
// creation of array containing movieclips and code that adds the clicked movieclip to Array-platformClicked
var platformArray:Array = [arunta_mc, f15_mc];
var platformClicked = [];
var selectedPlatform:MovieClip = new MovieClip();
for(var i:int = 0; i < platformArray.length; i++) {
platformArray[i].buttonMode = true;
platformArray[i].addEventListener(MouseEvent.CLICK, item_onClick);
}
function item_onClick(event:MouseEvent):void {
var selectedPlatformArray:Array = platformArray.filter(checkName);
selectedPlatform = selectedPlatformArray[0];
myText.text = event.currentTarget.name + " was clicked";
var platformClicked = String(event.currentTarget.name);
trace(platformClicked);
}
function checkName(item:MovieClip, index:int, array:Array):Boolean
{
return(item.name == platformClicked);
}
//setup of LOS Calculator code
var counter:Number=1;
operator_txt.text = "+";
ht1.restrict="-0123456789.";
ht2.restrict="-0123456789.";
var myresult:Number;
var test = [];
//start of code when equal button is pressed
equal_btn.addEventListener(MouseEvent.CLICK, equalhandler);
var newCircle:Shape = new Shape();//defines circle to be drawn
function equalhandler(event:MouseEvent):void{
newCircle.graphics.lineStyle(1, 0x000000);
newCircle.graphics.beginFill(0x435632);
newCircle.alpha = .1;
//start of result code
result_txt.text = String(int((1.23*(Math.sqrt(Number(parseFloat(ht1.text)+parseFloat(ht2.text)+""))))));
var test = String(int((1.23*(Math.sqrt(Number(parseFloat(ht1.text)+parseFloat(ht2.text)+""))))));
trace(test);
//end of result code
newCircle.graphics.drawCircle(0,0,test);//add circle based on LOS calculation
newCircle.graphics.endFill();
//var selectedPlatform:MovieClip = selectedPlatformArray[0];
selectedPlatform.addChild(newCircle);//this is where I need to add newCircle to the movieClip that is clicked
trace(selectedPlatform);
//trace(platformClicked);
}
//start of code for the clear button
clear_btn.addEventListener(MouseEvent.CLICK, clearhandler);
function clearhandler(event:MouseEvent):void{
ht1.text=ht2.text=result_txt.text="";
removeChild(newCircle);
var test = [];
}
You can use the filter() method to check each item's name, like so:
var selectedPlatformArray:Array = platformArray.filter(checkName);
and somewhere in your code, define the checkName function
function checkName(item:MovieClip, index:int, array:Array):Boolean
{
return (item.name == platformClicked);
}
selectedPlatformArray will now contain all elements that return true for the checkName function, and as long as you don't have multiple MovieClips with the same name the array should only contain one element, which you can retrieve simply by accessing the first element of the array:
var selectedPlatform:MovieClip = selectedPlatformArray[0];
Alternatively, you can also use the getChildByName() function, like so:
var selectedPlatform:MovieClip = stage.getChildByName(platformClicked);
However this depends on where the objects are added to, and if they're not all in the same container (or not added at all), then this isn't the best option. It's a quick and simple solution for small projects though.
Anyway, whatever method you use you can then easily add the circle to it in your equalHandler function as usual:
selectedPlatform.addChild(newCircle);
I'd recommend checking out the documentation for both filter() and getChildByName(), to get a better understanding of how they work, since my examples only showed how you'd use them in this specific situation.
Complete code that you should have:
import flash.events.MouseEvent;
import flash.display.MovieClip;
stage.focus=ht1;
// creation of array containing movieclips and code that adds the clicked movieclip to Array-platformClicked
var platformArray:Array = [arunta_mc, f15_mc];
var platformClicked:String = "";
var selectedPlatform:MovieClip = new MovieClip();
for(var i:int = 0; i < platformArray.length; i++) {
platformArray[i].buttonMode = true;
platformArray[i].addEventListener(MouseEvent.CLICK, item_onClick);
}
function item_onClick(event:MouseEvent):void {
var selectedPlatformArray:Array = platformArray.filter(checkName);
selectedPlatform = selectedPlatformArray[0];
myText.text = event.currentTarget.name + " was clicked";
platformClicked = String(event.currentTarget.name);
trace(platformClicked);
}
function checkName(item:MovieClip, index:int, array:Array):Boolean
{
return(item.name == platformClicked);
}
//setup of LOS Calculator code
var counter:Number=1;
operator_txt.text = "+";
ht1.restrict="-0123456789.";
ht2.restrict="-0123456789.";
var myresult:Number;
var test:String = "";
//start of code when equal button is pressed
equal_btn.addEventListener(MouseEvent.CLICK, equalhandler);
var newCircle:Shape = new Shape();//defines circle to be drawn
function equalhandler(event:MouseEvent):void{
newCircle.graphics.lineStyle(1, 0x000000);
newCircle.graphics.beginFill(0x435632);
newCircle.alpha = .1;
//start of result code
result_txt.text = String(int((1.23*(Math.sqrt(Number(parseFloat(ht1.text)+parseFloat(ht2.text)+""))))));
test = String(int((1.23*(Math.sqrt(Number(parseFloat(ht1.text)+parseFloat(ht2.text)+""))))));
trace(test);
//end of result code
newCircle.graphics.drawCircle(0,0,test);//add circle based on LOS calculation
newCircle.graphics.endFill();
//var selectedPlatform:MovieClip = selectedPlatformArray[0];
selectedPlatform.addChild(newCircle);//this is where I need to add newCircle to the movieClip that is clicked
trace(selectedPlatform);
//trace(platformClicked);
}
//start of code for the clear button
clear_btn.addEventListener(MouseEvent.CLICK, clearhandler);
function clearhandler(event:MouseEvent):void{
ht1.text=ht2.text=result_txt.text="";
selectedPlatform.removeChild(newCircle);
test = "";
}