Battleship spil
HejJeg er ved at lave et battleship spil, som er lektie på mit nye studie. Jeg kan dog ikke få den til at gøre en bestemt ting, nemlig at erstatte det første C i strengen til et X, jeg bruger replaceFirst(), men uden held? Er der nogen der kan se hvad jeg gør galt?
import java.util.*;
public class BattleshipExercise4 {
public static String carrier = "CCCC";
public static String battleShip = "BBBB";
public static String destroyer = "DDD";
public static String submarine = "S";
public static String patrol = "PP";
public static String star = "*";
public static int Board = 12;
public static void main ( String [] args ) {
Scanner console = new Scanner ( System.in );
createBoard ();
System.out.println ();
System.out.print ( "Indtast venligst din breddegrad og længdegrad, adskilt med mellemrum: " );
int userWidth = console.nextInt();
int userHeight = console.nextInt();
shootAt ( userWidth, userHeight );
}
//Methods
//Board
public static void createBoard () {
printLine ( star, 0 );
printLine ( star, 0 );
printLine ( carrier, 3 );
printLine ( battleShip, 7 );
printLine ( star, 0 );
printLine ( star, 0 );
printLine ( destroyer, 6 );
printLine ( star, 0 );
printLine ( star, 0 );
printLine ( submarine, 1 );
printLine ( patrol, 6 );
}
public static void printLine ( String character, int starsBefore ) {
for ( int i = 1; i <= starsBefore; i++ ) {
System.out.print ( star );
}
System.out.print ( character );
for ( int k = 1; k <= ( Board - ( character.length() + starsBefore ) ); k++ ) {
System.out.print ( star );
}
System.out.println ();
}
//ShootAt
public static void shootAt ( int width, int height ) {
if ( width == 4 && height == 3 ) {
System.out.println ( "Du ramte en carrier!" );
carrier.replaceFirst ( "C", "X" );
} else if ( width == 8 && height == 11 ) {
System.out.println ( "Du ramte et Battleship!" );
battleShip.replaceFirst ( "B", "X" );
} else if ( width == 7 && height == 7 ) {
System.out.println ( "Du ramte en destroyer!" );
} else if ( width == 2 && height == 10 ) {
System.out.println ( "Du ramte en submarine!" );
} else if ( width == 7 && height == 12 ) {
System.out.println ( "Du ramte en patrolboat." );
} else {
System.out.println ( "Forbier! - Prøv igen!" );
}
createBoard();
}
}