CountryIterator

AI discussion, ideas, and SDK help.
Post Reply
User avatar
SunTzu
Lux Cartographer
Posts: 1586
Joined: Sat Jan 14, 2006 1:48 am
Location: Maryland

CountryIterator

Post by SunTzu » Mon Jul 09, 2007 2:35 pm

How can I use the CountryIterator to create a new Country[] array?

Here's the method I'm trying to make:

Code: Select all

public Country[] getHomeCountries()
	{
	debug("Defender: getHomeCountries");

	// Count countries owned
	int numMyCountries = 0;
	CountryIterator mine = new PlayerIterator(ID, countries);
	while (mine.hasNext())
		{
		Country discard = mine.next();
		numMyCountries++;
		}
	debug("  --> numMyCountries: "+numMyCountries);


	// Set new Country array, using numMyCountries to specify the length of the array
	Country[] homeCountries = new Country[ numMyCountries ];

	// Insert countries owned
	CountryIterator owned = new PlayerIterator(ID, countries);
	for (int i = 0; i <  numMyCountries; i++)
		{
		homeCountries[i] = owned.next();
		debug("  ----> homeCountries[i]:"+this.homeCountries[i]);
		}
	return homeCountries;
	}

User avatar
dustin
Lux Creator
Lux Creator
Posts: 10915
Joined: Thu May 15, 2003 2:01 am
Location: Cascadia
Contact:

Post by dustin » Mon Jul 09, 2007 3:45 pm

This is how I would do it.

Code: Select all

public Country[] getHomeCountries()
	{
	// Put all our countries into a Vector
	Vector list = new Vector();
	CountryIterator mine = new PlayerIterator(ID, countries);
	while (mine.hasNext())
	  {
	  list.add(mine.next());
	  }

   // Transfer the Vector into an array
	Country[] homeCountries = new Country[ list.size() ];
	homeCountries = (Country[]) list.toArray(homeCountries);
	return homeCountries;
	} 

User avatar
SunTzu
Lux Cartographer
Posts: 1586
Joined: Sat Jan 14, 2006 1:48 am
Location: Maryland

Post by SunTzu » Mon Jul 09, 2007 4:06 pm

Thanks Dustin, it worked perfectly!


I've been going through the Java tutorials, but haven't learned about Vectors yet.

User avatar
Bertrand
Reaper Creator
Posts: 568
Joined: Mon Nov 28, 2005 4:35 pm
Location: Montreal

Post by Bertrand » Mon Jul 09, 2007 6:13 pm

Sun, I'm guessing here, but are you building the mine array in order to know whether or not a given country was yours at game beginning?

If yes, there is a better way, with a boolean array that you can build like this:

Code: Select all

boolean[] wasMine = new boolean[board.getNumberOfCountries()];
for (int i = 0; i < board.getNumberOfCountries(); i++)
    wasMine[i] = countries[i].getOwner() == ID;
Then, later on, you can look for countries to attack like this:

Code: Select all

if (country.getOwner() != ID  &&  wasMine[country.getCode()])
   // country must be attacked!

Post Reply