package model_pkg;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import def_classes.Point;
/**
*
* @author Alving J.
*/
public class BalloonInitializer {
private File file; // To hold the file
private BufferedReader reader; // To buffer and read content from the file
private String line; // To hold a line from the file
private int balloonAmount; // The amount of balloons in the level
private Point position; // The position of the balloon;
private ArrayList<Point> balloonPositions; // Array containing all positions of the balloons
/**
* Constructs a BalloonInitializer
* @param initFile
*/
public BalloonInitializer(String initFile) {
balloonPositions = new ArrayList<Point>();
try {
file = new File(initFile);
reader = new BufferedReader(new FileReader(file));
try {
readBalloonAmount();
for (int i = 0; i < balloonAmount; i++) {
readPosition();
balloonPositions.add(position);
}
}
finally {
reader.close();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Reads the value of BALLOON_AMOUNT
* @throws IOException
*/
private void readBalloonAmount() throws IOException {
getIdentifier();
if (line.contains("BALLOON_AMOUNT")) {
balloonAmount = Integer.valueOf(line.substring(line.indexOf('=')+1, line.indexOf(';')));
}
}
/**
* Reads the value of POSITION
* @throws IOException
*/
private void readPosition() throws IOException {
int x, y;
getIdentifier();
if (line.contains("POSITION")) {
x = Integer.valueOf( line.substring(line.indexOf('(')+1, line.indexOf(',')) );
y = Integer.valueOf( line.substring(line.indexOf(',')+1, line.indexOf(')')) );
position = new Point(x, y);
}
}
/**
* Searches the text-file for a line containing an identifier (e.g. POSITION)
* @throws IOException
*/
private void getIdentifier() throws IOException {
line = reader.readLine();
while (!line.contains("=")) {
line = reader.readLine();
}
}
/**
* Returns the amount of balloons in the level
* @return The amount of balloons in the level
*/
public int getBalloonAmount() {
return balloonAmount;
}
/**
* Returns the position of a balloon
* @param index The index of balloon
* @return The position of the balloon
*/
public Point getPosition(int index) {
return balloonPositions.get(index);
}
}