Jump to content

  • Log In with Google      Sign In   
  • Create Account

Battleship in java


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
18 replies to this topic

#1 4mad3u5   Members   -  Reputation: 116

Like
0Likes
Like

Posted 07 August 2014 - 02:06 PM

Hi I made a battleship game in java and there are a couple of places that I would like to reduce the code as much as I can. Because in battleship you are entering in a character and and number for a coordinate system I am having to assign a 1 to a two denominational array and do if loops to determine what part of the array I want to assign to 1: if c == a then a[rowinput][1]. I have made an class Ship and made two different object arrays for the ships of both players. I don't want to run through these big if loops each time I want to initialize my arrays I want to do them both at the same time. If anyone has any ideas on how I could shorten this code please let me know. 


import java.util.*;

public class a4 
{
  public static void main( String args[] ) 
  {
	Ship[] s1 = new Ship[5];
	Ship[] s2 = new Ship[5];

	Scanner in = new Scanner(System.in);
	

	s1[0] = new Ship(1,"Aircraft carrier",5,1,'a',1,'e',0);  // player, ship, size, row front, column front, row back, column back, hit
	s1[1] = new Ship(1,"Battleship",      4,2,'b',5,'b',0);
 	s1[2] = new Ship(1,"Submarine",       3,2,'c',4,'c',0);
	s1[3] = new Ship(1,"Destroyer",       3,2,'d',4,'d',0);
	s1[4] = new Ship(1,"Patrol boat",     2,2,'e',3,'e',0);

	s2[0] = new Ship(1,"Aircraft carrier",5,1,'a',1,'e',0);  // player, ship, size, row front, column front, row back, column back, hit
	s2[1] = new Ship(1,"Battleship",      4,2,'b',5,'b',0);
 	s2[2] = new Ship(1,"Submarine",       3,2,'c',4,'c',0);
	s2[3] = new Ship(1,"Destroyer",       3,2,'d',4,'d',0);
	s2[4] = new Ship(1,"Patrol boat",     2,2,'e',3,'e',0);


	int[][] b1  = new int[11][11];
	int[][] g1 = new int[11][11];
	int[][] a1 = new int[11][11];
	int[][] f1 = new int[11][11];

	int[][] b2  = new int[11][11];
	int[][] g2 = new int[11][11];
	int[][] a2 = new int[11][11];
	int[][] f2 = new int[11][11];

	int i = 0;
	int j = 0;
	int k = 0;
	int l = 0;
	int m = 0;
	//int true = 1;
	int b = 0;
	int player = 1;	
	char c;
	int inrow;
	int count1 = 0;
	int count2 = 0;



	for(Ship e: s1)	
	{

 		
		if((e.getColf() == 'a' || e.getColf() == 'A'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][1] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 1; i < (1+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}


		
		if((e.getColf() == 'b' || e.getColf() == 'B'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][2] = 1;

			if(e.getRowf() == e.getRowb())
				for(i = 2; i < (2+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}



		if((e.getColf() == 'c' || e.getColf() == 'C'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][3] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 3; i < (3+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}

		if((e.getColf() == 'd' || e.getColf() == 'D'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][4] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 4; i < (4+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}  

		if((e.getColf() == 'e' || e.getColf() == 'E'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][5] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 5; i < (5+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}   

		if((e.getColf() == 'f' || e.getColf() == 'F'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][6] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 6; i < (6+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}   

		if((e.getColf() == 'g' || e.getColf() == 'G'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][7] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 7; i < (7+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}  

		if((e.getColf() == 'h' || e.getColf() == 'H'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); j < (e.getRowf()+e.getSize()); i++ )
					b1[i][8] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 8; i < (8+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}   

		if((e.getColf() == 'i' || e.getColf() == 'I'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); j < (e.getRowf()+e.getSize()); i++ )
					b1[i][9] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 9; i < (9+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}   

		if((e.getColf() == 'j' || e.getColf() == 'J'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); j < (e.getRowf()+e.getSize()); i++ )
					b1[i][10] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 10; i < (10+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
			
		}       

               
	}



	for(Ship e: s2)	
	{

 		
		if((e.getColf() == 'a' || e.getColf() == 'A'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][1] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 1; i < (1+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}


		
		if((e.getColf() == 'b' || e.getColf() == 'B'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][2] = 1;

			if(e.getRowf() == e.getRowb())
				for(i = 2; i < (2+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}



		if((e.getColf() == 'c' || e.getColf() == 'C'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][3] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 3; i < (3+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}

		if((e.getColf() == 'd' || e.getColf() == 'D'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][4] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 4; i < (4+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}  

		if((e.getColf() == 'e' || e.getColf() == 'E'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][5] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 5; i < (5+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}   

		if((e.getColf() == 'f' || e.getColf() == 'F'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][6] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 6; i < (6+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}   

		if((e.getColf() == 'g' || e.getColf() == 'G'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); i < (e.getRowf()+e.getSize()); i++ )
					b1[i][7] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 7; i < (7+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}  

		if((e.getColf() == 'h' || e.getColf() == 'H'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); j < (e.getRowf()+e.getSize()); i++ )
					b1[i][8] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 8; i < (8+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}   

		if((e.getColf() == 'i' || e.getColf() == 'I'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); j < (e.getRowf()+e.getSize()); i++ )
					b1[i][9] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 9; i < (9+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
				
		}   

		if((e.getColf() == 'j' || e.getColf() == 'J'))
		{
			if(e.getColf() == e.getColb())
				for(i = e.getRowf(); j < (e.getRowf()+e.getSize()); i++ )
					b1[i][10] = 1;
				
			if(e.getRowf() == e.getRowb())
				for(i = 10; i < (10+e.getSize()); i++ )
					b1[e.getRowf()][i] = 1;
			
		}       

               
	}



	while((count1 < 17) || (count2 < 17))
	{



		
		


		System.out.println("\n\n\nPlayer: " + player + "'s turn:\n"); 
		if(player == 1)
		{
			b= 0;


			for(i = 1; i <= 10; i++)
			{
				for(j = 1; j <= 10; j++)
				{
					if(g1[i][j] == 3)
						System.out.print("* ");
					if(g1[i][j] == 1)
						System.out.print("X ");
					if(g1[i][j] == 0)
						System.out.print(g1[i][j] + " "); 
				}

				System.out.print("\n");
			}

			System.out.print("\nEnter a charactor from A - k for column and and number from 1 - 10 \nrespectively for the quardents of your shot: ");

			c = in.next().charAt(0);
			inrow  = in.nextInt();
		


			for(i = 1; i <= 10; i++)
				for(j = 1; j <= 10; j++)
					f1[i][j] = 5;




			if(c == 'A' || c == 'a')
				f1[inrow][1] = 1;
			if(c == 'B' || c == 'b')
				f1[inrow][2] = 1;
			if(c == 'C' || c == 'c')
				f1[inrow][3] = 1;
			if(c == 'D' || c == 'd')
				f1[inrow][4] = 1;
			if(c == 'E' || c == 'e')
				f1[inrow][5] = 1;
			if(c == 'F' || c == 'f')
				f1[inrow][6] = 1;
			if(c == 'G' || c == 'g')
				f1[inrow][7] = 1;
			if(c == 'H' || c == 'h')
				f1[inrow][8] = 1;
			if(c == 'I' || c == 'i')
				f1[inrow][9] = 1;
			if(c == 'J' || c == 'j')
				f1[inrow][10] = 1;




		


			for(i = 1; i <= 10; i++)
				for(j = 1; j <= 10; j++)
					if(  (f1[i][j] == 1) && (g1[i][j] == 3))
						b = 1;


	





			if( b == 0)
			{

				if(c == 'A' || c == 'a')
					g1[inrow][1] = 1;
				if(c == 'B' || c == 'b')
					g1[inrow][2] = 1;
				if(c == 'C' || c == 'c')
					g1[inrow][3] = 1;
				if(c == 'D' || c == 'd')
					g1[inrow][4] = 1;
				if(c == 'E' || c == 'e')
					g1[inrow][5] = 1;
				if(c == 'F' || c == 'f')
					g1[inrow][6] = 1;
				if(c == 'G' || c == 'g')
					g1[inrow][7] = 1;
				if(c == 'H' || c == 'h')
					g1[inrow][8] = 1;
				if(c == 'I' || c == 'i')
					g1[inrow][9] = 1;
				if(c == 'J' || c == 'j')
					g1[inrow][10] = 1;




				for(i = 1; i <= 10; i++)
					for(j = 1; j <= 10; j++)
					{
						if( b1[i][j] == 1 && g1[i][j] == 1)
						{
							for(Ship e : s1)
							{			
		
								for(k = 0; k <= 10; k++) 
								{
									for(l = 0; l <= 10; l++)
									{
										a1[k][l] = 0;
									}
								}


								if((e.getColf() == 'a' || e.getColf() == 'A'))
 									for(k = 1; k <= 10; k++)
									{

										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a1[l][1] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 1; m < 1+e.getSize(); m++)
											{
												a1[k][m] = 1;
											}

									}


		
								if((e.getColf() == 'b' || e.getColf() == 'B'))
 									for(k = 1; k <= 10; k++)
									{

										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a1[l][2] = 1;
		


										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 2; m < 2+e.getSize(); m++)
											{
												a1[k][m] = 1;
											}

					
	
									}


	
								if((e.getColf() == 'c' || e.getColf() == 'C'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a1[l][3] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 3; m < 3+e.getSize(); m++)
											{
												a1[k][m] = 1;
											}


					
	
									}

								if((e.getColf() == 'd' || e.getColf() == 'D'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a1[l][4] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 4; m < 4+e.getSize(); m++)
											{
												a1[k][m] = 1;
											}


					
	
									}   

								if((e.getColf() == 'e' || e.getColf() == 'E'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a1[l][5] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 5; m < 5+e.getSize(); m++)
											{
												a1[k][m] = 1;
											}


					
	
									} 

								if((e.getColf() == 'f' || e.getColf() == 'F'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a1[l][6] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 6; m < 6+e.getSize(); m++)
											{
												a1[k][m] = 1;
											}


					
	
									}  
								if((e.getColf() == 'g' || e.getColf() == 'G'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a1[l][7] = 1;



									if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
										for(m = 7; m < 7+e.getSize(); m++)
										{
											a1[k][m] = 1;
										}


					
		
									} 
								if((e.getColf() == 'h' || e.getColf() == 'H'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a1[l][8] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 8; m < 8+e.getSize(); m++)
											{
												a1[k][m] = 1;
											}


					
	
								}	   

								if((e.getColf() == 'i' || e.getColf() == 'I'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a1[l][9] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 9; m < 9+e.getSize(); m++)
											{
												a1[k][m] = 1;
											}


					
	
									}  

								if((e.getColf() == 'j' || e.getColf() == 'J'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a1[l][10] = 1;
	

										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 10; m < 10+e.getSize(); m++)
											{
												a1[k][m] = 1;
											}
									}


								for(k = 1; k<=10; k++)
									for(l = 1; l<=10; l++)
										if((a1[k][l] == 1) && (g1[k][l] ==1))
											g1[k][l] = 2;
									
												 
							
								for(k = 1; k<=10; k++)
									for(l = 1; l<=10; l++)
									{
										if((a1[k][l] == 1) && (g1[k][l] ==2))
										{
											e.setHit();
											count1++;	
											if(e.getHit() == e.getSize())
												System.out.print("you sunk my : " + e.getName() + "\n");
											else
												System.out.print("\n\nPlayer 1 hit a ship\n");
									
											g1[k][l] = 3;
										}		
									}	
							}	

						}
						//else
							//System.out.print("miss");
					}
	

			}
			else
				System.out.println("Guess already made");

		}
	


		if(player == 2)
		{
			b= 0;

			
			System.out.print("\n");

			for(i = 1; i <= 10; i++)
			{
				for(j = 1; j <= 10; j++)
				{
					if(g2[i][j] == 3)
						System.out.print("* ");
					if(g2[i][j] == 1)
						System.out.print("X ");
					if(g2[i][j] == 0)
						System.out.print(g2[i][j] + " "); 
				}

				System.out.print("\n");
			}

			System.out.print("\nEnter a charactor from A - k for column and and number from 1 - 10 \nrespectively for the quardents of your shot: ");
			c = in.next().charAt(0);
			inrow  = in.nextInt();



			for(i = 1; i <= 10; i++)
				for(j = 1; j <= 10; j++)
					f2[i][j] = 5;


			if(c == 'A' || c == 'a')
				f2[inrow][1] = 1;
			if(c == 'B' || c == 'b')
				f2[inrow][2] = 1;
			if(c == 'C' || c == 'c')
				f2[inrow][3] = 1;
			if(c == 'D' || c == 'd')
				f2[inrow][4] = 1;
			if(c == 'E' || c == 'e')
				f2[inrow][5] = 1;
			if(c == 'F' || c == 'f')
				f2[inrow][6] = 1;
			if(c == 'G' || c == 'g')
				f2[inrow][7] = 1;
			if(c == 'H' || c == 'h')
				f2[inrow][8] = 1;
			if(c == 'I' || c == 'i')
				f2[inrow][9] = 1;
			if(c == 'J' || c == 'j')
				f2[inrow][10] = 1;




		


			for(i = 1; i <= 10; i++)
				for(j = 1; j <= 10; j++)
					if(  (f2[i][j] == 1) && (g2[i][j] == 3))
						b = 1;


	
				

			System.out.print("\n");





			if( b == 0)
			{

				if(c == 'A' || c == 'a')
					g2[inrow][1] = 1;
				if(c == 'B' || c == 'b')
					g2[inrow][2] = 1;
				if(c == 'C' || c == 'c')
					g2[inrow][3] = 1;
				if(c == 'D' || c == 'd')
					g2[inrow][4] = 1;
				if(c == 'E' || c == 'e')
					g2[inrow][5] = 1;
				if(c == 'F' || c == 'f')
					g2[inrow][6] = 1;
				if(c == 'G' || c == 'g')
					g2[inrow][7] = 1;
				if(c == 'H' || c == 'h')
					g2[inrow][8] = 1;
				if(c == 'I' || c == 'i')
					g2[inrow][9] = 1;
				if(c == 'J' || c == 'j')
					g2[inrow][10] = 1;






				for(i = 1; i <= 10; i++)
					for(j = 1; j <= 10; j++)
					{
						if( b2[i][j] == 1 && g2[i][j] == 1)
						{
							for(Ship e : s2)
							{	


						
		
								for(k = 0; k <= 10; k++) 
								{
									for(l = 0; l <= 10; l++)
									{
										a2[k][l] = 0;
									}
								}


								if((e.getColf() == 'a' || e.getColf() == 'A'))
 									for(k = 1; k <= 10; k++)
									{

										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a2[l][1] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 1; m < 1+e.getSize(); m++)
											{
												a2[k][m] = 1;
											}

									}


		
								if((e.getColf() == 'b' || e.getColf() == 'B'))
 									for(k = 1; k <= 10; k++)
									{

										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a2[l][2] = 1;
		


										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 2; m < 2+e.getSize(); m++)
											{
												a2[k][m] = 1;
											}

					
	
									}


	
								if((e.getColf() == 'c' || e.getColf() == 'C'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a2[l][3] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 3; m < 3+e.getSize(); m++)
											{
												a2[k][m] = 1;
											}


					
	
									}

								if((e.getColf() == 'd' || e.getColf() == 'D'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a2[l][4] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 4; m < 4+e.getSize(); m++)
											{
												a2[k][m] = 1;
											}


					
	
									}   

								if((e.getColf() == 'e' || e.getColf() == 'E'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a2[l][5] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 5; m < 5+e.getSize(); m++)
											{
												a2[k][m] = 1;
											}


					
	
									} 

								if((e.getColf() == 'f' || e.getColf() == 'F'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a2[l][6] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 6; m < 6+e.getSize(); m++)
											{
												a2[k][m] = 1;
											}


					
	
									}  
								if((e.getColf() == 'g' || e.getColf() == 'G'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a2[l][7] = 1;



									if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
										for(m = 7; m < 7+e.getSize(); m++)
										{
											a2[k][m] = 1;
										}


					
		
									} 
								if((e.getColf() == 'h' || e.getColf() == 'H'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a2[l][8] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 8; m < 8+e.getSize(); m++)
											{
												a2[k][m] = 1;
											}


					
	
								}	   

								if((e.getColf() == 'i' || e.getColf() == 'I'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a2[l][9] = 1;



										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 9; m < 9+e.getSize(); m++)
											{
												a2[k][m] = 1;
											}


					
	
									}  

								if((e.getColf() == 'j' || e.getColf() == 'J'))
 									for(k = 1; k <= 10; k++)
									{
										if(e.getColf() == e.getColb() && (k == e.getRowf()))
											for(l = k; l < (k+e.getSize()); l++ )
												a2[l][10] = 1;
	


										if(  (e.getRowf() == e.getRowb() ) && (k == e.getRowf()) )
											for(m = 10; m < 10+e.getSize(); m++)
											{
												a2[k][m] = 1;
											}


					
	
									}

	


								for(k = 1; k<=10; k++)
									for(l = 1; l<=10; l++)
										if((a2[k][l] == 1) && (g2[k][l] ==1))
											g2[k][l] = 2;
									
								

							
								for(k = 1; k<=10; k++)
									for(l = 1; l<=10; l++)
									{
										if((a2[k][l] == 1) && (g2[k][l] ==2))
										{
											e.setHit();
											count2++;	
											if(e.getHit() == e.getSize())
												System.out.print("you sunk my : " + e.getName() + "\n");
											else
												System.out.print("\n\nPlayer 2 hit a ship\n");
									

											
											g2[k][l] = 3;
										}		
									}

							}	
	
					



						}
						//else
							//System.out.print("miss");
					}







			}
			else
				System.out.println("Guess already made");

		}

		if(player == 1)
			player = 2;
		else if(player == 2)
			player = 1;

	}

	
  }
}

class Ship
{
	public Ship(int p, String s, int z, int rf, char cf, int rb, char cb, int h)
 	{
		player = p;
		name   = s;		
 		size   = z; 		
		rowf   = rf; 
 		colf   = cf;
 		rowb   = rb; 
 		colb   = cb;
 		hit    = h;
 	}

	public String getName()
	{
		return name;
	}

	public int getSize()
	{
		return size;
	}

	public int getRowf()
	{
		return rowf;
	}

	public int getRowb()
	{
		return rowb;
	}


	public char getColf()
	{
		return colf;
	}


	public char getColb()
	{
		return colb;
	}


	public int getPlayer()
	{
		return player;
	}
	public int getHit()
	{
		return hit;
	}
	
	public void setHit()
	{
		hit = hit +1;
	}




			
	
	private String name;		
 	private int size; 		    //size of ship
	private int rowf; 
 	private char colf;		    //column front char
 	private int rowb; 
 	private char colb;		    //column back char
 	private int player;
	private int hit;
} 







Edited by 4mad3u5, 07 August 2014 - 02:47 PM.


Sponsor:

#2 dsm1891   Crossbones+   -  Reputation: 1540

Like
-1Likes
Like

Posted 07 August 2014 - 03:12 PM

I believe this post should be in the coding horror forum...

Oh the horror of such a long method.

 

Your code is horribly hard to read, maybe split it up into methods to make things easier for us? wacko.png



#3 4mad3u5   Members   -  Reputation: 116

Like
0Likes
Like

Posted 07 August 2014 - 03:36 PM

k



#4 rip-off   Moderators   -  Reputation: 8726

Like
7Likes
Like

Posted 07 August 2014 - 03:53 PM

I believe this post should be in the coding horror forum...

Oh the horror of such a long method.

 

Your code is horribly hard to read, maybe split it up into methods to make things easier for us? wacko.png

Well, this is For Beginners, so if you're not being constructive then please don't respond at all. Presumably, the OP wouldn't be asking the question if they found this easy to do.



#5 rip-off   Moderators   -  Reputation: 8726

Like
9Likes
Like

Posted 07 August 2014 - 04:21 PM

There are numerous issues with your current program that make it very difficult to read. The first is the variable names. Short names like "s1", "e" and "b1" are devoid of meaning. While you might know what they mean now, we don't and in a few weeks or months you won't remember either.

 

Instead, use descriptive names like playerOneFleet. You'll almost never regret using a longer word - remember a good IDE can offer you auto-completion so you won't even need to type it out fully!

 

The next issue is that your program contains lots of magic numbers. The integers in the "g" array seem to correspond with various states, but these are all implicit. Consider using named constants:

final int UNKNOWN = 0;
final int MISS = 1
final int HIT = 2;

// Later ...

if (boardPosition[y][x] == UNKNOWN) {
    if (containsShip(y, x)) {
        damageShip(y, x);
        boardPosition[y][x] = HIT;
    } else {
        boardPosition[y][x] = MISS;
    }
} else {
    System.out.println("You've already made that move!");
}

Better still would be to use an enum to represent this, but I'm not sure if you're familiar with them yet.

 

Another thing is modelling. You've modelled the Ship explicitly, but everything else is in a bunch of primitive arrays. Consider adding a class that represents the playing board itself, or perhaps two classes, one for the opponents "view" and another for the "true state" board. Try to move much of the logic into these classes.

 

Then, you should be able to cut the main() method's size in half by saying that a game consists of two player's boards - an array. You have an integer index for the active player. Each turn, you switch the active player between 0 and 1, and delegate to the appropriate object, maybe something like this:

public static void main(String args[]) {
    Board[] boards = { new Board(), new Board() };
    int activePlayer = 0;
    while (!isGameOver(boards)) {
        Board activeBoard = boards[activePlayer];
        Position position = new Position();
        while (!position.isValid()) {
            activeBoard.display();
            position = activeBoard.getMove();
        }
        activeBoard.makeMove(position);
        
        if (activePlayer == 0) {
            activePlayer = 1;
        } else {
            activePlayer = 0;
        }
    }
}


Edited by rip-off, 07 August 2014 - 04:26 PM.


#6 Glass_Knife   Moderators   -  Reputation: 4995

Like
5Likes
Like

Posted 07 August 2014 - 04:32 PM


The first is the variable names. Short names like "s1", "e" and "b1" are devoid of meaning.

 

Yes.  It took a while to figure out rowf = rowFront.  Naming things is really hard, and when you're just starting out, you may think "Well, I know what all this is, so I don't need descriptive names."  But when you come back to your code later, you won't remember all this stuff.

 

For example, to make it easier to understand, I would make a simple point class:


public class Point {

  private int x;
  private int y;

  public Point( int x, int y ) {
    this.x = x;
    this.y = y;
  }

  public int getX() { return x; }
  public int getY() { return y; }

}

Then, instead of rowf, colf, rowb, colb, I would do this:


  Point bow = new Point( 0, 1 );
  Point stern = new Point( 0, 3 );

And as rip-off pointed out, when you see the same code repeated over and over again, there is probably a better way to do it.

 

My first program, which shuffled a deck of cards in C++, looked just like this.  I had so many nested for loops I'm surprised it didn't run out of memory.


Edited by Glass_Knife, 07 August 2014 - 04:33 PM.

I think, therefore I am. I think? - "George Carlin"
Indie Game Programming

#7 4mad3u5   Members   -  Reputation: 116

Like
0Likes
Like

Posted 07 August 2014 - 05:02 PM

I put everything in methods


import java.util.*;

public class a4 
{
  public static void main( String args[] ) 
  {
	Ship[] s1 = new Ship[5];
	Ship[] s2 = new Ship[5];

	Scanner in = new Scanner(System.in);
	

	s1[0] = new Ship(1,"Aircraft carrier",5,1,'a',1,'e',0);  // player, ship, size, row front, column front, row back, column back, hit
	s1[1] = new Ship(1,"Battleship",      4,2,'b',5,'b',0);
 	s1[2] = new Ship(1,"Submarine",       3,2,'c',4,'c',0);
	s1[3] = new Ship(1,"Destroyer",       3,2,'d',4,'d',0);
	s1[4] = new Ship(1,"Patrol boat",     2,2,'e',3,'e',0);

	s2[0] = new Ship(1,"Aircraft carrier",5,1,'a',1,'e',0);  // player, ship, size, row front, column front, row back, column back, hit
	s2[1] = new Ship(1,"Battleship",      4,2,'b',5,'b',0);
 	s2[2] = new Ship(1,"Submarine",       3,2,'c',4,'c',0);
	s2[3] = new Ship(1,"Destroyer",       3,2,'d',4,'d',0);
	s2[4] = new Ship(1,"Patrol boat",     2,2,'e',3,'e',0);


	int[][] b1  = new int[11][11];
	int[][] g1  = new int[11][11];
	int[][] a1  = new int[11][11];
	int[][] f1  = new int[11][11];

	int[][] b2  = new int[11][11];
	int[][] g2  = new int[11][11];
	int[][] f2  = new int[11][11];

	int i = 0;
	int j = 0;
	int k = 0;
	int l = 0;
	int m = 0;
	int b = 0;
	int player = 1;	
	char c;
	int inrow;
	int count1 = 0;
	int count2 = 0;



	for(Ship e: s1)
		check(e, b1);

	for(Ship e: s2)	
		check(e, b2);



	while((count1 < 17) || (count2 < 17))
	{
		System.out.println("\n\n\nPlayer: " + player + "'s turn:\n"); 
		if(player == 1)
		{
			b= 0;


			for(i = 1; i <= 10; i++)
			{
				for(j = 1; j <= 10; j++)
				{
					if(g1[i][j] == 3)
						System.out.print("* ");
					if(g1[i][j] == 1)
						System.out.print("X ");
					if(g1[i][j] == 0)
						System.out.print(g1[i][j] + " "); 
				}

				System.out.print("\n");
			}

			System.out.print("\nEnter a charactor from A - k for column and and number from 1 - 10 \nrespectively for the quardents of your shot: ");

			c = in.next().charAt(0);
			inrow  = in.nextInt();
		


			for(i = 1; i <= 10; i++)
				for(j = 1; j <= 10; j++)
					f1[i][j] = 5;




			check1(f1,c,inrow);


			for(i = 1; i <= 10; i++)
				for(j = 1; j <= 10; j++)
					if(  (f1[i][j] == 1) && (g1[i][j] == 3))
						b = 1;


	



			if( b == 0)
			{

				check1(g1,c,inrow);


				for(i = 1; i <= 10; i++)
					for(j = 1; j <= 10; j++)
					{
						if( b1[i][j] == 1 && g1[i][j] == 1)
						{
							for(Ship e : s1)
							{			
		
								for(k = 0; k <= 10; k++) 
								{
									for(l = 0; l <= 10; l++)
									{
										a1[k][l] = 0;
									}
								}


								check(e,a1);								
												 
							
								for(k = 1; k<=10; k++)
									for(l = 1; l<=10; l++)
									{
										if((a1[k][l] == 1) && (g1[k][l] ==1))
										{
											e.setHit();
											count1++;	
											if(e.getHit() == e.getSize())
												System.out.print("you sunk my : " + e.getName() + "\n");
											else
												System.out.print("\n\nPlayer 1 hit a ship\n");
									
											g1[k][l] = 3;
										}		
									}	
							}	

						}
						//else
							//System.out.print("miss");
					}
	

			}
			else
				System.out.println("Guess already made");

		}
	


		if(player == 2)
		{
			b= 0;

			
			System.out.print("\n");

			for(i = 1; i <= 10; i++)
			{
				for(j = 1; j <= 10; j++)
				{
					if(g2[i][j] == 3)
						System.out.print("* ");
					if(g2[i][j] == 1)
						System.out.print("X ");
					if(g2[i][j] == 0)
						System.out.print(g2[i][j] + " "); 
				}

				System.out.print("\n");
			}

			System.out.print("\nEnter a charactor from A - k for column and and number from 1 - 10 \nrespectively for the quardents of your shot: ");
			c = in.next().charAt(0);
			inrow  = in.nextInt();



			for(i = 1; i <= 10; i++)
				for(j = 1; j <= 10; j++)
					f2[i][j] = 5;


			check1(f2,c,inrow);



			for(i = 1; i <= 10; i++)
				for(j = 1; j <= 10; j++)
					if(  (f2[i][j] == 1) && (g2[i][j] == 3))
						b = 1;


	
				

			System.out.print("\n");





			if( b == 0)
			{
				check1(g2,c,inrow);

				for(i = 1; i <= 10; i++)
					for(j = 1; j <= 10; j++)
					{
						if( b2[i][j] == 1 && g2[i][j] == 1)
						{
							for(Ship e : s2)
							{	


						
		
								for(k = 0; k <= 10; k++) 
								{
									for(l = 0; l <= 10; l++)
									{
										a1[k][l] = 0;
									}
								}


								check(e,a1);

									
								
							
								for(k = 1; k<=10; k++)
									for(l = 1; l<=10; l++)
									{
										if((a1[k][l] == 1) && (g2[k][l] == 1))
										{
											e.setHit();
											count2++;	
											if(e.getHit() == e.getSize())
												System.out.print("you sunk my : " + e.getName() + "\n");
											else
												System.out.print("\n\nPlayer 2 hit a ship\n");
									

											
											g2[k][l] = 3;
										}		
									}

							}	
	
					



						}
						//else
							//System.out.print("miss");
					}







			}
			else
				System.out.println("Guess already made");

		}

		if(player == 1)
			player = 2;
		else if(player == 2)
			player = 1;

	}	
  }



	public static void check1(int[][] a, char ch, int ir)
	{

			if(ch == 'A' || ch == 'a')
				a[ir][1] = 1;
			if(ch == 'B' || ch == 'b')
				a[ir][2] = 1;
			if(ch == 'C' || ch == 'c')
				a[ir][3] = 1;
			if(ch == 'D' || ch == 'd')
				a[ir][4] = 1;
			if(ch == 'E' || ch == 'e')
				a[ir][5] = 1;
			if(ch == 'F' || ch == 'f')
				a[ir][6] = 1;
			if(ch == 'G' || ch == 'g')
				a[ir][7] = 1;
			if(ch == 'H' || ch == 'h')
				a[ir][8] = 1;
			if(ch == 'I' || ch == 'i')
				a[ir][9] = 1;
			if(ch == 'J' || ch == 'j')
				a[ir][10] = 1;

	}




	public static void check(Ship x, int[][] a)
	{

		int i;
		
		if((x.getColf() == 'a' || x.getColf() == 'A'))
		{
			if(x.getColf() == x.getColb())
				for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
					a[i][1] = 1;
				
			if(x.getRowf() == x.getRowb())
				for(i = 1; i < (1+x.getSize()); i++ )
					a[x.getRowf()][i] = 1;
				
		}


		
		if((x.getColf() == 'b' || x.getColf() == 'B'))
		{
			if(x.getColf() == x.getColb())
				for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
					a[i][2] = 1;

			if(x.getRowf() == x.getRowb())
				for(i = 2; i < (2+x.getSize()); i++ )
					a[x.getRowf()][i] = 1;
				
		}



		if((x.getColf() == 'c' || x.getColf() == 'C'))
		{
			if(x.getColf() == x.getColb())
				for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
					a[i][3] = 1;
				
			if(x.getRowf() == x.getRowb())
				for(i = 3; i < (3+x.getSize()); i++ )
					a[x.getRowf()][i] = 1;
				
		}

		if((x.getColf() == 'd' || x.getColf() == 'D'))
		{
			if(x.getColf() == x.getColb())
				for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
					a[i][4] = 1;
				
			if(x.getRowf() == x.getRowb())
				for(i = 4; i < (4+x.getSize()); i++ )
					a[x.getRowf()][i] = 1;
				
		}  

		if((x.getColf() == 'e' || x.getColf() == 'E'))
		{
			if(x.getColf() == x.getColb())
				for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
					a[i][5] = 1;
				
			if(x.getRowf() == x.getRowb())
				for(i = 5; i < (5+x.getSize()); i++ )
					a[x.getRowf()][i] = 1;
				
		}   

		if((x.getColf() == 'f' || x.getColf() == 'F'))
		{
			if(x.getColf() == x.getColb())
				for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
					a[i][6] = 1;
				
			if(x.getRowf() == x.getRowb())
				for(i = 6; i < (6+x.getSize()); i++ )
					a[x.getRowf()][i] = 1;
				
		}   

		if((x.getColf() == 'g' || x.getColf() == 'G'))
		{
			if(x.getColf() == x.getColb())
				for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
					a[i][7] = 1;
				
			if(x.getRowf() == x.getRowb())
				for(i = 7; i < (7+x.getSize()); i++ )
					a[x.getRowf()][i] = 1;
				
		}  

		if((x.getColf() == 'h' || x.getColf() == 'H'))
		{
			if(x.getColf() == x.getColb())
				for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
					a[i][8] = 1;
				
			if(x.getRowf() == x.getRowb())
				for(i = 8; i < (8+x.getSize()); i++ )
					a[x.getRowf()][i] = 1;
				
		}   

		if((x.getColf() == 'i' || x.getColf() == 'I'))
		{
			if(x.getColf() == x.getColb())
				for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
					a[i][9] = 1;
				
			if(x.getRowf() == x.getRowb())
				for(i = 9; i < (9+x.getSize()); i++ )
					a[x.getRowf()][i] = 1;
				
		}   

		if((x.getColf() == 'j' || x.getColf() == 'J'))
		{
			if(x.getColf() == x.getColb())
				for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
					a[i][10] = 1;
				
			if(x.getRowf() == x.getRowb())
				for(i = 10; i < (10+x.getSize()); i++ )
					a[x.getRowf()][i] = 1;
			
		}       

	}



}

class Ship
{
	public Ship(int p, String s, int z, int rf, char cf, int rb, char cb, int h)
 	{
		player = p;
		name   = s;		
 		size   = z; 		
		rowf   = rf; 
 		colf   = cf;
 		rowb   = rb; 
 		colb   = cb;
 		hit    = h;
 	}

	public String getName()
	{
		return name;
	}

	public int getSize()
	{
		return size;
	}

	public int getRowf()
	{
		return rowf;
	}

	public int getRowb()
	{
		return rowb;
	}


	public char getColf()
	{
		return colf;
	}


	public char getColb()
	{
		return colb;
	}


	public int getPlayer()
	{
		return player;
	}
	public int getHit()
	{
		return hit;
	}
	
	public void setHit()
	{
		hit = hit +1;
	}


			
	
	private String name;		
 	private int size; 		    //size of ship
	private int rowf; 
 	private char colf;		    //column front char
 	private int rowb; 
 	private char colb;		    //column back char
 	private int player;
	private int hit;
} 







Edited by 4mad3u5, 07 August 2014 - 05:04 PM.


#8 4mad3u5   Members   -  Reputation: 116

Like
0Likes
Like

Posted 07 August 2014 - 05:10 PM

Yeah I know to use descriptive variable names I just didn't think I was going to be showing this to anyone, I will change. 



#9 4mad3u5   Members   -  Reputation: 116

Like
-2Likes
Like

Posted 07 August 2014 - 05:20 PM

Well Glass_Knife it shouldn't have been that hard to know what rowf meant since I had a comment right in front of it explaining what it meant. 



#10 4mad3u5   Members   -  Reputation: 116

Like
0Likes
Like

Posted 07 August 2014 - 05:43 PM

Here it is with meaningful variable names and methods



import java.util.*;

public class a4 
{
  public static void main( String args[] ) 
  {
	Ship[] playerOneShips = new Ship[5];
	Ship[] playerTwoShips = new Ship[5];

	
	

	playerOneShips[0] = new Ship(1,"Aircraft carrier",5,1,'a',1,'e',0);  // player, ship, size, row front, column front, row back, column back, hit
	playerOneShips[1] = new Ship(1,"Battleship",      4,2,'b',5,'b',0);
 	playerOneShips[2] = new Ship(1,"Submarine",       3,2,'c',4,'c',0);
	playerOneShips[3] = new Ship(1,"Destroyer",       3,2,'d',4,'d',0);
	playerOneShips[4] = new Ship(1,"Patrol boat",     2,2,'e',3,'e',0);

	playerTwoShips[0] = new Ship(1,"Aircraft carrier",5,1,'a',1,'e',0);  // player, ship, size, row front, column front, row back, column back, hit
	playerTwoShips[1] = new Ship(1,"Battleship",      4,2,'b',5,'b',0);
 	playerTwoShips[2] = new Ship(1,"Submarine",       3,2,'c',4,'c',0);
	playerTwoShips[3] = new Ship(1,"Destroyer",       3,2,'d',4,'d',0);
	playerTwoShips[4] = new Ship(1,"Patrol boat",     2,2,'e',3,'e',0);


	int[][] playerOneBoard  = new int[11][11];   //All the ships in an array
	int[][] playerOneGuess  = new int[11][11];
	
	

	int[][] playerTwoBoard  = new int[11][11];
	int[][] playerTwoGuess  = new int[11][11];
	int[][] count  = new int[1][2];

	
	
	int player = 1;	
	int count1 = 0;
	int count2 = 0;


	for(Ship e: playerOneShips)
		arrayAssignShip(e, playerOneBoard);

	for(Ship e: playerTwoShips)	
		arrayAssignShip(e, playerTwoBoard);



	while( (count1 < 17) && (count2 < 17) )
	{

		System.out.println("count[0][0] = " + count[0][0]);
		System.out.println("count[0][1] = " + count[0][1]);

		if(player == 1)
			player = play(playerOneBoard, playerOneGuess, playerOneShips,player,count);

		if((player == 2) && (count[0][0] < 17))
			player = play(playerTwoBoard, playerTwoGuess, playerTwoShips,player,count);

		count1 = count[0][0];
		count2 = count[0][1];

		System.out.println("count1 = " + count1);
		System.out.println("count2 = " + count2);

	}	
  }


  public static int play(int[][] playerBoard, int[][] playerGuess, Ship[] playerShips, int player, int[][] count)
  {
	Scanner in = new Scanner(System.in);
	int[][] shipBoard  = new int[11][11];	     //One Ship at a time in an array to check if ship was hit
	int[][] currentGuess  = new int[11][11];     //Current Guess in an array

	int i = 0;
	int j = 0;
	int k = 0;
	int l = 0;
	int m = 0;
	int b = 0;
	char c;
	int inrow;
	

		
	System.out.println("\n\n\nPlayer: " + player + "'s turn:\n");


	for(i = 1; i <= 10; i++)
	{
		for(j = 1; j <= 10; j++)
		{
			if(playerGuess[i][j] == 3)
				System.out.print("* ");
			if(playerGuess[i][j] == 1)
				System.out.print("X ");
			if(playerGuess[i][j] == 0)
				System.out.print(playerGuess[i][j] + " "); 
		}

		System.out.print("\n");
	}

	System.out.print("\nEnter a charactor from A - k for column and and number from 1 - 10 \nrespectively for the quardents of your shot: ");
	c = in.next().charAt(0);
	inrow  = in.nextInt();



	for(i = 1; i <= 10; i++)
		for(j = 1; j <= 10; j++)
			currentGuess[i][j] = 5;


	arrayAssignInput(currentGuess,c,inrow);



	for(i = 1; i <= 10; i++)
		for(j = 1; j <= 10; j++)
			if(  (currentGuess[i][j] == 1) && ((playerGuess[i][j] == 3) || (playerGuess[i][j] == 1)))
				b = 1;


	if( b == 0)
	{
		arrayAssignInput(playerGuess,c,inrow);

		for(i = 1; i <= 10; i++)
			for(j = 1; j <= 10; j++)
			{
				if( playerBoard[i][j] == 1 && playerGuess[i][j] == 1)
				{
					for(Ship x : playerShips)
					{	
		
						for(k = 0; k <= 10; k++) 
						{
							for(l = 0; l <= 10; l++)
							{
								shipBoard[k][l] = 0;
							}
						}


						arrayAssignShip(x,shipBoard);
		
				
						for(k = 1; k<=10; k++)
							for(l = 1; l<=10; l++)
							{
								if((shipBoard[k][l] == 1) && (playerGuess[k][l] == 1))
								{
									x.setHit();

									if(player == 1)
										count[0][0]++;
									if(player == 2)
										count[0][1]++;
	
									if(x.getHit() == x.getSize())
										System.out.print("you sunk my : " + x.getName() + "\n");
									else
										System.out.print("\n\nPlayer hit a ship\n");
											
									playerGuess[k][l] = 3;
								}		
							}
					}	
				}
						//else
							//System.out.print("miss");
			}
			
		
		if(player == 1)
			player = 2;
		else if(player == 2)
			player = 1;
			
	}
	else
		System.out.println("\n\nGuess already made");

	return player;
  }





  public static void arrayAssignInput(int[][] a, char ch, int ir)
  {

	if(ch == 'A' || ch == 'a')
		a[ir][1] = 1;
	if(ch == 'B' || ch == 'b')
		a[ir][2] = 1;
	if(ch == 'C' || ch == 'c')
		a[ir][3] = 1;
	if(ch == 'D' || ch == 'd')
		a[ir][4] = 1;
	if(ch == 'E' || ch == 'e')
		a[ir][5] = 1;
	if(ch == 'F' || ch == 'f')
		a[ir][6] = 1;
	if(ch == 'G' || ch == 'g')
		a[ir][7] = 1;
	if(ch == 'H' || ch == 'h')
		a[ir][8] = 1;
	if(ch == 'I' || ch == 'i')
		a[ir][9] = 1;
	if(ch == 'J' || ch == 'j')
		a[ir][10] = 1;
  }




  public static void arrayAssignShip(Ship x, int[][] a)
  {

	int i;
		
	if((x.getColf() == 'a' || x.getColf() == 'A'))
	{
		if(x.getColf() == x.getColb())
			for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
				a[i][1] = 1;
			
		if(x.getRowf() == x.getRowb())
			for(i = 1; i < (1+x.getSize()); i++ )
				a[x.getRowf()][i] = 1;
			
	}
		
	if((x.getColf() == 'b' || x.getColf() == 'B'))
	{
		if(x.getColf() == x.getColb())
			for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
				a[i][2] = 1;

		if(x.getRowf() == x.getRowb())
			for(i = 2; i < (2+x.getSize()); i++ )
				a[x.getRowf()][i] = 1;
				
	}


	if((x.getColf() == 'c' || x.getColf() == 'C'))
	{
		if(x.getColf() == x.getColb())
			for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
				a[i][3] = 1;
				
		if(x.getRowf() == x.getRowb())
			for(i = 3; i < (3+x.getSize()); i++ )
				a[x.getRowf()][i] = 1;
				
	}

	if((x.getColf() == 'd' || x.getColf() == 'D'))
	{
		if(x.getColf() == x.getColb())
			for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
				a[i][4] = 1;
				
		if(x.getRowf() == x.getRowb())
			for(i = 4; i < (4+x.getSize()); i++ )
				a[x.getRowf()][i] = 1;
				
	}  

	if((x.getColf() == 'e' || x.getColf() == 'E'))
	{
		if(x.getColf() == x.getColb())
			for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
				a[i][5] = 1;
			
		if(x.getRowf() == x.getRowb())
			for(i = 5; i < (5+x.getSize()); i++ )
				a[x.getRowf()][i] = 1;
				
	}   

	if((x.getColf() == 'f' || x.getColf() == 'F'))
	{
		if(x.getColf() == x.getColb())
			for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
				a[i][6] = 1;
				
		if(x.getRowf() == x.getRowb())
			for(i = 6; i < (6+x.getSize()); i++ )
				a[x.getRowf()][i] = 1;
				
	}   

	if((x.getColf() == 'g' || x.getColf() == 'G'))
	{
		if(x.getColf() == x.getColb())
			for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
				a[i][7] = 1;
				
		if(x.getRowf() == x.getRowb())
			for(i = 7; i < (7+x.getSize()); i++ )
				a[x.getRowf()][i] = 1;
				
	}  

	if((x.getColf() == 'h' || x.getColf() == 'H'))
	{
		if(x.getColf() == x.getColb())
			for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
					a[i][8] = 1;
			
		if(x.getRowf() == x.getRowb())
			for(i = 8; i < (8+x.getSize()); i++ )
				a[x.getRowf()][i] = 1;
				
	}   

	if((x.getColf() == 'i' || x.getColf() == 'I'))
	{
		if(x.getColf() == x.getColb())
			for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
				a[i][9] = 1;
				
		if(x.getRowf() == x.getRowb())
			for(i = 9; i < (9+x.getSize()); i++ )
				a[x.getRowf()][i] = 1;
				
	}   

	if((x.getColf() == 'j' || x.getColf() == 'J'))
	{
		if(x.getColf() == x.getColb())
			for(i = x.getRowf(); i < (x.getRowf()+x.getSize()); i++ )
				a[i][10] = 1;
				
		if(x.getRowf() == x.getRowb())
			for(i = 10; i < (10+x.getSize()); i++ )
				a[x.getRowf()][i] = 1;
			
	}       

  }



}

class Ship
{
	public Ship(int p, String s, int z, int rf, char cf, int rb, char cb, int h)
 	{
		player = p;
		name   = s;		
 		size   = z; 		
		rowFront   = rf; 
 		colFront   = cf;
 		rowBack   = rb; 
 		colBack   = cb;
 		hit    = h;
 	}

	public String getName()
	{
		return name;
	}

	public int getSize()
	{
		return size;
	}

	public int getRowf()
	{
		return rowFront;
	}

	public int getRowb()
	{
		return rowBack;
	}


	public char getColf()
	{
		return colFront;
	}


	public char getColb()
	{
		return colBack;
	}


	public int getPlayer()
	{
		return player;
	}
	public int getHit()
	{
		return hit;
	}
	
	public void setHit()
	{
		hit = hit +1;
	}


			
	
	private String name;		
 	private int size; 		    //size of ship
	private int rowFront; 
 	private char colFront;		    //column front char
 	private int rowBack; 
 	private char colBack;		    //column back char
 	private int player;
	private int hit;
} 







Edited by 4mad3u5, 08 August 2014 - 11:01 AM.


#11 LennyLen   Crossbones+   -  Reputation: 4021

Like
0Likes
Like

Posted 07 August 2014 - 10:56 PM

I'm not familiar with Java, so I just googled this and haven't tested it, but you can make some optimizations like this:

 

Instead of

public static void arrayAssignInput(int[][] a, char ch, int ir)
	{

			if(ch == 'A' || ch == 'a')
				a[ir][1] = 1;
			if(ch == 'B' || ch == 'b')
				a[ir][2] = 1;
			if(ch == 'C' || ch == 'c')
				a[ir][3] = 1;
			if(ch == 'D' || ch == 'd')
				a[ir][4] = 1;
			if(ch == 'E' || ch == 'e')
				a[ir][5] = 1;
			if(ch == 'F' || ch == 'f')
				a[ir][6] = 1;
			if(ch == 'G' || ch == 'g')
				a[ir][7] = 1;
			if(ch == 'H' || ch == 'h')
				a[ir][8] = 1;
			if(ch == 'I' || ch == 'i')
				a[ir][9] = 1;
			if(ch == 'J' || ch == 'j')
				a[ir][10] = 1;

	}

use

public static void arrayAssignInput(int[][] a, char ch, int ir)
{
    char upper = Character.toUpperCase(ch)
    int val = (int)upper - (int)'A' + 1;
    a[ir][val] = 1;
}


#12 Buster2000   Members   -  Reputation: 1775

Like
4Likes
Like

Posted 08 August 2014 - 01:43 AM


Yeah I know to use descriptive variable names I just didn't think I was going to be showing this to anyone, I will change.

 

The descriptive names aren't so that it looks pretty when you show it to other people.  They are there so that in a year or twos time when you have chopped and changed and refactored your code and added or removed new features you can tell what the variables do.  This may only be a small project but, it is good to get into the practice now.

 


Well Glass_Knife it shouldn't have been that hard to know what rowf meant since I had a comment right in front of it explaining what it meant.

 

We shouldn't have to scroll to a variable declaration to be able to know what it does.  In fact you should never need to comment a variable declaration.  If you do then the name you have chosen is not good enough.

 

 

 

All that being said the obvious things to do would be use constants to get rid of the magic number , Split it up into methods.  Use descriptive names for your variables and methods (check and check1 are meaningless).  Also consider creating a seperate Board class.
After all thats been said ignore any comments about it being a coding horror.  I have seen much worse code from so called proffesional programmers.  I haven't run it but, I assume that it works and it behaves how you expect it to behave. 



#13 TheChubu   Crossbones+   -  Reputation: 4756

Like
3Likes
Like

Posted 08 August 2014 - 01:55 AM


I put everything in methods
Nono. You put everything in a method. We say, put separate things in methods. Notice the difference.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

 

My journals: dustArtemis ECS framework and Making a Terrain Generator


#14 4mad3u5   Members   -  Reputation: 116

Like
-2Likes
Like

Posted 08 August 2014 - 08:08 AM

I don't want to argue semantics with people, I just want to know how to optimize my code. 



#15 Glass_Knife   Moderators   -  Reputation: 4995

Like
2Likes
Like

Posted 08 August 2014 - 08:37 AM

I don't want to argue semantics with people, I just want to know how to optimize my code. 

 

1.  Understand the more you learn about programming, the harder it gets.  Frustration is good.  It means you are learning.  If you expect to master programming this month you will disappointed. 

 

2.  You are not trying to optimize your code, but are trying to refactor the code.  The two are not mutually exclusive, but you are not replacing you algorithms to improve the speed or reduce the memory usage, you just want to make the code easier to read without changing the behavior.  That's refactoring.

 

Watch this:

 


I think, therefore I am. I think? - "George Carlin"
Indie Game Programming

#16 NotYourAverageUser   Members   -  Reputation: 500

Like
1Likes
Like

Posted 08 August 2014 - 08:58 AM

I don't want to argue semantics with people, I just want to know how to optimize my code. 

 

He was not arguing semantics, he was informing you that you didn't really do what was suggested to you.

 

Doing what has been suggested, breaking down specific tasks into separate methods, you should be able to end up with a main method that looks similar to rip-offs main.  This will help with readability and maintainability and will give you specific, contained areas of code to work with to optimize.  



#17 HyperV   Members   -  Reputation: 872

Like
0Likes
Like

Posted 08 August 2014 - 03:29 PM

Hi 

 

 

Create classes,

Call only the processes you need at a function not all.

But mostly rip-off gave you very important anwsers.

 

 

HyperV



#18 Spyderzone   Members   -  Reputation: 182

Like
0Likes
Like

Posted 08 August 2014 - 05:50 PM

Yeah I know to use descriptive variable names I just didn't think I was going to be showing this to anyone, I will change. 

I would still use descriptive names and make it a habit.  In 2-3 years when you revisit this code, (even if you think you never will, trust me you will) you will be able to quickly figure out what you were doing because you won't have to guess what variable names were supposed to represent.



#19 rip-off   Moderators   -  Reputation: 8726

Like
5Likes
Like

Posted 09 August 2014 - 01:37 PM

Having studied your code a bit more, there are a few more points I would make:

 

The method names like arrayAssignShip and arrayAssignInput are very mechanical, they describe what they do rather than the intent behind them. The first might be called "placeShip", the other is a little more tricky (I'll talk about this later), but in it's current state perhaps something like "mapInputToBoard". Now, play is a far better name, but it is still a bit vague. A better name might be something like "takeTurn" or "makeMove".

 

And while you've improved some of the names, the vast majority of them are unchanged. Names like the following are still very poor:

for(Ship e: playerOneShips)
    arrayAssignShip(e, playerOneBoard);
 
// ...
 
int i = 0;
int j = 0;
int k = 0;
int l = 0;
int m = 0;
int b = 0;
char c;
int inrow;
 
// ...
 

for(Ship x : playerShips)
{
    // ...
}

 

The methods you split up are still quite large. This means that they are still difficult to understand. The shortest one, arrayAssignInput, is about as long as I ideally let a method get. This way, you can see all of a method without scrolling. Shorter methods again tend to be more "obvious", and are easier to give good names as they are clearly focussed on one task.

 

You should try to separate display from your internal data structures. For example, all your arrays have 11 elements, but you're using elements 1 through 10. This is convenient as the indices you are using and the inputs you accept from the user. However, this is highly unconventional. While it isn't particularly problematic for the numeric input, it starts getting very inconvenient indeed for the character input. Instead, focus on quickly validating the user input and converting it to an internal format. In this case, the number the user inputs should be validated as between 1 and 10, and then you subtract one and use as your row index. Likewise, your character input should be validated for valid range and converted to an index, as LennyLen indicated how to do.

 

This is most obvious in the difficulty you appear to have handling the columns of the board state and the ship - by handling this as character based indexes internally, it certainly complicates a lot of things, even though it would be technically possible to achieve.

 

By elevating the concept of a "point", "location" or "co-ordinate" to something that can be described in the vocabulary of your program, 

 

Related to how you represent indices is how you represent ships and guesses. This is structuring your data in a way that is convenient for the program. There are often multiple ways to do so.

 

For instance, instead of an array of 1s and 0s (which probably should have been booleans), you can represent the board as a grid of Ship references. So if you have a patrol boat at the top left horizontally, those two occupied grid entries could point back to this Ship. This allows you to quickly get from a grid location to the Ship that cross it, so you can call methods to mark the ship as being hit.

 

In another representation, you could potentially dispense with the Ship objects themselves - all you need is something like a ShipType enumeration, with an entry for each Ship type, and an be used to get the display name and length of the ship. Your grid could consist of ShipType values of the appropriate length. Once you know a ship has been hit, you can attempt to access the adjacent horizontal or vertical entries in the grid to determine if it has been sunk.

 

Yet another way is to dispense with the grid of ship locations. Instead, your Ship class can each contain an array of booleans the length of that ship, each element of which represents whether that location has been hit. So to resolve if a hit has occurred, just iterate through the Ships, determine if the grid location lies between the locations spanned by the ship, and if so calculate the index into that array and mark it as hit.

 

Currently, you're storing redundant information - you store what you call a "count", which appears to be the number of hits that player has scored. You can also calculate this on demand by iterating though the Ships and summing the "hits taken" of each one. This isn't always a bad idea, in fact sometimes it can make sense to do so - when it might take a long time to iterate through all the elements in question. Here, it isn't going to take any time at all. However, it can cause difficulty as the values can get out of sync, though this isn't likely in your example, despite the fact that you've actually made this more complex still as you have the count arrays, and also more count variables.

 

I mentioned about your guess representation and algorithm. It is very complex. Part of the problem is that you're mapping grid co-ordinates to a separate grid, and then looping simultaneously between this array and your other arrays. Instead, try to structure the algorithm to avoid the temporary array and instead access the array of interest directly.

 

Some more general notes that are more purely stylistic:

 

I'd recommend scoping your variables much more tightly. For example, loop counters are best declared inside the loop statement, like so:

for(int i = 1; i <= 10; i++)
{
    for(int j = 1; j <= 10; j++)
    {
        if(playerGuess[i][j] == 3)
            System.out.print("* ");
        if(playerGuess[i][j] == 1)
            System.out.print("X ");
        if(playerGuess[i][j] == 0)
            System.out.print(playerGuess[i][j] + " "); 
    }
 
    System.out.print("\n");
}

 

Another example is here:

System.out.print("\nEnter a charactor from A - k for column and and number from 1 - 10 \nrespectively for the quardents of your shot: ");
c = in.next().charAt(0);
inrow  = in.nextInt();

These variables should be declared at this point, like so:

System.out.print("\nEnter a charactor from A - k for column and and number from 1 - 10 \nrespectively for the quardents of your shot: ");
char c = in.next().charAt(0);
int inrow  = in.nextInt();

 

Encapsulation is capturing logic inside a class and not having it leak outside. Ideally, all variables in all classes will be "private". Not only that, but the details of this state, even if private, should not be exposed lightly. Here is an example:

ship.setHit();
 
// ...
 
if(ship.getHit() == ship.getSize())
    System.out.print("you sunk my : " + ship.getName() + "\n");
else
    System.out.print("\n\nPlayer hit a ship\n");

Here, we can hit the "hit" value by having more meaningful method names that are not necessarily related to the variables that are used by them:

ship.markDamaged();
 
// ...
 
if(ship.isSunk())
    System.out.print("you sunk my : " + ship.getName() + "\n");
else
    System.out.print("\n\nPlayer hit a ship\n");
 
// ...
 
class Ship {
     
     private final int length;
     
     private int hitsTaken;
 
     // ...
 
     public void markDamaged() {
         assert hitsTaken < length;
         hitsTaken += 1;
     }
     
     public boolean isSunk() {
         return hitsTaken >= length;
     }
}

 

I've already mentioned about the magic numbers, but it bears repeating. It is very difficult to understand code where you see strange constants like 3 or 5 that have no meaning in an of themselves. You have to reason about the consequences before you can discover the meaning, and it can be easy to make an incorrect guess if you make a mistake or are impatient. Far better to name constants like 17 as "HitsRequiredToWin".

 

If you're only concerned about 0 or 1, using a boolean is clearer. If you're not dealing with numeric data, then consider using an enumeration.

 

I'd recommend moving your Ship class, and any other classes you make, to a separate file.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS