Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Battleships {
- /*
- * Program: Battleships.java
- * Purpose: Emulate popular board game
- * Creator: Chris Clarke
- * Created: 26.03.2012
- */
- // change this to a create larger or smaller board, e.g. 5 or 7
- static final int BOARDSIZE = 6;
- // create global array
- static int [][] grid = new int[BOARDSIZE][BOARDSIZE];
- // create global variables
- static int row, column;
- public static void main(String args[]) {
- Scanner scanner = new Scanner(System.in);
- int hits = 0, misses = 0;
- int numShips = 0;
- // set all grid values to zero
- for (int r = 0; r < BOARDSIZE; r++) {
- for (int c = 0; c < BOARDSIZE; c++) {
- grid[r][c] = 0;
- }
- }
- // display board dimensions
- System.out.println("Board size = "+BOARDSIZE+" by "+BOARDSIZE);
- System.out.println("Row and column are 0 to "+(BOARDSIZE-1));
- // set the number of ships on the board
- do {
- System.out.print("Enter number of ships(1..5): ");
- numShips = scanner.nextInt();
- } while (numShips<1||numShips>5);
- // set targets, 1 for each ship
- for (int i=0; i<numShips; i++)
- setTarget();
- // keep getting user input and checking it
- do {
- // get row
- System.out.print("Enter row: ");
- row = scanner.nextInt();
- // get column
- System.out.print("Enter column: ");
- column = scanner.nextInt();
- // check valid row and column
- if ( row < 0 || row > (BOARDSIZE-1))
- System.out.println( "Error in row number");
- else if ( column < 0 || column > (BOARDSIZE-1))
- System.out.println( "Error in column number");
- else if ( grid[row][column] == 1) {
- System.out.println( "***** hit! *****");
- // will need to register as a miss if same square tried again,
- // so change value
- grid[row][column] = 2;
- hits++;
- } else {
- System.out.println( "miss!");
- misses++;
- }
- } while (hits<numShips);
- System.out.print("Game Over. You won in ");
- int attempts = hits + misses;
- if (attempts == 1) {
- System.out.println("1 attempt. Lucky!");
- } else {
- System.out.println(attempts+" attempts.");
- }
- }
- public static void setTarget() {
- // select a blank square at random, set its value to 1
- row = (int) (Math.random()*BOARDSIZE); // 0 to BOARDSIZE-1 inclusive
- column = (int) (Math.random()*BOARDSIZE); // 0 to BOARDSIZE-1 inclusive
- if (grid[row][column]==0) { // blank square
- grid[row][column] = 1; // set a battleship
- } else {
- setTarget(); // recursive procedure call
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment