Results 1 to 2 of 2
  1. #1
    Lucid15 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Default Help with Revised Battleship program

    Battleship.java
    Java Code:
    package battleship;
    
    import java.util.Random;
    
    import java.util.Scanner;
    
    import static ljing.Program.*;
    
    public class Battleship {
    	private int[][] myfield;
    	private int[][] compfield;
    	private int[][] pos;
    	Board board;
    	Board comboard;
    	Board hiddenboard;
    	private int hit;
    	private int comphit;
    	public boolean shipdetect;
    	public Ship[][] shipLocations;
    	private int comphitstreak;
    	private int randomrow;
    	private int randomcol;
    
    	public int getHits() {
    		return hit;
    	}
    
    	public void setHits() {
    		hit++;
    	}
    
    	public int getCompHits() {
    		return comphit;
    	}
    
    	public void setCompHits() {
    		comphit++;
    	}
    
    	public static void main(String[] args) {
    		Battleship battleship = new Battleship();
    		battleship.run();
    	}
    	
    	public Battleship() {
    		
    		myfield = new int[10][10];
    		compfield = new int[10][10];
    		pos = new int[10][10];
    		
    		board = new Board(myfield);
    		comboard = new Board(compfield);
    		hiddenboard = new Board(pos);
    		
    		hit = 0;
    		comphit = 0;
    		shipdetect = false;
    		comphitstreak = 0;
    		randomrow = 0;
    		randomcol = 0;
    		
    		shipLocations = new Ship[10][10];
    	}
    
    	public void run() {
    		Ship boat = new Ship(2, "Boat", this, 1);
    		boat.placeShip(myfield);
    		boat.placeShip(compfield);
    
    		Ship cruise = new Ship(3, "Cruise", this, 2);
    		cruise.placeShip(myfield);
    		cruise.placeShip(compfield);
    
    		Ship sub = new Ship(4, "SubMarine", this, 3);
    		sub.placeShip(myfield);
    		sub.placeShip(compfield);
    
    		Ship battle = new Ship(5, "Battleship", this, 4);
    		battle.placeShip(myfield);
    		battle.placeShip(compfield);
    
    //		Ship air = new Ship(6, "AirCraftCarrier", this, 5);
    //		air.placeShip(myfield);
    //		air.placeShip(compfield);
    
    		while (hit < 14 && comphit < 14) {
    			printLine(" ");
    			System.out.println("     Your Field");
    			System.out.println("");
    			board.displayField(myfield);
    			printLine(" ");
    			System.out.println("     Computer Field");
    			System.out.println("");
    			hiddenboard.displayField(compfield);
    			attack(pos, compfield);
    			if (shipdetect) {
    				compattackhit(myfield);
    			}
    
    			else {
    				compattack(myfield);
    			}
    			if (hit == 14)
    				System.out.println("YOU WIN!");
    			if (comphit == 14)
    				System.out.println("COMPUTER WIN!");
    		}
    	}
    
    	public int randomRow() {
    		Random r = new Random();
    		int randrow = r.nextInt(10);
    		return randrow;
    	}
    
    	public int randomCol() {
    		Random r = new Random();
    		int randcol = r.nextInt(10);
    		return randcol;
    	}
    
    	public void attack(int[][] a, int[][] b) {
    		int row = 0;
    		int col = 0;
    		do {
    			Scanner reader = new Scanner(System.in);
    			System.out
    					.println("Attack: X and Y coordinate in one command separated by a space (not comma)");
    			row = reader.nextInt();
    			col = reader.nextInt();
    			System.out.println(row);
    			System.out.println(col);
    		} while (!isLegal(a, b, row, col));
    
    		if (b[col - 1][row - 1] == 1) {
    			b[col - 1][row - 1] = 3;
    			a[col - 1][row - 1] = 3;
    			setHits();
    			System.out.println("Hit!");
    			printLine("Hits now = " + getHits());
    
    		} else {
    			b[col - 1][row - 1] = 2;
    			a[col - 1][row - 1] = 2;
    			System.out.println("Missed!");
    		}
    
    	}
    
    	private boolean isLegal(int[][] a, int[][] b, int row, int col) {
    		if (row <= 0 || col <= 0 || row > 10 || col > 10) {
    			System.out.println("coordinates out of board. Use different value");
    			System.out.println();
    			row = 0;
    			col = 0;
    			attack(a, b);
    			return false;
    		}
    
    		if (b[col - 1][row - 1] == 2 || b[col - 1][row - 1] == 3) {
    			System.out
    					.println("You already used this coordinate! Use another one!");
    			row = 0;
    			col = 0;
    			attack(a, b);
    			return false;
    		}
    		return true;
    	}
    
    	private boolean isCompLegal(int[][] a, int randomrow, int randomcol) {
    		printLine("Checking Computer's random coordinates.... "
    				+ (randomrow + 1) + "," + (randomcol + 1));
    		if (randomrow < 0 || randomcol < 0 || randomrow >= 10
    				|| randomcol >= 10) {
    			System.out.println("coordinates out of board. Use different value");
    			System.out.println();
    			randomrow = 0;
    			randomcol = 0;
    			if (shipdetect) {
    				compattackhit(a);
    			} else {
    				compattack(a);
    			}
    			return false;
    		}
    
    		if (a[randomcol][randomrow] == 2 || a[randomcol][randomrow] == 3) {
    			System.out
    					.println("You already used this coordinate! Use another one!");
    			randomrow = 0;
    			randomcol = 0;
    			if (shipdetect) {
    				compattackhit(a);
    			} else {
    				compattack(a);
    			}
    			return false;
    		}
    
    		return true;
    	}
    
    	public void compattack(int[][] a) {
    		randomRow();
    		randomCol();
    		do {
    			randomrow = randomRow();
    			randomcol = randomCol();
    		} while (!isCompLegal(a, randomrow, randomcol));
    		if (a[randomcol][randomrow] == 1) {
    			a[randomcol][randomrow] = 3;
    			printLine("You are Hit! at " + (randomrow + 1) + " , "
    					+ (randomcol + 1));
    			setCompHits();
    			shipdetect = true;
    			printLine("Comphits now = " + getCompHits());
    		} else {
    			a[randomcol][randomrow] = 2;
    			printLine("Computer Missed at " + (randomrow + 1) + " , "
    					+ (randomcol + 1));
    		}
    
    	}
    
    	public void compattackhit(int[][] a) {
    		randomRow();
    		randomCol();
    		printLine("Entering compattackhit method where AI will be soon implemented, firing random shots for now..");
    		do {
    
    			randomrow = randomRow();
    			randomcol = randomCol();
    
    		} while (!isCompLegal(a, randomrow, randomcol));
    
    		if (a[randomcol][randomrow] == 2 || a[randomcol][randomrow] == 3) {
    			System.out
    					.println("You already used this coordinate! Use another one!");
    
    		}
    
    		if (a[randomcol][randomrow] == 1) {
    			a[randomcol][randomrow] = 3;
    			printLine("You are Hit! at " + (randomrow + 1) + " , "
    					+ (randomcol + 1));
    			setCompHits();
    			comphitstreak = 2;
    			printLine("comphits now = " + getCompHits());
    		} else {
    			a[randomcol][randomrow] = 2;
    			printLine("Computer Missed at " + (randomrow + 1) + " , "
    					+ (randomcol + 1));
    			shipdetect = false;
    			comphitstreak = 0;
    		}
    	}
    
    }
    // comphitstreak = how many successful hits in a row... 1 = last move was a
    // hit.. 2 = should know orientation if same ship was hit with next shot
    Board.java
    Java Code:
    package battleship;
    
    import java.util.Random;
    import static ljing.Program.*;
    import java.util.Scanner;
    
    public class Board {
    
    	public Board(int[][] a) {
    		
    		for (int col = 1; col < a.length; col++) {
    			for (int row = 1; row < a.length -1; row++) {
    				a[row][col] = 0;
    			}
    		}
    	}
    
    	public void displayField(int[][] a) {
    		System.out.println("      ----------------");
    		System.out.println("      ");
    		System.out.println("    1 2 3 4 5 6 7 8 9 10");
    		System.out.println("    -----------------");
    		int rownum = 1;
    		for (int row = 0; row < a.length; row++) {
    			if (row < 9){
    			System.out.print(rownum + "| ");
    			}
    			else{
    				System.out.print(rownum + "|");
    			}
    			rownum++;
    			for (int col = 0; col < a[0].length; col++) {
    				System.out.print(" " + a[row][col]);
    			}
    			System.out.println();
    		}
    	}
    }
    Ship.java
    Java Code:
    package battleship;
    
    import java.util.Random;
    import static ljing.Program.*;
    
    
    public class Ship {
        
    	private int size;
        String name;
        private int value;
        
        
        public Ship(int size, String name, Battleship game, int value){
            this.size = size;
            this.name = name;
            this.game = game;
            this.value = value;
        }
         
    
    private Battleship game;
    	public void placeShip(int [][]a)
        {
    		//ADD CHECKER HERE
           Random r = new Random();
           int orientation = r.nextInt(2);
           if(orientation == 0)//Vertical Ship
           {
              int x = r.nextInt(10);
              int y = r.nextInt(10-size);
              for(int z=0;z<size;z++)
              {
            	
                 a[y+z][x] = 1;
                 game.shipLocations[y+z][x] = this;
                 System.out.println(game.shipLocations[y+z][x]);
              }              
           }
           else//Horizontal Ship
           {
              int x = r.nextInt(10-size);
              int y = r.nextInt(10);
              for(int z=0; z < size; z++)
              {
                 a[y][x+z] = 1;
                 game.shipLocations[y][x+z] = this;
              } 
           }
        }
    	
    	public String toString() {
    		return size+" "+name+" "+value;
    	}
     
    }
    I have a few questions on suggestions on how to implement a couple of things.
    1. In the ship class i have inserted the position of each ship into a new array shipLocations, but am confused as to how i can manipulate this array further to actually track how many hits a ship has left, and if it has been "sunk", any solutions would be appreciated.

    2. In my placeShip method in Ship.java, i put a comment in there for a placeShip checker method, because sometimes the method will not place a certain ship, how would i produce random values, store them, check them, and then use them to place a ship in the most efficient way regarding the code i have now?

    3. Eventually i want to edit the compattackhit method in Battleship.java so it fire a shot that is next to a previously successful shot (hit), and one that makes sense. It needs to make sure its a valid coordinate, make sure it hasnt been chosen, and if it has 2 successful hits, you are likely to know the orientation of a ship. Again, not sure on the best approach to this either.

    4. Finally, i am going to eventually start on the GUI once the above questions are solved. I would like to make the playable board or grid clickable to the user to fire shots instead of having to input coordinates, is this an easy thing to do, or should i just make 2 editable coordinate text fields to input coordinates? If the clickable board is easy to do, would i just make a grid of jButtons?

    I am just trying to make sure i approach each question the best possible way, and again, I thank you in advance for any help you provide.

  2. #2
    Lucid15 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Default Re: Help with Revised Battleship program

    Started to work on the gui
    BattleshipGui
    Java Code:
    package battleship;
    
    import static battleship.Battleship.*;
    import static java.awt.Color.BLACK;
    import static java.awt.Color.RED;
    import static java.awt.Color.WHITE;
    import static java.awt.Color.GRAY;
    
    import javax.swing.JComponent;
    
    import ljing.*;
    
    /** Graphic user interface for the Battleship game. */
    public class BattleshipGui extends Gui {
    
    	public static void main(String[] args) {
    		new BattleshipGui().display();
    	}
    
    	/** The game behind this gui. */
    	private Battleship game;
    
    	/** Instructions to the users. */
    	private Label instructions;
    	private Label row;
    	private Label column;
    	private int ro = 1;
    	private int co = 1;
    
    	/** Array of graphic squares. */
    	private Square[][] squares;
    
    	public BattleshipGui() {
    		game = new Battleship();
    		squares = new Square[10][10];
    		for (int r = 0; r < 10; r++) {
    			for (int c = 0; c < 10; c++) {
    				squares[r][c] = new Square(30, 30, r, c, this);
    				add(squares[r][c], 175 + c * 30, 150 + r * 30);
    				row = new Label (""+ (ro));
    				add(row, 173 + c * 30, 125 + r * 30);
    				column = new Label (""+ (co));
    				add(column, 140, 125 + r * 30 );
    				ro++;
    				co++;
    			}
    		}
    		instructions = new Label(
    				"Enter coordinates, and click fire to attack. First person to sink all ships (14 hits) wins!");
    		add(instructions, 300, 600);
    	
    
    	}
    
    	/** Reacts to the user clicking on a square. */
    	protected void squareClicked(int row, int column) {
    		for (int r = 0; r < 10; r++) {
    			for (int c = 0; c < 10; c++) {
    				if (game.shipLocations[row][column] != null) {
    					squares[r][c].setFill(GRAY);
    					
    				}
    			}
    		}
    		repaint();
    	}
    
    }
    Square.java
    Java Code:
    package battleship;
    
    import static java.awt.Color.BLACK;
    import static java.awt.Color.WHITE;
    import ljing.Rectangle;
    
    /** Graphic square for the Battleship game. */
    public class Square extends Rectangle {
    
    	/** Row of this square. */
    	private int row;
    	
    	/** Column of this square. */
    	private int column;
    	
    	/** Gui associated with this square. */
    	private BattleshipGui gui;
    	
    	public Square(int width, int height, int row, int column, BattleshipGui gui) {
    		super(width, height, null, null, null);
    		this.row = row;
    		this.column = column;
    		this.gui = gui;
    			setFill(WHITE);
    			setOutline(BLACK);
    		
    		}
    	
    
    	/** Tells the gui that the mouse was pressed over this square. */
    	public void mousePressed() {
    		gui.squareClicked(row, column);
    	}
    
    }
    /
    The Questions i have now is.. how would i make vertical labels for the rows like i did columns? Also, how will i correspond the right square in the gui with a spot on each board(myboard, compfield, hiddenboard) in the game so i can correctly display hits, misses, and friendly ship when its the players turn?

Similar Threads

  1. Battleship Program Coding Assistance
    By nekaneka19 in forum New To Java
    Replies: 7
    Last Post: 03-21-2012, 06:26 PM
  2. Having trouble, Battleship program
    By Corrrrr in forum New To Java
    Replies: 15
    Last Post: 03-09-2012, 03:08 AM
  3. Help with Battleship program! 2D arrays
    By tylerkung in forum New To Java
    Replies: 3
    Last Post: 09-23-2011, 01:45 PM
  4. need help creating a battleship like program
    By ss1 in forum New To Java
    Replies: 12
    Last Post: 08-19-2011, 12:00 AM
  5. Battleship 2D Array Program
    By AaronHopkins in forum New To Java
    Replies: 6
    Last Post: 04-05-2011, 04:38 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •