This site requires JavaScript, please enable it in your browser!
Greenfoot back
manish123
manish123 wrote ...

2013/10/8

arrays

manish123 manish123

2013/10/8

#
hello! i was just wondering if there was a way too loop through an array to return objects. Like for example i am working on my AI right now and i want it to automatically turn and go after the closest point but im not sure how to go about this. My gird is set up as an array and i want to loops through it to find the closest point this is what i have in the map class so far: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.util.List; /** * Write a description of class map here. * * @author (your name) * @version (a version number or a date) */ public class map extends World { private int grid_; public final int POINT = 1; public final int EMPTY = 2; /** * Constructor for objects of class map. * */ public map() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(30, 30, 20); grid_ = new int; //make all array indices = EMPTY //put 5 POINTS in the board initially initialize(); } public void addPoint(int r, int c) { Points p = new Points(); addObject(p,r,c); grid_ = POINT; } public void makeEmpty(int r, int c) { List<Points> l = getObjectsAt(r,c,Points.class); removeObjects(l); grid_ = EMPTY; } public void act() { if(Greenfoot.getRandomNumber(100) == 0)//1 in 100 acts { int rows = Greenfoot.getRandomNumber(getHeight()); int col = Greenfoot.getRandomNumber(getWidth()); addPoint(rows, col); } } //add 5 points intially private void initialize() { for(int i = 0; i < 5; i++) { Points P = new Points(); int x = Greenfoot.getRandomNumber(getWidth()); int y = Greenfoot.getRandomNumber(getHeight()); addObject(P,x,y); } } }
danpost danpost

2013/10/8

#
You do not have to use your grid to find the points, just use 'getObjects(Point.class)'. If it returns empty, there are no points to turn toward. If the list is only one in size, then turn toward that one. If the list is longer, either compare the distances to each one to find the minimum distance or do an outward search using 'getObjectsInRange' in a while loop.
int dist = 1;
while (getObjectsInRange(dist, Point.class).isEmpty()) dist++;
Point closestPoint = (Point)getObjectsInRange(dist, Point.class).get(0);
davmac davmac

2013/10/8

#
or do an outward search using 'getObjectsInRange' in a while loop.
Just be aware that this is horribly inefficient! :) If only one actor is doing it, it should be fine.
danpost danpost

2013/10/8

#
davmac wrote...
Just be aware that this is horribly inefficient! :) If only one actor is doing it, it should be fine.
I figured that with a 30x30 grid, it would not be too bad.
davmac davmac

2013/10/8

#
I figured that with a 30x30 grid, it would not be too bad.
That's quite true.
manish123 manish123

2013/10/8

#
ok thanks guys! and yes it is only one actor doing it so it should run smoothly!
You need to login to post a reply.