I am currently working on a primitive ants vs zombies game for a class project. We are to read in a 'horde' file that contains characters corresponding to a Zombie that will be invading and an integer(1-9inclusive) that represents a multiple of the previous zombie char. What I am having trouble is differentiating between int and char within the file string and how to create multiple objects depending on the int. This is what I have so far:
public void readHordeFile(String filename){
try {
file = new FileReader(filename);
} catch (FileNotFoundException e) {
System.out.println("File not found " + e.getMessage());
}
buf = new BufferedReader(file);
try {
zombieString = buf.readLine();
for(int i = 0; i < zombieString.length(); i++){
if(zombieString.charAt(i) == 'S'){
horde.add(new ZombieScientist());
}else if(zombieString.charAt(i) == 'Z'){
horde.add(new StandardZombie());
}else if(zombieString.charAt(i) == 'I'){
horde.add(new InfectedZombie());
}else if(zombieString.charAt(i) == 1){
}
}
} catch (IOException e) {
e.getMessage();
}
}
an example file contains : SZI1
I was thinking of just hard-coding each number but I still run into the problem of not knowing how to add multiples of the same object. I would really appreciate any help. Thank you all in advance.
You can still check integer in char format like this.
else if(zombieString.charAt(i) == '1'){
}
if it is 1,2 or 3 you can check it in this way.
if you want to add multiple objects you can create a list of objects and add to "horde" object
To tell if a code point in a string is numeric you use the Character.isDigit method; to get a portion of your string into an int you use the Integer.parseInt method.
A few things; this is un-tested code so take it as more of a hint;
You should probably start by breaking the zombie creation up into its own method, so your loop looks something like;
zombieString = buf.readLine();
for(int i = 0; i < zombieString.length(); i++){
Character ch = zombieString.charAt(i);
addZombie(horde, ch);
}
Then you could just save the latest created zombie in a state variable;
Character previousZombie = ' ';
zombieString = buf.readLine();
for(int i = 0; i < zombieString.length(); i++){
Character ch = zombieString.charAt(i);
previousZombie = ch;
addZombie(horde, ch);
}
...and add a check if the next character is a digit and if so just add the correct number of the previous zombie.
Character previousZombie = ' ';
zombieString = buf.readLine();
for(int i = 0; i < zombieString.length(); i++){
Character ch = zombieString.charAt(i);
if(!Character.isDigit(ch))
{
previousZombie = ch;
addZombie(horde, ch);
}
else
{
for(int j='1'; j<ch; j++)
addZombie(horde, previousZombie);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.