Skip to content

Instantly share code, notes, and snippets.

@ianbishop
Created October 30, 2011 17:34
Show Gist options
  • Select an option

  • Save ianbishop/1326162 to your computer and use it in GitHub Desktop.

Select an option

Save ianbishop/1326162 to your computer and use it in GitHub Desktop.
initial boat placement for battleship game
/*
Initialize all boat positions for a given player
*/
private boolean initBoatPositions(String message) {
boatPositions = new String[(Player.boats).length][];
String[] boatInfo = message.split(",");
ArrayList<String> usedPositions = new ArrayList<String>();
for(String boat : boatInfo) {
int boatIndex;
String[] explodedBoat = boat.split("\\s+");
for(boatIndex=0; boatIndex < (Player.boats).length; boatIndex++)
if(explodedBoat[0].equals(Player.boats[boatIndex]))
break;
if(boatIndex >=0) {
if(!addBoat(boatIndex, explodedBoat, usedPositions)) {
return false;
}
}
else
return false;
}
return true;
}
/*
Add a boat position to the player's boat setup.
*/
private boolean addBoat(int boatIndex, String[] explodedBoat, ArrayList<String> usedPositions) {
if(boatPositions[boatIndex] != null)
return false;
if(explodedBoat.length-1 != Player.boatLengths[boatIndex])
return false;
boatPositions[boatIndex] = new String[Player.boatLengths[boatIndex]];
for(int i=1; i < explodedBoat.length; i++) {
if(validPosition(explodedBoat[i]) && !usedPositions.contains(explodedBoat[i])) {
boatPositions[boatIndex][i-1] = explodedBoat[i];
usedPositions.add(explodedBoat[i]);
}
else
return false;
}
String fPos = boatPositions[boatIndex][0];
char i;
int j, ncol, nrow;
ncol = nrow = 0;
i = fPos.charAt(0);
j = Integer.parseInt(fPos.substring(1,fPos.length()));
for(String pos : boatPositions[boatIndex]) {
if(pos.charAt(0) == i)
nrow++;
if(Integer.parseInt(pos.substring(1, pos.length())) == j)
ncol++;
}
if((ncol != Player.boatLengths[boatIndex]) && (nrow != Player.boatLengths[boatIndex]))
return false;
return true;
}
/*
Validates that a given string position
is a valid position on the game board
(in range A1-J10)
*/
private boolean validPosition(String position) {
try {
if(1 < position.length() && position.length() < 4) {
int m = position.charAt(0) - 64;
int n = Integer.parseInt(position.substring(1, position.length()));
if(m > 10 || n < 1)
return false;
if(1 < (m+n) && (m+n) < 21)
return true;
}
return false;
} catch(NumberFormatException nfe) {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment