Arranging items in an inventory - actionscript-3

I'm working on an inventory system I made following a short tutorial that leaves you stranded. I've managed to get the items removed and rearrange to the correct order somewhat. For some reason though, if I click on the last item in my inventory, then on the first item, the items do not rearrange correctly.
public class Inventory {
var itemsInInventory:Array;
var inventorySprite:Sprite;
var itemNum:int;
public function Inventory(parentMC:MovieClip) {
itemNum=0;
itemsInInventory = new Array();
inventorySprite = new Sprite();
inventorySprite.x = 50;
inventorySprite.y = 360;
parentMC.addChild(inventorySprite);
}
public function makeInventoryItems(arrayOfItems:Array){
for(var i:int = 0; i < arrayOfItems.length; i++){
arrayOfItems[i].addEventListener(MouseEvent.CLICK, getItem);
arrayOfItems[i].buttonMode = true;
}
}
public function getItem(e:MouseEvent){
var item:MovieClip = MovieClip(e.currentTarget);
itemsInInventory.push(item);
inventorySprite.addChild(item);
item.x = (itemsInInventory.length-1)*40;
item.y = 0;
item.removeEventListener(MouseEvent.CLICK, getItem);
item.addEventListener(MouseEvent.CLICK, useItem);
}
public function useItem(e:MouseEvent){
var item:MovieClip = MovieClip(e.currentTarget);
itemNum = item.x;
inventorySprite.removeChild(item);
itemsInInventory.splice(item, 1);
sortInventory();
}
public function sortInventory(){
for(var i:int = 0; i < itemsInInventory.length; i++){
if(itemsInInventory[i].x > itemNum){
itemsInInventory[i].x -= 40;
}
}
itemNum=0;
}
}
I belive thats all the coding info I need to provide for help solving this mystery.
Also, a link to the game for testing. If you would like a link for a download of the game, please ask.
LINK

Instead of substracting 40px, just set their position again:
for(var i:int = 0; i < itemsInInventory.length; i++){
itemsInInventory[i].x = i*40;
}
Also, I did not even know that it is possible to give an object reference to the splice function, I would rather use:
itemsInInventory.splice(itemsInInventory.indexOf(item), 1);
And remove the event listener from the item when you delete it from the inventory in the useItem function.
item.removeEventListener(MouseEvent.CLICK, useItem);
EDIT:
With Flash Player 10, Adobe introduced the Vector class which is kind of the same as the Array class, but it can only store one data type. In your case it would be MovieClip or Sprite. The Vector class is singificantly faster and more developer friendly because you can see the help from the IDE when you are typing myVector[i].. I recommend using that instead, although there is nothing wrong with Array. It is just outdated a bit, but is helpful when you want to store more data types.
myVector:Vector.<MovieClip> = new Vector.<MovieClip>();

Related

How to make housie / bingo game in Flash AS3

It shows an error when written this script has a package that cannot be nested how can I resolve the problem.
If not can anyone give me a new code so that I can try to make the new file?
I have this file in previous stack AS3 Bingo ticket generator
but i couldnt understan how to use it.
package {
import flash.display.Sprite;
import flash.text.TextField;
public class Main extends Sprite{
public var boards:Array = new Array();
private static const AMAUNT_BOARDS:uint = 6;
private static const NUMBER_FIELD_SIZE:uint = 20;
public function Main() {
for(var i:uint = 0; i < AMAUNT_BOARDS; i++)
{
var numbers:Array = genNumbers();
numbers = deleteFields(numbers);
var board:Sprite = getBoard(numbers);
board.y = NUMBER_FIELD_SIZE * 4 * i;
boards.push(board);
addChild(board);
}
}
//generates a 2 Dimensional Array (3x9) with TextFields
//populates the according Numbers and returns a board Sprite
private function getBoard(n:Array):Sprite
{
var s:Sprite = new Sprite();
var a:Array = new Array();
for(var i:uint = 0; i < 3; i++)
{
var b:Array = new Array();
for(var k:uint = 0; k < 9; k++)
{
//create TextFields
var tf:TextField = new TextField();
tf.x = k * NUMBER_FIELD_SIZE;
tf.y = i * NUMBER_FIELD_SIZE;
tf.border = true;
tf.width = NUMBER_FIELD_SIZE;
tf.height = NUMBER_FIELD_SIZE;
if(n[k][i] != 0) // adds the number if the value isn't 0
tf.text = n[k][i]; // Note that i am switching k & i because the number Array is 9x3
b.push(tf);
s.addChild(tf);
}
}
return s;
}
// Turns 4 random numbers out of the lines into 0 And returns the Array
private function deleteFields(a:Array):Array
{
for(var i:uint = 0; i < 3; i++)
{
var r:RandomPlus = new RandomPlus(8,0);
for(var k:uint = 0; k < 4; k++)
{
var t:uint = r.getNum();
a[t][i] = 0;
}
}
return a;
}
// Generates and returns a 2 Dimensional Array (9x3) with random numbers
private function genNumbers():Array
{
var a:Array = new Array();
var st:uint = 1;
var en:uint = 9;
for(var i:uint = 0; i < 9; i++)
{
var line:Array = new Array();
var ran:RandomPlus = new RandomPlus(en,st);
if(i == 0)//accounting for the number differnenz at start
st--;
if(i==7)//accounting for the number differnenz at end
en ++;
st += 10;
en += 10;
for(var e:uint = 0; e < 3; e++)
line[e] = ran.getNum();
a.push(line);
}
return a;
}
}
}
TL;DR: "Main" in the class definition may have to be changed conflict of already existing name. Extends sprite may need to be changed to extends movieclip. RandomPlus either needs an import you don't have or needs to be made into a symbol and exported to Actionscript.
Ok, so a few things:
If you are really putting the code into the stage code area, then you can't use the private identifier.
Unless RandomPlus is an object that you have defined in the stage it is probably either not a method you can use or you don't have the right imports for it. Look up what imports you need for RandomPlus or if it is an object defined in the stage then you may need to turn it into a symbol or if you have already export it to flash ActionScript I think. To do this you have to check the checkbox in the middle of the symbol creation page. It will always give you the error when you do this, but don't worry it is fine that way.
Third thing is that I never extend sprite in the class definition, I always do extends movieclip(not sure of the capitalization, but you can look that up). You may also be running into an error from using "Main" as the name because it may be a conflict with a name or method already defined in flash in general.
One last thing is for the variable declaration(mostly just for making the code more readable). While it is good to not declare variables as global when you don't have to, I tend to like having most of the variables up at the top, because I like to be able to see most of the declarations in one space. It's not necessary, really just a personal opinion, and I know a lot of experienced coders will say to do what you did, but if you want to use the arrays in multiple functions then sometimes it is easier to just declare them globally rather than having to pass a million things in the function call and then having to figure out later where all the variable declarations are called and where they are being passed as arguments. Again it's more of a coder's choice, but you can also just do whatever you feel more comfortable with rather than just following the already laid out rules by people who have more experience coding.
Another optional fix to the organization might be to name variables something meaningful so as to not forget what they are all doing. I am bad at naming as well, but I think it's really better to name them something better than just a single letter or two.
Another thing that can help is placing trace(code or "text"); in different places to see what's going wrong once you have the compiler happy.

How to compare properties of objects inside a vector?

I have a couple of display objects moving around the screen, the all belong to the same Vector.
I would like to create a function that lets me pick an object with the lowest x value at the moment the function is called.
This is quite easy and if you're into programming, you should be able to do it yourself, but if you're a beginner, I'll give you some code:
var vec:Vector.<DisplayObject> = new Vector.<DisplayObject>();
function getLowestXObject():DisplayObject
{
var minX:DisplayObject = vec[0];
for(var i:int = 1; i < vec.length; i++)
{
if(minX.x > vec[i].x)
{
minX = vec[i];
}
}
return minX;
}

randomize buttons on in as3 from array

I'm pretty novice to flash 5.5, im trying to build a quiz for my elementary students.
So far I have made the layout, created the image buttons, and I used to as3 to advance the quiz.
So what I'm, looking for is the ability to shuffle the image buttons/answers. Here is a sample of what i have so far.
the red ______
apple (button of apple) boy (button of boy) pineapple (button with pineapple)
In my example, the pictures are buttons, the correct answer is apple. I have tried to create an array, after hours of google searches. This is my code, I'm doing something wrong but I have no idea what. Please help.
Please help.
function Main() {
var button:Array = [];
button.push("choice1");
button.push("choice2");
button.push("choice3");
ShuffleArray(button);
trace(button);
}
function ShuffleArray(button:Array)
{
for (var i:int = button.length-1; i >=0; i--)
{
var randomIndex:int = Math.floor(Math.random()*(i+1));
var itemAtIndex:Object = button[randomIndex];
button[randomIndex] = button[i];
button[i] = itemAtIndex;
thanks in advance.
thanks in advance.
Try something more like this:
protected var button:Array=[choice1, choice2, choice3];//note no quotes, puts in the actual objects
function Main() {
super();
randomArray=shuffleArray(button);
var prevX:int = 0;
var space:int = 10;
//places the buttons from left to right in the order
//they were in the random array
//uses existing y
for (var i:int=0; i<randomArray.length; i++) {
var btn:DisplayObject = randomArray[i] as DisplayObject;
btn.x = prevX;
prevX = btn.x + btn.width + space;
}
}
protected function shuffleArray(inArray:Array):Array {
//create copy of array so as not to alter it
var tempArray = new Array().concat(inArray);
//resultarray (we'll be destroying the temp array)
var resultArray:Array = [];
while(tempArray.length>0) {
var index:int = int(Math.random() * tempArray.length);
//delete object from random location and put it into result array
resultArray.push(tempArray.splice(index, 1)[0]);
}
return resultArray;
}
Note this assumes you're using a document Class and that your buttons are already on the stage at the same y position.

ActionScript 3.0 Changing Direction

Alright let me make this clear. I am just doing out of interest. This is not a homework. I am doing it because I am interest in writing the ActionScript. I saw a guy website doing something amazing so I tried to copy and I want to do this:
Oh by the way you need to make a symbol and need to export for ActionScript and class name is "ball". And the button instant name is:bButton. So here's the script I wrote so far.
var boundaryRight:Number = stage.stageWidth;
var boundaryLeft:Number = 0;
var balls:Array;
var reverseRight:Number = 0;
var reverseLeft:Number = stage.stageWidth;
init();
function init(){
balls = new Array();
for(var i:Number = 0; i<10; i++){
var myBall:ball = new ball();
myBall.x=(Math.random()*boundaryRight);
myBall.y=50+i*40;
addChild(myBall);
balls.push(myBall);
}
}
addEventListener(Event.ENTER_FRAME,moveBall);
function moveBall(e:Event){
for(var i:Number = 0;i<10;i++){
var myBall:ball = balls[i];
myBall.x-=20;
if(myBall.x<boundaryLeft){
myBall.x=boundaryRight;
}
}
}
As you can see that code made the multiple ball go to left and looping over and over again. So here's what I want to do. I want to make a button and when I click the button it'll change direction like click and it change direction to right. I click it again and it'll go left again. How do I write the code for that?
Use two global variables direction and speed.
var direction:Number = 1;
var speed:Number = 20;
Instead of giving myBall.x-=20;
Give myBall.x += ( direction * speed );
In the click handling function of the button
Give direction *= -1;
You can also change speed like this.

Multiple movieclips all go to the same spot; What am i doing wrong?

So I'm trying to shoot multiple bullets out of my body and it all works except I have an odd problem of just one bullet showing up and updating to set position for the new ones.
I have a move able player thats supposed to shoot and I test this code by moving the player and shooting. Im taking it step by step in creating this.
The result of tracing the bulletContainer counts correctly in that its telling me that movieclips ARE being added to the stage; I Just know it comes down to some kind of logic that im forgetting.
Here's My Code (The Bullet it self is a class)
UPDATE*
Everything in this code works fine except for I stated earlier some code seems reduntned because I've resorted to a different approaches.
BulletGod Class:
public class bulletGod extends MovieClip{
//Register Variables
//~Global
var globalPath = "http://127.0.0.1/fleshvirusv3/serverside/"
//~MovieCLips
var newBullet:bulletClass = new bulletClass();
//~Boolean
var loadingBulletInProgress:Number = 0;
var shootingWeapon:Number = 0;
//~Timers
var fireBulletsInterval = setInterval(fireBullets, 1);
var bulletFireEvent;
//~Arrays
var bulletArray:Array = new Array();
var bulletType:Array = new Array();
var bulletContainer:Array = new Array();
//~Networking
var netBulletRequest:URLRequest = new URLRequest(globalPath+"bullets.php");
var netBulletVariables:URLVariables = new URLVariables();
var netBulletLoader:URLLoader = new URLLoader();
//~Bullet Image Loader
var mLoader:Loader = new Loader();
var mRequest:URLRequest = new URLRequest();
public function bulletGod() {
//Load every bullet for every gun
//Compile data to be requested
netBulletVariables.act = "loadBullets"
netBulletRequest.method = URLRequestMethod.POST
netBulletRequest.data = netBulletVariables;
netBulletLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
netBulletLoader.addEventListener(Event.COMPLETE, getBulletImages);
netBulletLoader.load(netBulletRequest);
}
private function getBulletImages(bulletImageData:Event){
//Request every bullet URL image
//Set vars
var bulletData = bulletImageData.target.data;
//Load images
for(var i:Number = 0; i < bulletData.numBullets; i++){
bulletArray.push(bulletData["id"+i.toString()]);
bulletType.push(bulletData["bullet"+i.toString()]);
//trace(bulletData["id"+i]+"-"+bulletData["bullet"+i]);
}
//All the arrays have been set start firing the image loader/replacer
var imageLoaderInterval = setInterval(imageReplacer, 10);
}
private function imageReplacer(){
//Check to see which image needs replacing
if(!loadingBulletInProgress){
//Begin loading the next image
//Search for the next "String" in the bulletType:Array, and replace it with an image
for(var i:Number = 0; i < bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//Load this image
mRequest = new URLRequest(globalPath+"ammo/"+bulletType[i]);
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadImage);
mLoader.load(mRequest);
//Stop imageReplacer() while we load image
loadingBulletInProgress = 1;
//Stop this for() loop while we load image
i = 999;
}
}
}
}
private function loadImage(BlackHole:Event){
//Image has loaded; find which array slot it needs to go into
for(var i:Number = 0; i <= bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//We found which array type it belongs to; now replace the text/url location with the actual image data
var tmpNewBullet:MovieClip = new MovieClip;
tmpNewBullet.addChild(mLoader);
//Add image to array
bulletType[i] = tmpNewBullet;
//Restart loadingBullets if there are more left
loadingBulletInProgress = 0;
//Stop for() loop
i = 999;
}
}
}
//###############################################################################################################################################
private function fireBullets(){
//If player is holding down mouse; Fire weapon at rate of fire.
if(shootingWeapon >= 1){
if(bulletFireEvent == null){
//Start shooting bullets
bulletFireEvent = setInterval(allowShooting, 500);
}
}
if(shootingWeapon == 0){
//The user is not shooting so stop all bullets from firing
if(bulletFireEvent != null){
//Strop firing bullets
clearInterval(bulletFireEvent);
bulletFireEvent = null
}
}
}
private function allowShooting(){
//This function actually adds the bullets on screen
//Search for correct bullet/ammo image to attach
var bulletId:Number = 0;
for(var i:Number = 0; i < bulletArray.length; i++){
if(bulletArray[i] == shootingWeapon){
//Bullet found
bulletId = i;
//End For() loop
i = 999;
}
}
//Create new bullet
//Create Tmp Bullet
var tmpBulletId:MovieClip = new MovieClip
tmpBulletId.addChild(newBullet);
tmpBulletId.addChild(bulletType[bulletId]);
//Add To Stage
addChild(tmpBulletId)
bulletContainer.push(tmpBulletId); //Add to array of bullets
//Orientate this bullet from players body
var bulletTmpId:Number = bulletContainer.length
bulletTmpId--;
bulletContainer[bulletTmpId].x = Object(root).localSurvivor.x
bulletContainer[bulletTmpId].y = Object(root).localSurvivor.y
//addChild(bulletContainer[bulletTmpId]);
}
//_______________EXTERNAL EVENTS_______________________
public function fireBullet(weaponId:Number){
shootingWeapon = weaponId;
}
public function stopFireBullets(){
shootingWeapon = 0;
}
}
}
BulletClass:
package com{
import flash.display.*
import flash.utils.*
import flash.net.*
import flash.events.*
public class bulletClass extends MovieClip {
public var damage:Number = 0;
public function bulletClass() {
//SOME MOVEMENT CODE HERE
}
public function addAvatar(Obj:MovieClip){
this.addChild(Obj);
}
}
}
Well ... if I may say so, this code looks quite wrong. Either something is missing from the code or this code will never make the bullets fly.
First off, you can set x and y of the new bullet directly (replace everything after "orientate this bullet from players body" with this):
tmpBulletId.x = Object(root).localSurvivor.x;
tmpBulletId.y = Object(root).localSurvivor.y;
Perhaps this already helps, but your code there should already do the same.
But to let these bullets fly into any direction, you also need to add an event listener, like so:
tmpBulletId.addEventListener(Event.ENTER_FRAME, moveBullet);
function moveBullet(e:Event) {
var movedBullet:MovieClip = MovieClip(e.currentTarget);
if (movedBullet.x < 0 || movedBullet.x > movedBullet.stage.width ||
movedBullet.y < 0 || movedBullet.y > movedBullet.stage.height) {
// remove move listener, because the bullet moved out of stage
movedBullet.removeEventListener(Event.ENTER_FRAME);
}
// remove the comment (the //) from the line that you need
MovieClip(e.currentTarget).x += 1; // move right
// MovieClip(e.currentTarget).y -= 1; // move up
// MovieClip(e.currentTarget).x -= 1; // move left
// MovieClip(e.currentTarget).y += 1; // move down
}
This example lets your bullet fly to the right. If you need it flying into another direction, just comment out the line with the "move right" comment and uncomment one of the other lines.
This is of course a very simple example, but it should get you started.
I hope this helps, and that my answer is not the wrong answer to the question.
As far as I have expirienced it you can have only one copy of MovieClip object added to specific child. Best approach is to use ByteArray for the clip source and instantiate new MovieClip and pass the ByteArray as a source. It have something to do with child/parent relation since a DisplayObject can have only one parent (and a way to detach the object from scene too).
Well i ended up writeing the whole code from scratch for a 3rd time and ran into a similar problem and just for reference to anybody else that comes to a problem thats random as this one i found that problem was likly does to a conversion error somewhere that doesn't necessarily break any compiling rules. Just that i was calling a movieclip and not the class it self.