mercredi 4 mars 2015

Selecting first key from hashmap meets if statement

Is there a way to choose first key from a hashmap that meets certain condition?


As part of my coursework I need to write a battleship "game".


I have two hashmaps, one with encounters that ships can fight in and another one with all the ships. Encounter and ships have battle level and the one with higher battle skill wins.


The problem I'm having is that user is only allowed to enter encounter no. in which he wants to fight. Once encounter is chosen, it then should select a random ship from the hashmap, see if the ship can fight in that encounter type(not every ship can fight in every encounter) and if it can then it compares the battle skill and returns final result.


Basically I dont know make my program select a first key from my hashmap and if that one cant fight then it selects next one until it finds one that can fight.



public String fightEncounter(int encNo)
{
String s = "";
if ( encounterList.get(encNo) != null)
{
if (!allActiveShips.isEmpty())
{
if ( canFight(encNo) == true)
{
for (Ship sh : allActiveShips.values())
{
if (encounterList.get(encNo).getSkillReq() < allActiveShips.get(sh).getBattleSkill())
{
s = s + (" Encounter won by : " + s.toString());
chest = chest + encounterList.get(encNo).getPlunder();
sh.setShipState(ShipState.RESTING);
}
else if ( allActiveShips.isEmpty() )
{
s = s + (" Encounter lost as no ships available ");
chest = chest - encounterList.get(encNo).getPlunder();
}
else if ( encounterList.get(encNo).getSkillReq() > allActiveShips.get(sh).getBattleSkill() )
{
s = s + (" Encounter lost on battle skill leve and " + sh.getShipName() + " sunk ");
chest = chest - encounterList.get(encNo).getPlunder();
sh.setShipState(ShipState.SUNK);
if ( isDefeated() == true )
{
s = s + (" You have been defeated");
}
}
}
}
else
{
return("CANT FIGHT");
}

}
else
{
return("No ship to available");
}
}
return s;
}


I have also written a private method in the same class which checks if Ship can fight in chosen encounter and that's the method I can't write :



private boolean canFight(int encNo)
{
if ( encounterList.containsValue(encNo))
{
for (Ship s : allActiveShips.values())
{
if (s.getShipType() == "ManOwar" && encounterList.get(encNo).getEncounterType() == EncounterType.BATTLE && encounterList.get(encNo).getEncounterType() == EncounterType.BLOCKADE )
{
return true;
}
else if (s.getShipType() == "Sloop" && encounterList.get(encNo).getEncounterType() == EncounterType.BATTLE && encounterList.get(encNo).getEncounterType() == EncounterType.SKIRMISH )
{
return true;
}
else if (s.getShipType() == "Frigate" && ((Frigate)s).isPinnace() == true )
{
return true;
}
else if (s.getShipType() == "Frigate" && encounterList.get(encNo).getEncounterType() == EncounterType.BATTLE && encounterList.get(encNo).getEncounterType() == EncounterType.SKIRMISH )
{
return true;
}
}
}
return false;
}




Aucun commentaire:

Enregistrer un commentaire