// Programmer: Paul Adcock //
// Project: GUI Project //
// Last Modification Date: 6/2/10 //
/* The project makes an array of up to 100 buttons. My
if statements will keep asking user for a value between 2 and 10 till they do it. Then I'm
going to put the battleship in the array and then going to have actionEvent deal with if it's
not a hit and has a text of 0, I set them default to 0, then it changes the text of that button to an M.
If they shoot there again one or more times, it changes it to an A. If they actually hit the battleship, it changes the text to
an H, shows the number of shots, and then exits. If they surrender, it asks them if they want to, and if they do, it shows the number of shots
and then exits. If they quit, it asks them if they want to, and if they do, it justs says a goodbye message and exits. */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JDialog;
import javax.swing.JPanel;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import java.util.*;
import java.io.*;
import java.awt.Component;
import javax.swing.AbstractButton;
public class BattleshipGUI extends JFrame
implements ActionListener
{ // beginning of class
// label
private JLabel shotsLabel, arraySize;
// area where text is displayed and user would normally enter text but I have made it so the user can't alter the shot count.
private JTextField shotsTF, arraySizeTF;
JFrame frame;
JButton [][] arrayOfButtons;
char [][] charArray;
int x, y, i, j;
// buttons
private JButton surrenderB, quitB;
private static final int WIDTH = 500;
private static final int HEIGHT = 500;
public BattleshipGUI()
{ // beginning of constructor
setTitle("Battleship Game");
Container pane = getContentPane();
// makes Label for shots
shotsLabel = new JLabel("Shots: ",
SwingConstants.RIGHT);
arraySize= new JLabel("Array Size ",
SwingConstants.RIGHT);
// makes Text Field for shots and makes the text field non-editable
shotsTF = new JTextField(7);
shotsTF.setEditable(false);
arraySizeTF = new JTextField(2);
arraySizeTF.setEditable(false);
// makes the buttons and sets their value initially to 0 and makes the method actionPerformed
// a method of the class BattleshipGUI. I don't need individual handlers.
surrenderB = new JButton("Surrender");
surrenderB.addActionListener(this);
quitB = new JButton("Quit");
quitB.addActionListener(this);
// n is the size of the grid
int n = 0;
String gridSizeStr, outputStr;
boolean isInRange = false;
// while loop and boolean allow user to keep entering int values till n is between 2 and 10. Also, it needs to have
// the array of buttons in a square shape, and also so I can place the battleship in the array and later use actionListeners to
// change the text to either a M, an A, or a H. Hence why all buttons in the array have the same label to begin with.
shotsTF.setText("0");
boolean isValid = false;
while (isValid == false)
{ // beginning of while
try
{ // beginning of try
gridSizeStr = JOptionPane.showInputDialog("Enter the size of the grid:");
n = Integer.parseInt(gridSizeStr);
if (n < 2)
throw new MyTooSmallException();
if (n > 10)
throw new MyTooBigException();
isValid = true;
} // end of try
catch ( MyTooSmallException mtse)
{ // beginning of catch
JOptionPane.showMessageDialog(null, "Enter a value that is not less than"
+ " 2 and is no greater than 10. " +"\n " + mtse.toString() );
} // end of catch
catch ( MyTooBigException mtbe)
{ // beginning of catch
JOptionPane.showMessageDialog(null, "Enter a value that is not less than"
+ "2 and is no greater than 10. " +"\n " + mtbe.toString() );
} // end of catch
catch (NumberFormatException nfeRef)
{ // beginning of catch
JOptionPane.showMessageDialog(null,
"Enter an integer. Exception "
+ nfeRef.toString(),
"NumberFormatException",
JOptionPane.ERROR_MESSAGE);
} // end of catch
} // end of while
if (n >=2 && n <= 10)
{ // beginning of if
charArray = new char[n][n];
for ( int x = 0; x < charArray.length; x++)
{
for ( int y = 0; y < charArray[x].length; y++)
charArray[x][y] = '0';
}
arrayOfButtons = new JButton[n][n];
for ( int i = 0; i < arrayOfButtons.length; i++)
{
for ( int j = 0; j < arrayOfButtons[i].length; j++)
arrayOfButtons[i][j] = new JButton("0");
}
for (int i = 0; i < arrayOfButtons.length; i++)
{
for ( int j = 0; j < arrayOfButtons[i].length; j++)
arrayOfButtons[i][j].addActionListener(this);
}
for ( int i = 0; i < arrayOfButtons.length; i++)
{
for ( int j = 0; j < arrayOfButtons[i].length; j++)
pane.add(arrayOfButtons[i][j]);
}
pane.setLayout(new GridLayout((n+1), (n+1)));
pane.add(surrenderB);
pane.add(quitB);
pane.add(shotsLabel);
pane.add(shotsTF);
// the char array is where the actual 1 square battleship is going to be placed.
// it is a n by n grid and the other array needs to be too to make them parallel.
// A value in the arrayOfButtons[i][j] should be the same as charArray[x][y].
} // end of if
// makes an n by n grid
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
} // end of constructor
public static void main(String[] args)
{ // beginning of main
BattleshipGUI refVar = new BattleshipGUI();
} // end of main
// this method handles the buttons.
public void actionPerformed(ActionEvent e)
{ // beginning of method
String outputStr2, outputStr3, outputStr4, outputStr5, outputStr6;
String outputStrM, outputStrA, outputStrAA;
outputStrM = "Miss";
outputStrA = "Already shot there";
outputStrAA = "I told you that you already shot there";
outputStr2 = "Are you sure you want to quit? ";
outputStr3 = "You Quit.";
outputStr4 = "Ok don't quit then." ;
outputStr5 = "Thought not.";
outputStr6 = "You surrendered.";
int i, j, x,y;
x = 0;
i = 0;
y = 0;
j = 0;
/* for (int r = 0; r < arrayOfButtons.length; r++)
{
for (int c = 0; c < arrayOfButtons[r].length; c++)
if (arrayOfButtons[r][c].isSelected())
{
i = r;
j = c;
}
} */
int shots = Integer.parseInt(shotsTF.getText());
placeBattleship(charArray);
Integer tries;
Integer tries2;
Integer tries3;
Integer tries4;
Integer tries5;
tries = shots;
tries2 = shots;
tries3 = shots;
tries4 = shots;
tries5 = shots;
if (e.getActionCommand().equals("Quit"))
{ // beginning of if
Object[] options = {"Yes",
"Continue Playing"};
int n = JOptionPane.showOptionDialog(frame,
"Are you sure you want to Quit?",
"Quit",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
// creates Yes and Continue playing butons buttons.
// if Yee button is clicked, sends output "You quit." as heading and sends a message "Adiós!" and exits when
// user clicks OK on dialog box
if (n == JOptionPane.YES_OPTION)
{ // beginning of if
JOptionPane.showMessageDialog(null,"Adiós!", outputStr3, JOptionPane.PLAIN_MESSAGE);
System.exit(0);
} // end of if
// changes the string the standard dialog box for the No button but still uses its predefined return value. If user clicks on
// Continue Playing, sends title "Ok don't quit then." and the message "Whatever." and takes the user back to the grid.
else if (n == JOptionPane.NO_OPTION)
{ // beginning of else if
JOptionPane.showMessageDialog(null,"Whatever.", outputStr4, JOptionPane.PLAIN_MESSAGE);
} // end of else if
} // end of if
else if (e.getActionCommand().equals("Surrender"))
{ // beginning of else if
Object[] options2 = {"Yes",
"No, I have not yet begun to fight!"};
int p = JOptionPane.showOptionDialog(frame,
"Are you sure you want to Surrender?",
"Surrender?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, options2, options2[0]);
// creates Yes and No, I have not yet begun to fight! butons .
// if Yes button is clicked, sends output "You surrendered." as heading and sends a message "It took you [number of shots]
// shots!" and exits when user clicks OK on dialog box
if (p == JOptionPane.YES_OPTION)
{ // beginning of if
// code for showing grid
arrayOfButtons[i][j].setText("B");
JOptionPane.showMessageDialog(null, "You took " + shotsTF.getText() + " shots" , outputStr6, JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
} // end of if
// changes the string the standard dialog box for the No button but still uses its predefined return value. If user clicks on
// "No button", sends output "Thought not." and the title "You didn't surrender." and takes the user back to the grid.
else if (p == JOptionPane.NO_OPTION)
{ // beginning of else if
JOptionPane.showMessageDialog(null, outputStr5, "You didn't surrender." , JOptionPane.PLAIN_MESSAGE);
} // end of else if
} // end of else if
else if (e.getActionCommand().equals("0"))
{ // beginning of else if
if ( Fire(charArray, x, y) == 'H')
{ // beginning of if
String outputStr7;
arrayOfButtons[i][j].setText("H"); // changes text on button to H
shots = shots + 1;
tries = new Integer(shots);
shotsTF.setText(tries.toString());
outputStr7 = "You sank my battleship. " + "\n" + "You sank my battleship in " + shotsTF.getText() + " tries";
JOptionPane.showMessageDialog(null, outputStr7 , "You win!", + JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}// end of if
else
{ // beginning of else
JOptionPane.showMessageDialog(null, outputStrM , "You missed!", + JOptionPane.INFORMATION_MESSAGE);
arrayOfButtons[i][j].setText("M"); // changes text on button to M
shots = shots + 1;
tries2 = new Integer(shots);
shotsTF.setText(tries2.toString());
System.out.println(arrayOfButtons[i][j]);
} // end of else
} // end of else if
// does this if text on button hit is M.
else if (e.getActionCommand().equals("M"))
{ // beginning of else if
shots = shots + 1;
tries3 = new Integer(shots);
shotsTF.setText(tries3.toString());
JOptionPane.showMessageDialog(null, outputStrA , "Still a miss!", + JOptionPane.INFORMATION_MESSAGE);
arrayOfButtons[i][j].setText("A"); // changes text on button to A
} // end of else if
// does this if text on button hit is A
else if (e.getActionCommand().equals("A"))
{ // beginning of else if
shots = shots + 1;
tries4 = new Integer(shots);
shotsTF.setText(tries4.toString());
JOptionPane.showMessageDialog(null, outputStrAA , "Still a miss!", + JOptionPane.INFORMATION_MESSAGE);
arrayOfButtons[i][j].setText("A"); // changes text, sorta, on button to A
} // end of else if
} // end of method
// the method placeBattleship, places the battleship by randomly choosing a
// row and column coordinate and storing a 'B' there. The 'B' is not displayed to
// the user unless the user hits the surrender button. It takes the array as a parameter and
// should return nothing. This method sets the location of the battleship.
private static void placeBattleship(char charArray[][])
{ // beginning of method placeBattleship
int valueOne, valueTwo;
char B;
valueOne= (int) ( 1 + (Math.random() * charArray.length -1));
valueTwo = (int) ( 1 + (Math.random() * charArray.length -1 ));
charArray[valueOne][valueTwo] = 'B';
} //end of method placeBattleship
public static char Fire(char charArray[][], int x, int y)
{ // beginning of method Fire
char A;
char M;
char H;
if (charArray[x][y] == 'B') // if battleship is hit return H and end game
{ // beginning of if statement
charArray[x][y] = 'H';
return ('H');
} // end of if statement
else if (charArray[x][y] == 'M') // this is else if
// because it could also
// be just a miss.
{ // beginning of else if statement
charArray[x][y] = 'A';
return ('A');
} // end of else if statement
else if (charArray[x][y] == 'A') // makes sure it won't set an A to an M again.
{ // beginning of else if
charArray[x][y] = 'A';
return ('A');
} // end of else if
else
{ // beginning of else statement
charArray[x][y] = 'M';
return ('M');
} // end of else statement
} // end of method fire
} // end of program