How do i get Object index in an array - arrays

I have seen many threads about this but my problem doesn't solved. This may be a simple way but i have no idea...
I'm trying to get Objects indices in an array like so :
var test:Array = new Array();
for (var row:Number = 0; row < 2; row++) {
test[row] = [];
for (var column:Number = 0; column < 3; column++) {
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
test[row][column] = new ballShape(column, column, row);
addChild(test[row][column]);
}
}
function objClicked(evt:MouseEvent):void {
// Here must return Object index in array
}
P.S :
I can get items index in int array, but i don't know about objects.
Any ideas would be appreciated.
Edit :
ballShape.as
package {
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.MouseEvent;
import fl.motion.Color;
public class ballShape extends Sprite {
private var shapeId:uint;
private var currentPosition:uint;
private var arrayPosition:uint;
private var color:Number;
public function ballShape(Id:uint, currPos:uint, arrPos:uint) {
setId(Id);
setArrayPos(arrPos);
setCurrentPos(currPos);
//trace("Array : " + arrPos);
//trace("Curr : " + currPos);
if (arrPos == 0) {
var posX:uint = 60;
} else {
var posX:uint = (arrPos + 1) * 60;
}
if (currPos == 0) {
var posY:uint = 42;
} else {
var posY:uint = (currPos + 1) * 42;
}
if (arrPos == 0) {
color = 0xFF0000;
} else {
color = 0x00FF00;
}
graphics.beginFill(color, 1.0);
graphics.drawCircle(posX, posY, 20);
graphics.endFill();
this.addEventListener(MouseEvent.CLICK, Clicked);
}
public function setId(Id:uint):void {
shapeId = Id;
}
public function getId():uint {
return shapeId;
}
public function Clicked(evt:MouseEvent):void {
//return getId();
trace("Ball id is " + getId());
trace("Array id is " + getArrayPos());
trace("PositionInArray id is " + getCurrentPos());
//return arrayPosition;
}
public function setCurrentPos(Pos:uint):void {
currentPosition = Pos;
}
public function getCurrentPos():uint {
return currentPosition;
trace(currentPosition);
}
public function setArrayPos(arrayPos:uint):void {
arrayPosition = arrayPos;
}
public function getArrayPos():uint {
return arrayPosition;
trace(arrayPosition);
}
public function addBead(arrayId, currPos):void {
}
}
}

I would suggest adding row and column as public variables in your ballShape class.
That way you can get them like this:
function objClicked(evt:MouseEvent):void {
trace(ballShape(evt.target).getCurrentPos(), ballShape(evt.target).getArrayPos());
}
Maybe turn this two lines around:
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
test[row][column] = new ballShape(column, column, row);
to be :
test[row][column] = new ballShape(column, column, row);
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);

Try something like:
protected function objClicked(e:MouseEvent):void {
for (var row: int=0; row < test.length; row++) {
var column:int = (test[row] as Array).indexOf(e.currentTarget);//use currentTarget so you don't try to match on internal Interactive Objects!
if (column>-1) {
trace(row, column);
return;//or break, if you need to do something else below this loop
}
}
}

Related

How to build a swipable intro screen?

A lot of apps have swipable intro screens - You know - those with the dots below which indicate the page one is currently viewing.
What would be the best way to create one in Codename One - a Container with snapToGrid?
I have my own implementation for this use case. There are two classes : TutoDialog which could be in your case the "intro screens" dialog and Caroussel with the dots indicator.
A tuto dialog has a title and some images in parameter. It automatically adjust the number of dots of the caroussel according to the number of images. For my use case, each image is a screenshot of my app with some advise. The tuto dialog contains 3 buttons to navigate between images (next/previous/finish).
public class Caroussel extends Container {
private final static Image CIRCLE = MainClass.getResources().getImage("circle-blue20.png");
private final static Image CIRCLE_EMPTY = MainClass.getResources().getImage("circle-empty-blue20.png");
private Label[] circles;
private int currentIndex = -1;
public Caroussel(int nbItems, boolean selectFirst) {
if (nbItems < 2 || nbItems > 50) {
throw new IllegalArgumentException("Can't create Caroussel component with nbItems<2 || nbItems>50 ! ");
}
this.circles = new Label[nbItems];
setLayout(new BoxLayout(BoxLayout.X_AXIS));
for (int i = 0; i < nbItems; i++) {
circles[i] = new Label("", CIRCLE_EMPTY);
add(circles[i]);
}
if (selectFirst) {
select(0);
}
}
public void select(int index) {
if (index >= 0 && index <= circles.length) {
if (currentIndex > -1) {
circles[currentIndex].setIcon(CIRCLE_EMPTY);
}
circles[index].setIcon(CIRCLE);
currentIndex = index;
repaint();
}
}
public void selectNext() {
if (currentIndex <= circles.length) {
select(currentIndex + 1);
}
}
public void selectPrevious() {
if (currentIndex >= 1) {
select(currentIndex - 1);
}
}}
And
public class TutoDialog extends Dialog {
private Caroussel caroussel = null;
public TutoDialog(String title, Image... images) {
if (images == null) {
return;
}
this.caroussel = new Caroussel(images.length, true);
setTitle(title);
setAutoAdjustDialogSize(true);
getTitleComponent().setUIID("DialogTitle2");
setBlurBackgroundRadius(8.5f);
Tabs tabs = new Tabs();
tabs.setSwipeActivated(false);
tabs.setAnimateTabSelection(false);
int px1 = DisplayUtil.getScaledPixel(800), px2 = DisplayUtil.getScaledPixel(600);
for (Image img : images) {
tabs.addTab("", new Label("", img.scaled(px1, px2)));
}
Container cButtons = new Container(new BorderLayout());
Button bSuivant = new Button("button.suivant");
Button bPrecedent = new Button("button.precedent");
Button bTerminer = new Button("button.terminer");
bPrecedent.setVisible(false);
bTerminer.setVisible(false);
bSuivant.addActionListener(new ActionListener<ActionEvent>() {
public void actionPerformed(ActionEvent evt) {
int currentInd = tabs.getSelectedIndex();
if (currentInd == 0) {
bPrecedent.setVisible(true);
}
if (currentInd + 1 <= tabs.getTabCount() - 1) {
if (caroussel != null)
caroussel.selectNext();
tabs.setSelectedIndex(currentInd + 1);
if (currentInd + 1 == tabs.getTabCount() - 1) {
bTerminer.setVisible(true);
bSuivant.setVisible(false);
cButtons.revalidate();
}
}
};
});
bPrecedent.addActionListener(new ActionListener<ActionEvent>() {
public void actionPerformed(ActionEvent evt) {
int currentInd = tabs.getSelectedIndex();
tabs.setSelectedIndex(currentInd - 1);
bSuivant.setVisible(true);
if (caroussel != null)
caroussel.selectPrevious();
if (currentInd - 1 == 0) {
bPrecedent.setVisible(false);
cButtons.revalidate();
}
};
});
bTerminer.addActionListener(new ActionListener<ActionEvent>() {
#Override
public void actionPerformed(ActionEvent evt) {
tabs.setSelectedIndex(0);
bPrecedent.setVisible(false);
bTerminer.setVisible(false);
bSuivant.setVisible(true);
if (caroussel != null)
caroussel.select(0);
TutoDialog.this.dispose();
}
});
cButtons.add(BorderLayout.WEST, bPrecedent).add(BorderLayout.CENTER, bSuivant).add(BorderLayout.EAST, bTerminer);
add(BoxLayout.encloseY(tabs, BoxLayout.encloseY(FlowLayout.encloseCenter(caroussel), cButtons)));
}
public static void showIfFirstTime(AbstractComponentController ctrl) {
if (ctrl == null) {
Log.p("Can't execute method showIfFirstTime(...) with null AbstractComponentController");
return;
}
String key = getKey(ctrl);
if (ctrl.getTutoDlg() != null && !Preferences.get(key, false)) {
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
Preferences.set(key, true);
ctrl.getTutoDlg().show();
}
});
}
}
public static String getKey(AbstractComponentController ctrl) {
String key = "tuto" + ctrl.getClass().getSimpleName();
if (UserController.getCurrentUser() != null) {
key += "-" + UserController.getCurrentUser().getId();
}
return key;
}
public static boolean isAlreadyShown(AbstractComponentController ctrl) {
return Preferences.get(getKey(ctrl), false);
}
}
It's look like this :
OK - so that is my first attempt and I am pretty content with that:
private void showIntro() {
Display display = Display.getInstance();
int percentage = 60;
int snapWidth = display.getDisplayWidth() * percentage / 100;
int snapHeight = display.getDisplayHeight() * percentage / 100;
Dialog dialog = new Dialog(new LayeredLayout()) {
#Override
protected Dimension calcPreferredSize() {
return new Dimension(snapWidth, snapHeight);
}
};
Tabs tabs = new Tabs();
tabs.setTensileLength(0);
tabs.hideTabs();
int[] colors = {
0xc00000,
0x00c000,
0x0000c0,
0x909000,
0x009090,
};
for (int colorIndex = 0; colorIndex < colors.length; colorIndex++) {
Container containerElement = new Container() {
#Override
protected Dimension calcPreferredSize() {
return new Dimension(snapWidth, snapHeight);
}
};
Style style = containerElement.getAllStyles();
style.setBgTransparency(0xff);
style.setBgColor(colors[colorIndex]);
tabs.addTab("tab" + tabs.getTabCount(), containerElement);
}
int tabCount = tabs.getTabCount();
Button[] buttons = new Button[tabCount];
Style styleButton = UIManager.getInstance().getComponentStyle("Button");
styleButton.setFgColor(0xffffff);
Image imageDot = FontImage.createMaterial(FontImage.MATERIAL_LENS, styleButton);
for (int tabIndex = 0; tabIndex < tabCount; tabIndex++) {
buttons[tabIndex] = new Button(imageDot);
buttons[tabIndex].setUIID("Container");
final int tabIndexFinal = tabIndex;
buttons[tabIndex].addActionListener(aActionEvent -> tabs.setSelectedIndex(tabIndexFinal, true));
}
Container containerButtons = FlowLayout.encloseCenter(buttons);
dialog.add(tabs);
Button buttonWest = new Button("Skip");
buttonWest.setUIID("Container");
buttonWest.getAllStyles().setFgColor(0xffffff);
buttonWest.addActionListener(aActionEvent -> dialog.dispose());
Button buttonEast = new Button(">");
buttonEast.setUIID("Container");
buttonEast.getAllStyles().setFgColor(0xffffff);
buttonEast.addActionListener(aActionEvent -> {
int selectedIndex = tabs.getSelectedIndex();
if (selectedIndex < (tabs.getTabCount() - 1)) {
tabs.setSelectedIndex(selectedIndex + 1, true);
} else {
dialog.dispose();
}
});
Container containerSouth = BorderLayout.south(BorderLayout.centerAbsoluteEastWest(containerButtons, buttonEast, buttonWest));
Style styleContainerSouth = containerSouth.getAllStyles();
styleContainerSouth.setMarginUnit(
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS);
styleContainerSouth.setMargin(2, 2, 2, 2);
dialog.add(containerSouth);
SelectionListener selectionListener = (aOldSelectionIndex, aNewSelectionIndex) -> {
for (int buttonIndex = 0; buttonIndex < buttons.length; buttonIndex++) {
if (buttonIndex == aNewSelectionIndex) {
buttons[buttonIndex].getAllStyles().setOpacity(0xff);
} else {
buttons[buttonIndex].getAllStyles().setOpacity(0xc0);
}
}
buttonEast.setText((aNewSelectionIndex < (tabs.getTabCount() - 1)) ? ">" : "Finish");
buttonEast.getParent().animateLayout(400);
};
tabs.addSelectionListener(selectionListener);
dialog.addShowListener(evt -> {
buttonEast.getParent().layoutContainer();
selectionListener.selectionChanged(-1, 0);
});
Command command = dialog.showPacked(BorderLayout.CENTER, true);
}

Trouble creating multiple objects (Arrays) in Flash

I'm making a basic Galaga type game in Flash and have been running into issues. This is my first time really messing with ActionScript.
I created an Array for my Enemies and would like to know how I would go about having them spawn in their own respective locations, like in Galaga and then have them move uniformly form left to right while descending once reaching the edge of the stage.
Game
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class SpaceVigilanteGame extends MovieClip
{
public var army:Array;
public var avatar:Avatar;
public var gameTimer:Timer;
public var useMouseControl:Boolean;
public var rightKeyIsBeingPressed:Boolean;
public var leftKeyIsBeingPressed:Boolean;
var gameWidth:int = 0;
var gameHeight:int = 0;
public function SpaceVigilanteGame()
{ useMouseControl = false;
leftKeyIsBeingPressed = false;
rightKeyIsBeingPressed = false;
army = new Array();
var newEnemy = new Enemy( 60, 30 );
army.push( newEnemy );
addChild( newEnemy );
avatar = new Avatar();
addChild( avatar );
if ( useMouseControl )
{
avatar.x = mouseX;
avatar.y = mouseY;
}
else
{
avatar.x = 50;
avatar.y = 400;
}
gameWidth = stage.stageWidth;
gameHeight = stage.stageHeight;
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, moveEnemy );
gameTimer.addEventListener( TimerEvent.TIMER, moveAvatar );
gameTimer.start();
stage.addEventListener( KeyboardEvent.KEY_DOWN, onKeyPress );
stage.addEventListener( KeyboardEvent.KEY_UP, onKeyRelease );
function onKeyPress( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.RIGHT )
{
rightKeyIsBeingPressed = true;
}
else if ( keyboardEvent.keyCode == Keyboard.LEFT )
{
leftKeyIsBeingPressed = true;
}
}
function onKeyRelease( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.RIGHT )
{
rightKeyIsBeingPressed = false;
}
else if (keyboardEvent.keyCode ==Keyboard.LEFT )
{
leftKeyIsBeingPressed = false;
}
}
}
public function moveEnemy( timerEvent:TimerEvent ):void
{
for each ( var enemy:Enemy in army )
{
}
//enemy.moveDownABit();
if(enemy.x+enemy.width+2<=gameWidth)
{
enemy.moveRight();
}
else if(enemy.y+enemy.height+2<=gameHeight)
{
enemy.moveDown();
}
else if(enemy.x-2>=0)
{
enemy.moveLeft();
}
else if(enemy.y-2>=0)
{
enemy.moveUp();
}
}
public function moveAvatar( timerEvent:TimerEvent ):void
{
if ( useMouseControl )
{
avatar.x = mouseX;
avatar.y = mouseY;
}
else if ( rightKeyIsBeingPressed )
{
avatar.moveRight();
}
else if ( leftKeyIsBeingPressed )
{
avatar.moveLeft();
}
}
}
}
Enemy Class
package
{
import flash.display.MovieClip;
public class Enemy extends MovieClip
{
public function Enemy( startX:Number, startY:Number )
{
x = startX;
y = startY;
}
public function moveRight():void
{
x = x + 2;
}
public function moveDown():void
{
y = y + 2;
}
public function moveLeft():void
{
x = x - 2;
}
public function moveUp():void
{
y = y - 2;
}
}
}
I would suggest that during the enemy instantiation (of which there seems to be only one), you should be setting the locations respective of one another.
as an example:
your code currently does this:
var newEnemy = new Enemy( 60, 30 );
army.push( newEnemy );
addChild( newEnemy );
Perhaps it should do something like this:
for(var x:int = 0; x< ARMY_WIDTH; x++)
{
for(var y:int = 0; y < ARMY_HEIGHT; y++)
{
army.push(new Enemy(60 + x * X_GAP, 30 + y *Y_GAP));
this.addChild(army[army.length-1]);
}
}
Now, I've made a lot of assumptions in the above code; I've invented constants that you may not have, and I've only solved your immediate problem. Ideally you're going to need to look at more advanced solutions for your issue, something like a factory class that creates your enemies for you, or recycles them from a pool of enemies.
However, you're just starting out and you will figure a lot of this stuff out in time. Good luck in your project and I hope you keep up developing your skills :)

DataDriven testing with TestNG using Apache POI in Selenium WebDriver

I am new to TestNG framework. Please guide how to parameterise the test cases using Apache POI(Excel).
I have a code to read from second row from Excel.
public class spreadData {
private transient Collection data = null;
public spreadData(final InputStream excelInputStream) throws IOException {
this.data = loadFromSpreadsheet(excelInputStream);
}
public Collection getData() {
return data;
}
private Collection loadFromSpreadsheet(final InputStream excelFile)
throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook(excelFile);
data = new ArrayList();
Sheet sheet = workbook.getSheetAt(0);
int numberOfColumns = countNonEmptyColumns(sheet);
List rows = new ArrayList();
List rowData = new ArrayList();
/*for (Row row : sheet) {
if (isEmpty(row)) {
break;
} else {
rowData.clear();
for (int column = 0; column < numberOfColumns; column++) {
Cell cell = row.getCell(column);
rowData.add(objectFrom(workbook, cell));
}
rows.add(rowData.toArray());
}
}*/
int rowStart = 1;
//int rowEnd = Math.max(1400, sheet.getLastRowNum());
for (int rowNum = rowStart; rowNum <= sheet.getLastRowNum(); rowNum++) {
//Row r = sheet.getRow(rowNum);
Row read = sheet.getRow(rowNum);
if (isEmpty(read)) {
break;
} else {
rowData.clear();
for (int column = 0; column < numberOfColumns; column++) {
Cell cell = read.getCell(column);
rowData.add(objectFrom(workbook, cell));
}
rows.add(rowData.toArray());
}
}
return rows;
}
private boolean isEmpty(final Row row) {
Cell firstCell = row.getCell(0);
boolean rowIsEmpty = (firstCell == null)
|| (firstCell.getCellType() == Cell.CELL_TYPE_BLANK);
return rowIsEmpty;
}
/**
* Count the number of columns, using the number of non-empty cells in the
* first row.
*/
private int countNonEmptyColumns(final Sheet sheet) {
Row firstRow = sheet.getRow(0);
return firstEmptyCellPosition(firstRow);
}
private int firstEmptyCellPosition(final Row cells) {
int columnCount = 0;
for (Cell cell : cells) {
if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
break;
}
columnCount++;
}
return columnCount;
}
private Object objectFrom(final HSSFWorkbook workbook, final Cell cell) {
Object cellValue = null;
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
cellValue = cell.getRichStringCellValue().getString();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cellValue = getNumericCellValue(cell);
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
cellValue = cell.getBooleanCellValue();
} else if (cell.getCellType() ==Cell.CELL_TYPE_FORMULA) {
cellValue = evaluateCellFormula(workbook, cell);
}
return cellValue;
}
private Object getNumericCellValue(final Cell cell) {
Object cellValue;
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = new Date(cell.getDateCellValue().getTime());
} else {
cellValue = cell.getNumericCellValue();
}
return cellValue;
}
private Object evaluateCellFormula(final HSSFWorkbook workbook, final Cell cell) {
FormulaEvaluator evaluator = workbook.getCreationHelper()
.createFormulaEvaluator();
CellValue cellValue = evaluator.evaluate(cell);
Object result = null;
if (cellValue.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
result = cellValue.getBooleanValue();
} else if (cellValue.getCellType() == Cell.CELL_TYPE_NUMERIC) {
result = cellValue.getNumberValue();
} else if (cellValue.getCellType() == Cell.CELL_TYPE_STRING) {
result = cellValue.getStringValue();
}
return result;
}
}
My question is how to parameterise the test cases using TestNG? means by using #DataProvider TestNG annotation.
Kindly help me with a sample code or explanation.
I'm not sure which set of data you want...but here's how a dataProvider works:
Say I have a test that takes a String and then an int like this:
#Test(dataProvider = "excelData")
public void executeTest(String name, int value){}
My data provider would look something like this:
#DataProvider(name = "excelData")
public Object[][] data(){
return new Object[][]{
{"Test",1},
{"More Testing",7},
{"Last Test",-5}}
}
The test will be run 3 times, with each row of the array is the set of data that is to be passed in. You will need to convert your excel data into such a format.
Note, you can also return an Iterator<Object[]> if you prefer.

Creating Enemy Cone of vision

I am trying to create a cone of vision for my enemy class. Right now it checks to see if the player is within a radius before moving towards them and will move around randomly if they are not. I want to give it vision so the enemy does not always rotate towards the player.
Enemy Class
package
{
import flash.automation.ActionGenerator;
import flash.events.Event;
import flash.geom.Point;
public class Enemy extends GameObject
{
var isDead:Boolean = false;
var speed:Number = 3;
var originalValue:Number = 50;
var changeDirection:Number = originalValue;
var checkDirection:Number = 49;
var numberGen:Number;
//var startTime:int = getTimer();
//var $timer = getTimer();
//var myTimer:int = getTimer();
//var moveTimer:int = timer - $timer;
public function Enemy()
{
super();
target = target_mc;
}
override public function update():void
{
movement();
}
private function movement():void
{
if (changeDirection >= 0)
{
if (changeDirection > checkDirection)
{
numberGen = (Math.random() * 360) / 180 * Math.PI;
}
var velocity:Point = new Point();
var $list:Vector.<GameObject > = getType(Player);
var $currentDistance:Number = Number.MAX_VALUE;
for (var i:int = 0; i < $list.length; i++)
{
var currentPlayer:GameObject = $list[i];
if (MathUtil.isWithinRange(currentPlayer.width,currentPlayer.x,currentPlayer.y,width,x,y))
{
var $delta:Point = new Point ;
$delta.x = currentPlayer.x - x;
$delta.y = currentPlayer.y - y;
if ($currentDistance > $delta.length)
{
$currentDistance = $delta.length;
velocity = $delta;
velocity.normalize(speed);
}
}
}
if(velocity.length == 0)
{
velocity = Point.polar(2, numberGen);
}
changeDirection--;
if (changeDirection == 0)
{
changeDirection = originalValue;
}
}
velocity.x = Math.floor(velocity.x * 10) * .1;
velocity.y = Math.floor(velocity.y * 10) * .1;
moveBy([Wall, Door], velocity.x, velocity.y, collides_mc);
var $collides:GameObject = collision([Player]);
if ($collides != null)
{
destroy();
}
if ($collides == null)
{
$collides = collision([Player],this);
if ($collides != null)
{
$collides.destroy();
}
}
rotation = (Math.atan2(velocity.y, velocity.x) * 180 / Math.PI);
collides_mc.rotation = -rotation;
trace($collides);
}
override public function onCollideX($collision:GameObject):void
{
}
override public function onCollideY($collision:GameObject):void
{
}
}
}
GameObject Class, which contains all the functions and Enemy extends it
package
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.sensors.Accelerometer;
import flashx.textLayout.elements.ListElement;
public class GameObject extends MovieClip
{
static public var list:Vector.<GameObject> = new Vector.<GameObject>;
protected var hitBox:Sprite;
public var target:MovieClip;
public function GameObject()
{
target=this;
list.push(this);
}
public function update():void
{
}
public function collision(typesColliding:Array, $target:DisplayObject = null):GameObject
{
if($target == null)
$target = target;
for (var i:int = list.length - 1; i >= 0; i--)
{
var item:GameObject = list[i], found:Boolean = false;
for (var f:int = typesColliding.length - 1; f >= 0; f--)
{
if (item is typesColliding[f])
{
found = true;
break;
}
}
if (found && $target.hitTestObject(item.target) && this != item)
{
return item;
}
}
return null;
}
public function moveBy(typesColliding:Array, $x:Number = 0, $y:Number = 0, $target:DisplayObject = null):void
{
var $collision:GameObject;
x += $x;
if (($collision = collision(typesColliding, $target)) != null)
{
x -= $x;
onCollideX($collision);
}
y += $y;
if (($collision = collision(typesColliding, $target)) != null)
{
y -= $y;
onCollideY($collision);
}
}
public function onCollideX($collision:GameObject):void
{
}
public function onCollideY($collision:GameObject):void
{
}
public function getType($class:Class):Vector.<GameObject>
{
var $list:Vector.<GameObject> = new Vector.<GameObject>;
for (var i:int = 0; i < list.length; i++)
{
if (list[i] is $class)
{
$list.push(list[i]);
}
}
return $list;
}
public function destroy():void
{
var indexOf:int = list.indexOf(this);
if (indexOf > -1)
list.splice(indexOf, 1);
if (parent)
parent.removeChild(this);
trace("removing item: "+this+" list: " + list.length + ": " + list);
}
}
}
Any help would be appreciated, thank you.
Changing radius of vision to the cone of vision simply requires computing (after checking the distance) the angle between the direction enemy is facing and the player. If this angle is smaller then some T, then it is in the cone of vision of angle 2T (due to symmetry).
This obviously ignores any walls/obstacles that should limit vision, but it should give you the general idea.

looping and returning a array

I am in need of some help. I am very new to actionscript and what I am trying to do is calculate the amount of apples from the array and then trace it in the main function. Right now I am getting an error on the return and that error is 1067: Implicit coercion of a value of type String to an unrelated type Number. Now I have tried to switch out the number and string but I still get the error.
public class extends Sprite
{
public function()
{
var fruitNames:Array = ["apple", "peach","banana","pear","guava","apple","peach"];
var totalApples:Number = countingApples(fruitNames);
trace("You have " + totalApples);
}
private function countingApples(fruitNames:Array):Number
{
var total:String = "apple";
for(var i:uint=0; i<7; i++)
{
total += Number[i];
}
return total;
}
}
public class extends Sprite
{
public function()
{
var fruitNames:Array = ["apple", "peach","banana","pear","guava","apple","peach"];
var totalApples:Number = countingApples(fruitNames);
trace("You have " + totalApples);
}
private function countingApples(fruitNames:Array):Number
{
var total:uint = 0;
var i:String = new String();
for(i in fruitNames) {
if (fruitNames[i] == "apple") {
total = total + 1;
}
}
return total;
}
}
That error is because you're trying to return total, which is a String, but you've set the countingApples function's return type as Number. Here's an example which will do what you want, but I think you should try writing your own version again so that you know what's going on:
private function countingApples(fruitNames:Array):Number
{
var total:uint = 0;
var targetFruit:String = "apple";
var totalFruit:uint = fruitNames.length;
for(var i:uint = 0; i < totalFruit; i++)
{
if (fruitNames[i] == targetFruit) {
total++;
}
}
return total;
}

Resources