Developing A Loop To Solve Powers In Kotlin Android - loops

**I have been given an assignment which I have been stuck on for the last few weeks as I have no clue on where to proceed on how to do it.
The Question is as Follows:
The app must be able to calculate powers. For example, if the user enters 2 and 3,
the calculation should be 23. Do this calculation by using a loop, to calculate 2 x 2 x 2.
Use the notation 2^3 = 8 for the display>
Here Is the code that I managed to do for the rest of the app **
package com.example.poepart1_1
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.lang.Math.sqrt
class MainActivity : AppCompatActivity() {
private lateinit var num1: EditText // User Entered Variable 1
private lateinit var num2: EditText // User Entered Variable 2
private lateinit var add: Button // The addition Button
private lateinit var minus: Button // The Subtraction Button
private lateinit var multiply: Button // The Multiplication Button
private lateinit var division: Button // The division Button
private lateinit var sqroot: Button
private lateinit var power: Button
private lateinit var output: TextView // The Text View Output that displays the answer to the given sum.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Linking all attributes and finding their ID's that I have assigned them to in the .xml file
num1 = findViewById(R.id.num1)
num2 = findViewById(R.id.num2)
add = findViewById(R.id.add)
minus = findViewById(R.id.minus)
multiply = findViewById(R.id.multiply)
division = findViewById(R.id.division)
sqroot = findViewById(R.id.sqroot)
power = findViewById(R.id.power)
output = findViewById(R.id.output)
power.setOnClickListener {
if (num1.text.toString() == "0") {
Toast.makeText(this, "You Cannot Use 0 As A Power. Please Enter A Different Value", Toast.LENGTH_LONG).show()
}else{
val num = num1.text.toString().toInt()
val num2 = num2.text.toString().toInt()
val result = "$num ^ $num2 ="
output.text = "$result"
}
}
}
}```

Related

Putting an object into an array in as3

So I'm trying to create a row of ten buttons using a for loop that create a new button every time it runs, changing the x value each time. However ever each time a button is created i want it to be put into a specific array so i can refer to a specific button later on. However I'm not sure how to put objects into arrays. Is it possible to do this? This is the code I have so far:
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class backgound extends MovieClip {
var btnx = 30;
var btny= 20;
var row1:Array = [];
public function backgound() {
// constructor code
var continueBtn:Button;
for(var i=0; i < 10; i++)
{
continueBtn = new Button();
continueBtn.x = btnx;
continueBtn.y = 100;
continueBtn.width = 30;
continueBtn.height = 20;
continueBtn.border = true;
continueBtn.visible = true;
continueBtn.label = "Continue";
addChild(continueBtn);
btnx += 30;
}
}
}
}
in your loop:
myArray.push(continueBtn);
or in your loop:
continueBtn =myArray[i]= new Button();
or many other ways.
now you can access your buttons:
myArray[3]// gets the 4th item in your array
I just wonder, is this ALL you want?
I  H☺P E  this helps !

Action Script 3. Assign Movie Clips to other Movie Clips

So I'm creating game where will be shown world map with active countries as buttons and in top of screen should randomly pop-up product which should be assigned to specific country. Idea of game is that player should answer from which country this product Is, If answer correct should pop-up other product with assigned country.
So I have to create each country and products as MovieClips, just how to assign to each products correct country? If country clicked It should check If products correct.
I need to put all countries to one array and products to other array? Just I'm confused how to make that checking.
package
{
Import Object1;
Import Object2;
//all objects...
Import Canada;
//all countries...
public class MapGame extends MovieClip
{
private var object1:Object1;
private var object2:Object2;
private var object3:Object3;
private var object4:Object4;
private var object5:Object5;
//etc.....
private var canada:Canada;
private var lithuania:Lithuania;
private var uk:UK;
private var italy:Italy;
//etc.....
private function CreateMap()
{
//Here should be code to add countries as buttons
}
private function SpawnProduct()
{
//Here should be code to spawn random Object
}
private function CheckProducts()
{
// Here should be checking If products correct.
}
Also should be ability to assign multiple products to one country.
I will try to help you.
Firstly let's create two Object's.
private var _countries:Object = {};
private var _objects:Object = {};
_countries assigns an objects to the country. Example:
_countries[USA] = [object1, object2, object3];
So, USA contains three objects.
Same for the object:
_objects[object1] = [USA, Italy, UK];
Next. This is a function that assigns an objects to the country and vice versa.
public function assignCountryAndObject(country:MovieClip, object:MovieClip):void
{
if (_countries[country] is Array && _countries[country].indexOf(object) == -1)
_countries[country].push(object);
else
_countries[country] = [object];
if (_objects[object] is Array && _objects[object].indexOf(country) == -1)
_objects[object].push(country);
else
_objects[object] = [country];
}
So you can call this method this way:
assignCountryAndObject(country1, obj3);
assignCountryAndObject(country2, obj2);
assignCountryAndObject(country2, obj4);
assignCountryAndObject(country2, obj2);
assignCountryAndObject(country3, obj4);
assignCountryAndObject(country3, obj1);
assignCountryAndObject(country3, obj2);
Next two functions are used to get all countries of an object or all objects of the country.
public function getCountriesOfObject(object:MovieClip):Array
{
return _objects[object];
}
public function getObjectsOfCountry(country:MovieClip):Array
{
return _countries[country];
}
For checking you can use next functions:
This function checks is object belongs to the country:
public function isObjectBelongsCountry(object:MovieClip, country:MovieClip):Boolean
{
return _objects[object].indexOf(country) != -1;
}
This function checks is country belongs to an object:
public function isCountryBelongsObject(country:MovieClip, object:MovieClip):Boolean
{
return _countries[country].indexOf(object) != -1;
}
I would suggest using one array of items with all necessary information about countries and their products. Each element of that array should hold country name and array of products associated with that country. This is an example of what I'm talking about:
package
{
import flash.display.MovieClip;
public class Main extends MovieClip
{
//Array that holds a country name and the array of products associated woth that country
//(each item is an instance of Item.as)
private var allItems:Array;
public function Main()
{
this.allItems = new Array();
//Create all items
var item1:Item = new Item("Italy", ["Pizza", "Pasta"]);
var item2:Item = new Item("Lithuania", ["Šaltibarsčiai"]);
//Push those items into main allItems array
this.allItems.push(item1, item2);
//This traces all information in allItems array
for(var i:int = 0; i < allItems.length; i++)
{
trace("Country:", allItems[i].country + ", " + "Products:", allItems[i].products);
}
}
}
}
And the Item.as class:
package
{
import flash.display.MovieClip;
public class Item
{
public var country:String;
public var products:Array;
public function Item(country:String, products:Array)
{
this.country = country;
this.products = products;
}
}
}
I should also add that country and products doesn't necessarily have to be String's. They can be anything you want, like say MovieClips.
Linkėjimai :)

How can I access multiple ToggleButtons created in a class?

I have a GridPane (6x9) made with SceneBuilder. Inside that GridPane I created 50 ToggleButtons in my controller with the following code:
#FXML
private void initialize() {
Font numbersFont = new Font("Arial", 10);
for (int y = 0; y < 9; y++){
for (int x = 1; x < 7; x++) {
Integer buttonId = (y * 6) + x;
if (buttonId == 51) {break;}
ToggleButton tb = new ToggleButton(Integer.toString(buttonId));
tb.setId("tb_" + Integer.toString(buttonId));
tb.setFont(numbersFont);
tb.setPrefSize(27, 27);
tb.setAlignment(Pos.CENTER);
tb.selectedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
boolean isSelected = newValue;
System.out.println(isSelected);
}
});
numbersGrid.add(tb, x - 1, y);
}
}
}
In my MainApp.java I've created an array of integers:
private ObservableIntegerArray selectedNumbers = FXCollections.observableIntegerArray();
I have two questions.
I want is to update the selectedNumbers array with the numbers of the ToggleButtons that are pressed. For example, if I press button 1, 13 and 25, the array should be [1, 13, 25]. When I "turn off" a button, that number should be removed from the array. How can I add and remove those values? Where should I have this code? Inside the initialize method?
I have a method that randomly picks N numbers from the 50 available (1 to 50). When the user clicks a button, I want the ToggleButtons with that number to be "turned on". I know how to do a loop but how can I access the buttons? I mean, I named them tb_1, tb_2 and so on. So... how can I call them?
Thanks!
I would recommend creating and exposing an ObservableSet<Integer> in the controller, representing the set of selected toggles. This is pretty straightforward to do using the code you already have:
public class MyController {
private final ObservableSet<Integer> selectedToggles = FXCollections.observableSet();
public final ObservableSet<Integer> getSelectedToggles() {
return selectedToggles ;
}
#FXML
private void initialize() {
Font numbersFont = new Font("Arial", 10);
for (int y = 0; y < 9; y++){
for (int x = 1; x < 7; x++) {
Integer buttonId = (y * 6) + x;
if (buttonId == 51) {break;}
ToggleButton tb = new ToggleButton(Integer.toString(buttonId));
tb.setId("tb_" + Integer.toString(buttonId));
tb.setFont(numbersFont);
tb.setPrefSize(27, 27);
tb.setAlignment(Pos.CENTER);
tb.selectedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
boolean isSelected = newValue;
if (isSelected) {
selectedToggles().add(buttonId);
} else {
selectedToggles().remove(buttonId);
}
}
});
numbersGrid.add(tb, x - 1, y);
}
}
}
}
Then in your main application (or wherever you need) you can retrieve the observable set and register a listener with it:
FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/fxml"));
Parent parent = loader.load();
MyController controller = loader.getController();
controller.getSelectedToggles().addListener((Change<? extends Integer> change) -> {
ObservableSet<Integer> selectedToggles = controller.getSelectedToggles();
// process selected ids...
});
To be able to manipulate the toggle buttons state (e.g. to initialize them to your random values), you can make each button respond to changes in the observable set. In the code where you create the toggle button (in the controller), add this:
// existing code:
ToggleButton tb = new ToggleButton(Integer.toString(buttonId));
tb.setId("tb_" + Integer.toString(buttonId));
// respond to changes in observable set:
selectedToggles.addListener((Change<? extends Integer> change) ->
tb.setSelected(selectedToggles.contains(buttonId)));
Then you can manipulate the toggle button state with
List<Integer> initiallySelected = ... ;
controller.getSelectedToggles().clear();
controller.getSelectedToggles().addAll(initiallySelected);
1:
Don't use arrays like that. If doing something like that, use an ArrayList!
I suggest using an array with 50 boolean indices boolean[] myArray = boolean[50]; and setting the indices true or false.
You would have it loop over the entire array and use the array's values on initialization. You then add an event listener to the buttons to run it again whenever the user toggles a value.
2:
Add all your buttons to an array and get them by index. As they will be referenced (and not copied) this will have no impact on performance, perhaps the memory usage increases by a few kilobits, but that'll be it.

#1009: Cannot access a property or method of a null object reference. with random dropping squares

i am rebuilding a top down shooter form a .fla files with actions in it to a separate .as file
managed to fix allot of problems with is but i stumbled upon a problem with a function that drops random squares in to a particleContainer and adds them to stage to float down.
when the page is loaded is get allot of
TypeError: Error #1009: Cannot access a property or method of a null object reference. at Level/generateParticles()
i really hope someone can help me fix this! and show me where i made a mistake, i have tried allot of things already but none of them seem to work:(
package {
import playerAuto
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.filters.BlurFilter;
import flash.utils.Timer;
import flash.text.TextField;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.utils.*;
import flash.display.Shape;
import flash.display.DisplayObject
/**
*
*/
public class Level extends Sprite
{
//these booleans will check which keys are down
public var leftIsPressed:Boolean = false;
public var rightIsPressed:Boolean = false;
public var upIsPressed:Boolean = false;
public var downIsPressed:Boolean = false;
//how fast the character will be able to go
public var speed:Number = 5;
public var vx:Number = 0;
public var vy:Number = 0;
//how much time before allowed to shoot again
public var cTime:int = 0;
//the time it has to reach in order to be allowed to shoot (in frames)
public var cLimit:int = 12;
//whether or not the user is allowed to shoot
public var shootAllow:Boolean = true;
//how much time before another enemy is made
public var enemyTime:int = 0;
//how much time needed to make an enemy
//it should be more than the shooting rate
//or else killing all of the enemies would
//be impossible :O
public var enemyLimit:int = 16;
//the PlayerAuto's score
public var score:int = 0;
//this movieclip will hold all of the bullets
public var bulletContainer:MovieClip = new MovieClip();
//whether or not the game is over
public var gameOver:Boolean = false;
private var PlayerAuto:playerAuto = new playerAuto;
// publiek toegangkelijke verwijzing naar deze class
public static var instance:Level;
public var particleContainer:MovieClip = new MovieClip();
// constructor code
public function Level()
{
instance = this;
PlayerAuto.x = 200;
PlayerAuto.y = 100;
addChild(this.PlayerAuto);
Project.instance.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
Project.instance.stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
Project.instance.stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
Project.instance.stage.addEventListener(Event.ENTER_FRAME, generateParticles);
drieButton.addEventListener( MouseEvent.CLICK, loadScreenThree );
//checking if there already is another particlecontainer there
if(particleContainer == null)
{
//this movieclip will hold all of the particles
addChild(this.particleContainer);
}
}
function keyDownHandler(e:KeyboardEvent):void {
switch(e.keyCode) {
case Keyboard.LEFT : leftIsPressed = true; break;
case Keyboard.RIGHT : rightIsPressed = true; break;
case Keyboard.UP : upIsPressed = true; break;
case Keyboard.DOWN : downIsPressed = true; break;
}
}
function keyUpHandler(e:KeyboardEvent):void {
switch(e.keyCode) {
case Keyboard.LEFT : leftIsPressed = false; break;
case Keyboard.RIGHT : rightIsPressed = false; break;
case Keyboard.UP : upIsPressed = false; break;
case Keyboard.DOWN : downIsPressed = false; break;
}
}
function enterFrameHandler(e:Event):void {
vx = -int(leftIsPressed)*speed + int(rightIsPressed)*speed;
vy = -int(upIsPressed)*speed + int(downIsPressed)*speed;
PlayerAuto.x += vx;
PlayerAuto.y += vy;
}
function generateParticles(event:Event):void
{
//so we don't do it every frame, we'll do it randomly
if(Math.random()*10 < 2){
//creating a new shape
var mcParticle:Shape = new Shape();
//making random dimensions (only ranges from 1-5 px)
var dimensions:int = int(Math.random()*5)+1;
//add color to the shape
mcParticle.graphics.beginFill(0x999999/*The color for shape*/,1/*The alpha for the shape*/);
//turning the shape into a square
mcParticle.graphics.drawRect(dimensions,dimensions,dimensions,dimensions);
//change the coordinates of the particle
mcParticle.x = int(Math.random()*stage.stageWidth);
mcParticle.y = -10;
//adding the particle to stage
particleContainer.stage.addChild(mcParticle);
}
//making all of the particles move down stage
for(var i:int=0;i<particleContainer.numChildren;i++){
//getting a certain particle
var theParticle:DisplayObject = particleContainer.getChildAt(i);
//it'll go half the speed of the character
theParticle.y += speed*.5;
//checking if the particle is offstage
if(theParticle.y >= 400){
//remove it
particleContainer.stage.removeChild(theParticle);
}
}
}
/**
* eventhandler voor als je op de tweede knop klikt
*/
private function loadScreenThree( event:MouseEvent ):void
{
// eerst opruimen!
cleanListeners();
// dan naar ander scherm
Project.instance.switchScreen( "derde" );
}
private function cleanListeners():void
{
drieButton.removeEventListener( MouseEvent.CLICK, loadScreenThree );
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.removeEventListener(Event.ENTER_FRAME, generateParticles);
}
}
}
I think the problem is here:
for(var i:int=0;i<particleContainer.numChildren;i++){
var theParticle:DisplayObject = particleContainer.getChildAt(i);
[...]
if (theParticle.y >= 400){
particleContainer.removeChild(theParticle);
}
}
You are removing children from the particleContainer while iterating through it. This is usually a bad idea because once you remove an item from the beginning, you are changing the index of all following items.
One solution is to loop backwards, so when you remove something the only items changed are the ones that you already checked.
for(var i:int=particleContainer.numChildren - 1; i>=0; i--){
And the rest keeps the same.

Movieclip not being removed from array or stage - AS3 - CS6

my enemy movie clips are not being removed from the stage on collision/hitTestObject with the bullet movie clip, the bullets are being removed though, only the enemies that are not. Appreciate all help with this. Thanks you guys, your a brilliant community here, respect you loads.
I used the same code that made the bullet movie clips be removed for the enemies (though change changing the vars etc accordingly).
My code for Main.as and Enemy.as is here:
Main.as
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends MovieClip
{
public var player:Player;
public var enemy:Enemy;
public var bulletList:Array = [];
public var mousePressed:Boolean = false; //keeps track of whether the mouse is currently pressed down
public var delayCounter:int = 0; //this adds delay between the shots
public var delayMax:int = 7; //change this number to shoot more or less rapidly
public var enemies:Array = [];
public function Main():void
{
player = new Player(stage, 320, 240);
stage.addChild(player);
//stage.addEventListener(MouseEvent.CLICK, shootBullet, false, 0, true); //remove this
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler, false, 0, true);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, false, 0, true);
stage.addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
for(var numBaddies=0; numBaddies<6;numBaddies++){
var enemy:Enemy = new Enemy(null);
enemy.x = numBaddies*50;
enemy.y = numBaddies*50
stage.addChild(enemy);
enemies.push(enemy);
}
}
public function loop(e:Event):void
{
if(mousePressed) // as long as the mouse is pressed...
{
delayCounter++; //increase the delayCounter by 1
if(delayCounter == delayMax) //if it reaches the max...
{
shootBullet(); //shoot a bullet
delayCounter = 0; //reset the delay counter so there is a pause between bullets
}
}
if(bulletList.length > 0)
{
for(var i:int = bulletList.length-1; i >= 0; i--)
{
bulletList[i].loop();
}
}
for(var h = 0; h<bulletList.length; ++h)
{
if(bulletList[h].hitTestObject(this)){
trace("player hit by baddie " + h);
}
}
for(var u:int=0; u<enemies.length; u++) {
Enemy(enemies[u]).moveTowards(player.x, player.y);
}
}
public function mouseDownHandler(e:MouseEvent):void //add this function
{
mousePressed = true; //set mousePressed to true
}
public function mouseUpHandler(e:MouseEvent):void //add this function
{
mousePressed = false; //reset this to false
}
public function shootBullet():void //delete the "e:MouseEvent" parameter
{
var bullet:Bullet = new Bullet(stage, player.x, player.y, player.rotation, enemies);
bullet.addEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved, false, 0, true);
bulletList.push(bullet);
stage.addChild(bullet);
}
public function bulletRemoved(e:Event):void
{
e.currentTarget.removeEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved);
bulletList.splice(bulletList.indexOf(e.currentTarget),1);
}
}
}
Enemy.as
package {
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
public class Enemy extends MovieClip {
public var bullets:Array;
public var stageRef:Stage;
private var enemyPositionX, enemyPositionY,xDistance,yDistance,myRotation:int;
public function Enemy(bulletList:Array) {
// constructor code
bullets = bulletList;
}
public function moveTowards(playerX:int, playerY:int){
xDistance = this.x - playerX;
yDistance = this.y - playerY;
myRotation = Math.atan2(yDistance, xDistance);
this.x -= 3 * Math.cos(myRotation);
this.y -= 3 * Math.sin(myRotation);
}
public function loop():void{
for(var i=0; i<bullets.length; ++i)
{
if(bullets[i].hitTestObject(this)){
trace("you killed enemy " + i);
removeSelf();
}
}
}
private function removeSelf():void
{
removeEventListener(Event.ENTER_FRAME, loop);
if (stageRef.contains(this))
stageRef.removeChild(this);
}
}
}
And for reference so you can see how I used the same code to remove the movie clips, I'll add the Bullet.as too:
Bullet.as
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
public class Bullet extends MovieClip
{
private var stageRef:Stage; //checks if the bullet leaves the screen borders
private var speed:Number = 10; //speed that the bullet will travel at
private var xVel:Number = 0; //current x velocity
private var yVel:Number = 0; //current y velocity
private var rotationInRadians = 0; //convenient to store our rotation in radians instead of degrees
public var allBaddies:Array;
//our constructor requires: the stage, the position of the bullet, and the direction the bullet should be facing
public function Bullet(stageRef:Stage, X:int, Y:int, rotationInDegrees:Number, enemies:Array):void
{
this.stageRef = stageRef;
this.x = X;
this.y = Y;
this.rotation = rotationInDegrees;
this.rotationInRadians = rotationInDegrees * Math.PI / 180; //convert degrees to radians, for trigonometry
allBaddies = enemies;
}
public function loop():void //we don't need to include the "e:Event" because we aren't using an EventListener
{
for(var b=0; b<allBaddies.length; ++b)
{
if(allBaddies[b].hitTestObject(this)){
trace("bullet hit baddie " + b);
removeSelf();
}
}
xVel = Math.cos(rotationInRadians) * speed; //uses the cosine to get the xVel from the speed and rotation
yVel = Math.sin(rotationInRadians) * speed; //uses the sine to get the yVel
x += xVel; //updates the position
y += yVel;
//if the bullet goes off the edge of the screen...
if(x > stageRef.stageWidth || x < 0 || y > stageRef.stageHeight || y < 0)
{
this.parent.removeChild(this); //remove the bullet
}
}
private function removeSelf():void
{
removeEventListener(Event.ENTER_FRAME, loop);
if (stageRef.contains(this))
stageRef.removeChild(this);
}
}
}
Ok there are a couple of things I would change around, alongside a couple issues I noticed.
First, your Enemy class as far as I can tell never gets the stageRef variable set. Therefore in your Enemy class removeSelf() your stageRef will be null.
You can either pass the stage in through the constructor and set it (as you do in your bullet class), or you can set it after you instantiate in your enemies loop with enemy.stageRef = stage. Or you can add and event listener to your enemy class for Event.ADDED_TO_STAGE and when that happens your enemy will have a reference to the stage inherited.
Now, the real meat of the matter. You have 2 for loops testing for collision (aside from one in your Main class too, but I'll get to that). One is in your bullet class and one is in your enemy class. This is overkill and is difficult on performance if you start adding in lots of bullets and enemies. You really only need a single for loop (like the one in your bullet class), and when it detects a collision it calls the collided objects remove method. That would look something like this in your Bullet class:
public function loop():void //we don't need to include the "e:Event" because we aren't using an EventListener
{
for(var b=0; b<allBaddies.length; ++b)
{
if(allBaddies[b].hitTestObject(this)){
trace("bullet hit baddie " + b);
removeSelf();
allBaddies[b].removeSelf();
}
}
Although, for this to work you would need to set the removeSelf() in your Enemy class access to public:
public function removeSelf():void
{
//this is removing a listener not even added Enemy...
//removeEventListener(Event.ENTER_FRAME, loop);
if (stageRef.contains(this))
stageRef.removeChild(this);
}
Then you can probably even eliminate your loop() from the Enemy class seeing as how all it does it detect collisions that will no longer be necessary.
Lastly as to why this might happened? Well it could be the bullet hitTest which is running first from your call in the main class: bulletList[i].loop(); This hitTest is being detected, then removing the bullet leaving your Enemy class without an object to hit test against. BUT! you are not calling the loop() from enemy anywhere in your main class, therefore that hit test will never run.
It's best to condense your collisions down. You are currently looping through your Bullet instances in the main class, calling their loop() (which tests for collisions), and then afterwards doing a for loop doing the collision test again. You could change this:
if(bulletList.length > 0)
{
for(var i:int = bulletList.length-1; i >= 0; i--)
{
bulletList[i].loop();
}
}
//this is no longer needed...
/*for(var h = 0; h<bulletList.length; ++h)
{
if(bulletList[h].hitTestObject(this)){
trace("player hit by baddie " + h);
}
}*/
There is no reason to test the collision in the Bullet class AND in the Main class loop(e:Event).
Hope this information helps! Good luck :)

Resources