SlideShare a Scribd company logo
1 of 15
Download to read offline
i need a taking turn method for a player vs computer battleship game in java. when a user slects
on players board then computer should be able to pick one on the computer board. this should
continue to repeat the order until the first one finds all the ship on their board first.
Solution
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*;
import java.io.*; import java.lang.Integer; import java.util.Vector; import java.net.*; public class
Battleship extends JFrame { private static JButton ok = new
JButton("OK"),//closes stats menu done =new
JButton("Done");//closes options menu private static JFrame statistics= new
JFrame("Statistics"),//holds stats options=new
JFrame("Options");//holds opts private static JLabel data,//used for stats menu
title;//used for options menu private static JPanel stats=new
JPanel(),//used for stats menu opts,//used for options menu
inputpanel;//for manually inputting ships private static Container
b,c,d;//board and input panel private JPanel input;//input bar private static
JMenuItem m,pvp,pvc,cvc;//menu items private static String[] cletters = {"
","A","B","C","D","E","F","G","H","I","J"}, //array of letters used for combo
boxes cnumbers = {"
","1","2","3","4","5","6","7","8","9","10"}, //array of numbers used for
combo boxes ships =
{"Carrier","Battleship","Submarine","Destroyer", "Patrol
Boat"},//strings used for ship combo box direction =
{"Horizontal","Vertical"},//directions level={"Normal",
"Ridiculously Hard"}, layout={"Manual","Automatic"},
colors={"Cyan", "Green", "Yellow", "Magenta", "Pink", "Red",
"White"}, first={"Player 1", "Player 2",
"Random"};//used for options private JComboBox cshi = new JComboBox(ships),//ships
cdir = new JComboBox(direction);//directions private static
JComboBox aiLevel=new JComboBox(level), shipLayout=new
JComboBox(layout), shipColor=new JComboBox(colors),
playsFirst=new JComboBox(first);//used
//for options menu private JTextField mbar = new JTextField();//message bar
private static int enemy=1, i,j,//counters
length=5, you=0,
prevcolor=0,//index of previous color prevFirst=0,
prevLayout=0, prevLevel=0,//tracks changes in corresponding comboboxes
ready=0, sindex=0,//stores index of array
dindex=0;//direction private static Player players[]=new Player[2]; private static
JButton deploy=new JButton("DEPLOY"); private static int
w=0,a=0,s=0,t=0,e=0;//counters to track the use of all ships private static String[][]
shiphit=new String[10][10]; private static String user,user2; private static Color[]
color={Color.cyan,Color.green,Color.yellow,Color.magenta,
Color.pink, Color.red, Color.white}; private static Object
selectedValue=" ", gametype; private static
BattleshipClient me; private static boolean gameover=false; public Battleship()
{ setTitle("Battleship");
setDefaultCloseOperation(EXIT_ON_CLOSE); setJMenuBar(createMenuBar());
setResizable(false); //gets user to input name
user=JOptionPane.showInputDialog("Enter your name."); int dummy=0;
while (((user==null)||(user.equals("")))&&(dummy<3)) {
user=JOptionPane.showInputDialog("You have to input something."); if
((user!=null)&&(!user.equals(""))) dummy=4; else
dummy++; } if (dummy==3) {
JOptionPane.showMessageDialog(null,"Since you're having trouble inp"
+"utting your name, I'll just call you stupid.","",JOptionPane.INFORMATION_MESSAGE);
user="Stupid"; } players[you]=new Player (user);
players[enemy]=new Player ("Computer");
b=getContentPane(); b.add(setBoard(you),BorderLayout.CENTER);
c=getContentPane(); d = getContentPane();
inputpanel=shipinput(); d.add(inputpanel,BorderLayout.NORTH);
pack(); setVisible(true); } public static boolean
getGameOver() { return gameover; } public static void
setGameOver(boolean b) { gameover=b; } //method to
determine who plays first public void whoGoesFirst() { int x=0; if
(playsFirst.getSelectedIndex()!=2) { if
(playsFirst.getSelectedIndex()!=you) flipYou();
players[playsFirst.getSelectedIndex()].getTimer().start();
x=playsFirst.getSelectedIndex(); } else {
int rand=(int)(Math.random()*2);
JOptionPane.showMessageDialog(null,players[rand].getUser()+" will " +"go
first.","",JOptionPane.PLAIN_MESSAGE); if (rand!=you)
flipYou(); players[rand].getTimer().start(); x=rand; }
if
((!players[x].getUser().equals("Computer"))||(!players[x].getUser().equals("CPU1"))||(!players
[x].getUser().equals("CPU2"))) players[x].setMove(true); }
//returns ship color, as selected by the user public static Color getColor() {
return (color[shipColor.getSelectedIndex()]); } //asks if two players
are playing on the same computer or over the web public static boolean isLocal() {
if ((gametype==pvp)&&(selectedValue.equals("Local"))) return true;
else return false; } public static void flipYou() {
if (you==1) { you=0; enemy=1; }
else { you=1; enemy=0; } }
//determines whether or not is shipLayout is set to automatic public static boolean
isAutoSet() { if (shipLayout.getSelectedIndex()==0) return false;
else return true; } //variable that determines whether
or not a carrier has been placed public static int getW() { return w;
} //variable that determines whether or not a battleship has been placed public
static int getA() { return a; } //variable that determines
whether or not a submarine has been placed public static int getS() { return s;
} //variable that determines whether or not a destroyer has been placed
public static int getT() { return t; } //variable that determines
whether or not a patrol boat has been placed public static int getE() { return
e; } public static int getReady() { return ready;
} public static JFrame getStatistics() { return statistics; }
public static void setData(JLabel x) { data=x; } public static
JLabel getData() { return data; } public static JPanel getStats()
{ return stats; } public static void setDeploy(boolean k) {
deploy.setEnabled(k); } public static Player getPlayers(int x)
{ return players[x]; } public static String getDirection(int i) {
return direction[i]; } public static String getCletters(int i) {
return cletters[i]; } public static String getShips(int i) {
return ships[i]; } public static String getCnumbers(int i) {
return cnumbers[i]; } public static int getSIndex() { return
sindex; } public static int getDIndex() { return dindex; }
public static int getYou() { return you; } public
static int getEnemy() { return enemy; } public static void
setYou(int x) { you=x; } public static void setEnemy(int x)
{ enemy=x; } //creates Game menu and submenus public
JMenuBar createMenuBar() { JMenu menu;//menu // create the
menu bar JMenuBar menuBar = new JMenuBar(); // build the Game menu
menu = new JMenu("Game"); menuBar.add(menu); m = new
JMenu("New Game"); menu.add(m); //submenu of New
Game GameListener stuff = new GameListener(); pvp = new
JMenuItem("Player vs. Player"); pvp.addActionListener(stuff);
m.add(pvp); pvc = new JMenuItem("Player vs. Computer");
pvc.addActionListener(stuff); m.add(pvc); cvc = new
JMenuItem("Computer vs. Computer"); cvc.addActionListener(stuff);
m.add(cvc); m = new JMenuItem("Rules");
m.addActionListener(new RulesListener()); menu.add(m); m = new
JMenuItem("Statistics"); m.addActionListener(new StatsListener());
menu.add(m); m = new JMenuItem("Options"); m.addActionListener(new
OptionsListener()); menu.add(m); m = new JMenuItem("Exit");
m.addActionListener(new ExitListener()); menu.add(m); return
menuBar; } //creates panels that used to place ships public JPanel
shipinput() { input= new JPanel(); mbar.setText("Select a ship, its front
position and direction."); mbar.setFont(new Font("Courier New", Font.BOLD, 14));
mbar.setEditable(false); //input.add(mbar); cshi.setSelectedIndex(0);
cshi.addActionListener(new ShipsListener()); TitledBorder title;//used for
titles around combo boxes title = BorderFactory.createTitledBorder("Ships");
cshi.setBorder(title); input.add(cshi); cdir.setSelectedIndex(0);
cdir.addActionListener(new DirectListener()); input.add(cdir);
title = BorderFactory.createTitledBorder("Direction"); cdir.setBorder(title);
deploy.setEnabled(false); deploy.addActionListener(new DeployListener());
input.add(deploy); return input; } //creates board for manual
ship placement public JPanel setBoard(int n) { players[n].setMyBoard(new
JPanel(new GridLayout(11,11)));//panel to store board JTextField k;
for (i=0;i<11;i++) { for (j=0;j<11;j++)
{ if ((j!=0)&&(i!=0)) {
players[n].getBboard(i-1,j-1).addActionListener(new BoardListener());
players[n].getMyBoard().add(players[n].getBboard(i-1,j-1)); }
if (i==0) {
if (j!=0) { //used to
display row of numbers k= new
JTextField(Battleship.getCnumbers(j)); k.setEditable(false);
k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT);
} else
{ //used to display column of numbers
k= new JTextField(); k.setEditable(false);
}
players[n].getMyBoard().add(k); } else if (j==0)
{ k= new
JTextField(Battleship.getCletters(i)); k.setEditable(false);
k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT);
players[n].getMyBoard().add(k); } }
} return players[n].getMyBoard(); } //creates board and
automatically places ship public JPanel autoBoard(int u,int t) {
players[u].setGBoard(new JPanel(new GridLayout(11,11)));//panel to store board
JTextField k; if (!players[u].getUser().equals("Unknown")) for
(i=0;i<5;i++) {
players[u].setBoats(i,players[u].getBoats(i).compinput(i,u)); }
for (i=0;i<11;i++) { for (j=0;j<11;j++) {
if ((j!=0)&&(i!=0)) {
if ((players[u].getUser().equals("Computer"))||(isLocal()))
{
players[u].getBboard(i-1,j-1).addActionListener(new AttackListener());
}
else if
((players[t].getUser().equals("Computer"))||(players[t].getUser().equals("CPU1"))||(players[t].
getUser().equals("CPU2"))||(players[t].getUser().equals("Unknown")))
{ if (players[u].getHitOrMiss(i-1,j-1))
players[u].setBboard(i-1,j-1,getColor());
} else {
players[u].getBboard(i-1,j-1).addActionListener(new InternetListener());
} players[u].getGBoard().add(players[u].getBboard(i-
1,j-1)); } if (i==0)
{ if (j!=0) {
//used to display row of numbers k= new
JTextField(Battleship.getCnumbers(j)); k.setEditable(false);
k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT);
} else
{ //used to display column of numbers
k= new JTextField(); k.setEditable(false);
}
players[u].getGBoard().add(k); } else if (j==0)
{ k= new
JTextField(Battleship.getCletters(i)); k.setEditable(false);
k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT);
players[u].getGBoard().add(k); } }
} return players[u].getGBoard(); }
//Listener for combo boxes used to layout ships private class ShipsListener implements
ActionListener { public void actionPerformed(ActionEvent v) {
sindex=cshi.getSelectedIndex(); if
(players[you].getBoats(sindex)!=null)
cdir.setSelectedIndex(players[you].getBoats(sindex).getDirect()); switch (sindex)
{ case 0: length=5; break;
case 1: length=4; break; case 2:
length=3; break; case 3: length=3;
break; case 4: length=2; break;
} if (players[you].getBoats(sindex) != null)
{ Ship boat=new
Ship(ships[sindex],players[you].getBoats(sindex).getDirect()
,length,players[you].getBoats(sindex).getX(),players[you].getBoats(sindex).getY());
players[you].getBoats(sindex).clearship();
players[you].setBoats(sindex,boat);
players[you].getBoats(sindex).placeship(); }
} } //Listener for the Direction
combo box private class DirectListener implements ActionListener {
public void actionPerformed(ActionEvent v) {
dindex = cdir.getSelectedIndex(); if
(players[you].getBoats(sindex) != null) { Ship boat=new
Ship(ships[sindex],dindex,players[you].getBoats(sindex).getLength(),
players[you].getBoats(sindex).getX(),players[you].getBoats(sindex).getY());
players[you].getBoats(sindex).clearship();
players[you].setBoats(sindex,boat);
players[you].getBoats(sindex).placeship(); }
} } //Listener for the buttons on the board
private class BoardListener implements ActionListener { public void
actionPerformed(ActionEvent v) { if (ready==0)
{ if (players[you].getBoats(sindex)!=null)
players[you].getBoats(sindex).clearship(); Object source = v.getSource();
outer: for (i=0;i<10;i++)
{ for (j=0;j<10;j++)
{ if (source==players[you].getBboard(i,j))
{ switch (sindex)
{ case 0: {
if (w==0)
w++;
}
break;
case 1: {
if (a==0) a++;
} break;
case 2: {
if (s==0)
s++; }
break; case 3: {
if (t==0)
t++;
}
break; case 4: {
if (e==0)
e++;
} break;
}
players[you].setBoats(sindex,new Ship(ships[sindex],dindex,length,i,j));
break outer;
} } }
players[you].getBoats(sindex).placeship(); }
} } //creates a panel that tells whose board is which private JPanel
whoseBoard() { JPanel panel=new JPanel(new BorderLayout());
panel.add(new JLabel(players[you].getUser()+"'s
Board",SwingConstants.LEFT),BorderLayout.WEST); panel.add(new
JLabel(players[enemy].getUser()+"'s Board",SwingConstants.RIGHT),BorderLayout.EAST);
return panel; } //Listener for exit choice on Game menu private
class ExitListener implements ActionListener { public void
actionPerformed(ActionEvent e) { int r=
JOptionPane.showConfirmDialog(null,"Are you sure you would l" +"ike to exit
Battleship?", "Exit?", JOptionPane.YES_NO_OPTION); if (r==0)
System.exit(0); } } //listener for New Game submenu
private class GameListener implements ActionListener { public void
actionPerformed(ActionEvent e) { int q=
JOptionPane.showConfirmDialog(null,"Are you sure you would l" +"ike to
start a new game?", "New Game?", JOptionPane.YES_NO_OPTION); if
(q==0) { //resets variables
b.removeAll(); c.removeAll(); d.removeAll();
you=0; enemy=1;
ready=0; if (players[you].getTimer()!=null)
if (players[you].getTimer().isRunning())
players[you].getTimer().stop(); if (players[enemy].getTimer()!=null)
if (players[enemy].getTimer().isRunning())
players[enemy].getTimer().stop();
gametype = e.getSource();
if (gametype==pvp) { if (!selectedValue.equals("no
server")) { String[] possibleValues = {
"Local", "Online"}; selectedValue =
JOptionPane.showInputDialog(null, "Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null, possibleValues,
possibleValues[0]); } if
(!players[you].getUser().equals("CPU1")) {
if (players[you].getUser().equals("Stupid")) {
int w=JOptionPane.showConfirmDialog(null,"Would you"
+" like to try inputting your name again?","",
JOptionPane.YES_NO_OPTION); if
(w==JOptionPane.YES_OPTION) {
user=JOptionPane.showInputDialog("Enter your name.");
int dummy=0; while
(((user==null)||(user.equals("")))&&(dummy<3)) {
user=JOptionPane.showInputDialog("You have to input something.");
if ((user!=null)&&(!user.equals("")))
dummy=4; else
dummy++; }
if (dummy==3) {
JOptionPane.showMessageDialog(null,"Still a"
+"cting stupid. Oh well, we'll run with it."
,"",JOptionPane.INFORMATION_MESSAGE);
user="Stupid"; }
else
JOptionPane.showMessageDialog(null,"That wasn't"
+" so hard now, was it?","YEAH!",
JOptionPane.INFORMATION_MESSAGE);
} }
players[you]=new Player (players[you].getUser());
} else
players[you]=new Player (user);
if (selectedValue.equals("Online")) {
players[enemy]=new Player ("Unknown"); if (!isAutoSet())
{
b.add(setBoard(you),BorderLayout.CENTER);
deploy.setEnabled(false);
d.add(inputpanel,BorderLayout.NORTH); }
else {
b.add(autoBoard(you,enemy),BorderLayout.WEST);
c.add(autoBoard(enemy,you),BorderLayout.EAST); ready=1;
} } else
{ //gets user to input name
if((players[enemy].getUser().equals("Computer"))||(players[enemy].getUser().equals("CPU2")
)||(players[enemy].getUser().equals("Unknown"))) {
user2=JOptionPane.showInputDialog("Enter your name.");
while ((user2==null)||(user2.equals("")))
{
user2=JOptionPane.showInputDialog("You have to input something.");
}
} else
user2=players[enemy].getUser(); players[enemy]=new Player
(user2); b.add(autoBoard(you,enemy),BorderLayout.WEST);
c.add(autoBoard(enemy,you),BorderLayout.EAST);
d.add(whoseBoard(),BorderLayout.NORTH);
whoGoesFirst(); ready=1;
} //ready=1; } else if
(gametype==pvc)//Player vs Computer {
if (!players[you].getUser().equals("CPU1")) {
if (players[you].getUser().equals("Stupid"))
{ int w=JOptionPane.showConfirmDialog(null,"Would you"
+" like to try inputting your name again?","",
JOptionPane.YES_NO_OPTION); if
(w==JOptionPane.YES_OPTION) {
user=JOptionPane.showInputDialog("Enter your name.");
int dummy=0; while
(((user==null)||(user.equals("")))&&(dummy<3)) {
user=JOptionPane.showInputDialog("You have to input something.");
if ((user!=null)&&(!user.equals("")))
dummy=4; else
dummy++; }
if (dummy==3) {
JOptionPane.showMessageDialog(null,"Still a"
+"cting stupid. Oh well, we'll run with it."
,"",JOptionPane.INFORMATION_MESSAGE);
user="Stupid"; }
else
JOptionPane.showMessageDialog(null,"That wasn't"
+" so hard now, was it?","YEAH!",
JOptionPane.INFORMATION_MESSAGE);
} }
players[you]=new Player (players[you].getUser());
} else
players[you]=new Player (user);
players[enemy]=new Player ("Computer"); if
(!isAutoSet()) {
b.add(setBoard(you),BorderLayout.CENTER);
deploy.setEnabled(false);
d.add(inputpanel,BorderLayout.NORTH); }
else {
b.add(autoBoard(you,enemy),BorderLayout.WEST);
c.add(autoBoard(enemy,you),BorderLayout.EAST); whoGoesFirst
(); } } else if
(gametype==cvc)//Computer vs Computer {
mbar.setText("Battleship Demo");
mbar.setEditable(false);
d.add(mbar,BorderLayout.NORTH); players[you]=new Player
("CPU1"); players[enemy]=new Player ("CPU2");
b.add(autoBoard(you,enemy),BorderLayout.WEST);
c.add(autoBoard(enemy,you),BorderLayout.EAST);
whoGoesFirst(); }
pack(); repaint(); }
} } //Listener for Rules menu private class
RulesListener implements ActionListener { public void
actionPerformed(ActionEvent e) { } }
//Listener for ok button in statistics menu private class OkListener implements
ActionListener { public void actionPerformed(ActionEvent e) {
statistics.dispose(); } } //Listener for Stats menu
private class StatsListener implements ActionListener { // public
void setup() { stats=new JPanel();
ok.addActionListener(new OkListener()); statistics.setSize(300,300);
statistics.setResizable(false);
statistics.getContentPane().add(ok,BorderLayout.SOUTH);
//statistics.setLocation(700,200); } public
void actionPerformed(ActionEvent e) { if
(data==null) setup(); else
stats.removeAll(); stats.setLayout(new GridLayout(6,3));
data=new JLabel(""); stats.add(data); data=new
JLabel("Player 1",SwingConstants.CENTER); stats.add(data);
data=new JLabel("Player 2",SwingConstants.CENTER); stats.add(data);
data=new JLabel("Names"); stats.add(data);
if (you == 0) {
data=new JLabel(players[you].getUser(),SwingConstants.CENTER);
stats.add(data); data=new
JLabel(players[enemy].getUser(),SwingConstants.CENTER);
stats.add(data); data=new JLabel("Shots Taken");
stats.add(data); data=new
JLabel(Integer.toString(players[you].getShots()),SwingConstants.CENTER);
stats.add(data); data=new
JLabel(Integer.toString(players[enemy].getShots()),SwingConstants.CENTER);
stats.add(data); data=new JLabel("Hits");
stats.add(data); data=new
JLabel(Integer.toString(players[you].getHits()),SwingConstants.CENTER);
stats.add(data); data=new
JLabel(Integer.toString(players[enemy].getHits()),SwingConstants.CENTER);
stats.add(data); data=new JLabel("Shot Accuracy");
stats.add(data); data=new
JLabel(players[you].getAcc(),SwingConstants.CENTER); stats.add(data);
data=new JLabel(players[enemy].getAcc(),SwingConstants.CENTER);
stats.add(data); data=new JLabel("Ships Left");
stats.add(data); data=new
JLabel(Integer.toString(players[you].getShipsLeft()),SwingConstants.CENTER);
stats.add(data); data=new
JLabel(Integer.toString(players[enemy].getShipsLeft()),SwingConstants.CENTER);
stats.add(data); } else {
data=new
JLabel(players[enemy].getUser(),SwingConstants.CENTER);
stats.add(data); data=new
JLabel(players[you].getUser(),SwingConstants.CENTER); stats.add(data);
data=new JLabel("Shots Taken"); stats.add(data);
data=new
JLabel(Integer.toString(players[enemy].getShots()),SwingConstants.CENTER);
stats.add(data); data=new
JLabel(Integer.toString(players[you].getShots()),SwingConstants.CENTER);
stats.add(data); data=new JLabel("Hits");
stats.add(data); data=new
JLabel(Integer.toString(players[enemy].getHits()),SwingConstants.CENTER);
stats.add(data); data=new
JLabel(Integer.toString(players[you].getHits()),SwingConstants.CENTER);
stats.add(data); data=new JLabel("Shot Accuracy");
stats.add(data); data=new
JLabel(players[enemy].getAcc(),SwingConstants.CENTER); stats.add(data);
data=new JLabel(players[you].getAcc(),SwingConstants.CENTER);
stats.add(data); data=new JLabel("Ships Left");
stats.add(data); data=new
JLabel(Integer.toString(players[enemy].getShipsLeft()),SwingConstants.CENTER);
stats.add(data); data=new
JLabel(Integer.toString(players[you].getShipsLeft()),SwingConstants.CENTER);
stats.add(data); } statistics.getContentPane().add(stats);
statistics.pack(); statistics.setVisible(true);
} } //Listener for Deploy Button private class DeployListener
implements ActionListener { public void actionPerformed(ActionEvent v)
{ int r= JOptionPane.showConfirmDialog(null,"Are you sure you
would l" +"ike to deploy your ships?", "Deploy Ships?",
JOptionPane.YES_NO_OPTION); if (r==0) {
w=0; a=0; s=0; t=0;
e=0; d.remove(input);
b.add(players[you].getMyBoard(),BorderLayout.WEST); ready=1;
c.add(autoBoard(enemy,you),BorderLayout.EAST);
d.add(new JPanel(),BorderLayout.CENTER);
if (!selectedValue.equals("Online"))
whoGoesFirst(); pack();
repaint(); } }
} //Listener for Options menu public class OptionsListener implements ActionListener
{ public void actionPerformed(ActionEvent e) {
if (opts==null) setup(); else
options.setVisible(true); } public
void setup() { opts=new JPanel(new GridLayout(4,2));
title=new JLabel("Computer AI"); opts.add(title);
aiLevel.setSelectedIndex(0); opts.add(aiLevel);
title=new JLabel("Ship Layout"); opts.add(title);
shipLayout.setSelectedIndex(0); opts.add(shipLayout);
title=new JLabel("Ship Color"); opts.add(title);
shipColor.addActionListener(new SColorListener());
shipColor.setSelectedIndex(0); opts.add(shipColor); title=new
JLabel("Who Plays First?"); opts.add(title);
playsFirst.setSelectedIndex(0); opts.add(playsFirst);
options.getContentPane().add(opts,BorderLayout.CENTER);
//options.setSize(600,800); options.setResizable(false);
done.addActionListener(new DoneListener());
options.getContentPane().add(done,BorderLayout.SOUTH);
options.setLocation(200,200); options.pack();
options.setVisible(true); } //Listener for the Colors
combo box private class SColorListener implements ActionListener
{ public void actionPerformed(ActionEvent v) {
for (i=0;i<10;i++) for (j=0;j<10;j++)
{ if
(players[you].getBboard(i,j).getBackground()==color[prevcolor])
players[you].setBboard(i,j,color[shipColor.getSelectedIndex()]);
if (players[enemy].getBboard(i,j).getBackground()
==color[prevcolor])
players[enemy].setBboard(i,j,color[shipColor.getSelectedIndex()]);
} prevcolor=shipColor.getSelectedIndex(); } }
//Listener for ok button in statistics menu private class
DoneListener implements ActionListener { public void
actionPerformed(ActionEvent e) { if
((shipLayout.getSelectedIndex()!=prevLayout)||
(aiLevel.getSelectedIndex()!=prevLevel)||
(playsFirst.getSelectedIndex()!=prevFirst)) {
JOptionPane.showMessageDialog(null,"Changes will take"+ " place
at the start of a new game.","" ,JOptionPane.PLAIN_MESSAGE);
if (shipLayout.getSelectedIndex()!=prevLayout)
prevLayout=shipLayout.getSelectedIndex(); if
(playsFirst.getSelectedIndex()!=prevFirst)
prevFirst=playsFirst.getSelectedIndex(); if
(aiLevel.getSelectedIndex()!=prevLevel)
prevLevel=aiLevel.getSelectedIndex(); }
options.dispose(); } } } public static
BattleshipClient getClient() { return me; } public static
void main(String[] args){ Battleship gui= new Battleship();
while (gui.isActive()) { while (selectedValue.equals(" "))
{ } System.out.println("xenophobia");
System.out.println("Object = "+selectedValue); if
(selectedValue.equals("Online")) { selectedValue=" ";
while (ready!=1) { }
try { me=new BattleshipClient();
if (!me.getServerName().equals("invalid")) {
me.sendShips(); while (!gameover)
{ if (!players[you].getMove())
{ try
{ me.listen();
} catch
(IOException e){ System.out.println("Aw naw."); }
} while (players[you].getMove())
{ } me.results();
} }
else { b.removeAll();
c.removeAll(); d.removeAll();
players[you]=new Player (user); players[enemy]=new Player
("Computer");
b.add(gui.setBoard(you),BorderLayout.CENTER);
inputpanel=gui.shipinput();
d.add(inputpanel,BorderLayout.NORTH); gui.pack();
gui.repaint(); }
} catch (IOException e)
{ System.out.println("You Suck"); } } }
//System.out.println("okay"); } }

More Related Content

Similar to i need a taking turn method for a player vs computer battleship game.pdf

import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfaoneonlinestore1
 
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfrajkumarm401
 
import java.awt.;class FlowLayoutDemo {    public static void.pdf
import java.awt.;class FlowLayoutDemo {    public static void.pdfimport java.awt.;class FlowLayoutDemo {    public static void.pdf
import java.awt.;class FlowLayoutDemo {    public static void.pdfapjewellers
 
i have a runable code below that works with just guessing where the .pdf
i have a runable code below that works with just guessing where the .pdfi have a runable code below that works with just guessing where the .pdf
i have a runable code below that works with just guessing where the .pdfarmcomputers
 
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdfimport java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdfvenkt12345
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfarchanaemporium
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdffonecomp
 
20-Arid-850 Ali Haider Cheema BSSE(5A) Evening MPL Assignement 08.docx
20-Arid-850 Ali Haider Cheema BSSE(5A) Evening MPL Assignement 08.docx20-Arid-850 Ali Haider Cheema BSSE(5A) Evening MPL Assignement 08.docx
20-Arid-850 Ali Haider Cheema BSSE(5A) Evening MPL Assignement 08.docxAliHaiderCheema2
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfsooryasalini
 
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfTic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfinfomalad
 
Tic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdfTic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdfformaxekochi
 
Tank Battle - A simple game powered by JMonkey engine
Tank Battle - A simple game powered by JMonkey engineTank Battle - A simple game powered by JMonkey engine
Tank Battle - A simple game powered by JMonkey engineFarzad Nozarian
 
i have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfi have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfpoblettesedanoree498
 
Unity遊戲程式設計 - 2D platformer game
Unity遊戲程式設計 - 2D platformer gameUnity遊戲程式設計 - 2D platformer game
Unity遊戲程式設計 - 2D platformer game吳錫修 (ShyiShiou Wu)
 
Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲吳錫修 (ShyiShiou Wu)
 
Java ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdfJava ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdfatulkapoor33
 
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfmohammedfootwear
 
VideoGamepublic class VideoGam.pdf
VideoGamepublic class VideoGam.pdfVideoGamepublic class VideoGam.pdf
VideoGamepublic class VideoGam.pdfannaistrvlr
 

Similar to i need a taking turn method for a player vs computer battleship game.pdf (20)

import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
 
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
 
import java.awt.;class FlowLayoutDemo {    public static void.pdf
import java.awt.;class FlowLayoutDemo {    public static void.pdfimport java.awt.;class FlowLayoutDemo {    public static void.pdf
import java.awt.;class FlowLayoutDemo {    public static void.pdf
 
i have a runable code below that works with just guessing where the .pdf
i have a runable code below that works with just guessing where the .pdfi have a runable code below that works with just guessing where the .pdf
i have a runable code below that works with just guessing where the .pdf
 
Final_Project
Final_ProjectFinal_Project
Final_Project
 
662305 11
662305 11662305 11
662305 11
 
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdfimport java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdf
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdf
 
20-Arid-850 Ali Haider Cheema BSSE(5A) Evening MPL Assignement 08.docx
20-Arid-850 Ali Haider Cheema BSSE(5A) Evening MPL Assignement 08.docx20-Arid-850 Ali Haider Cheema BSSE(5A) Evening MPL Assignement 08.docx
20-Arid-850 Ali Haider Cheema BSSE(5A) Evening MPL Assignement 08.docx
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdf
 
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfTic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
 
Tic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdfTic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdf
 
Tank Battle - A simple game powered by JMonkey engine
Tank Battle - A simple game powered by JMonkey engineTank Battle - A simple game powered by JMonkey engine
Tank Battle - A simple game powered by JMonkey engine
 
i have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfi have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdf
 
Unity遊戲程式設計 - 2D platformer game
Unity遊戲程式設計 - 2D platformer gameUnity遊戲程式設計 - 2D platformer game
Unity遊戲程式設計 - 2D platformer game
 
Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲
 
Java ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdfJava ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdf
 
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
 
VideoGamepublic class VideoGam.pdf
VideoGamepublic class VideoGam.pdfVideoGamepublic class VideoGam.pdf
VideoGamepublic class VideoGam.pdf
 

More from petercoiffeur18

John, a sociologist, will be focusing on how larger societal institu.pdf
John, a sociologist, will be focusing on how larger societal institu.pdfJohn, a sociologist, will be focusing on how larger societal institu.pdf
John, a sociologist, will be focusing on how larger societal institu.pdfpetercoiffeur18
 
Implement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdfImplement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdfpetercoiffeur18
 
In what ways do humans effect the environment Explain in 200 words.pdf
In what ways do humans effect the environment Explain in 200 words.pdfIn what ways do humans effect the environment Explain in 200 words.pdf
In what ways do humans effect the environment Explain in 200 words.pdfpetercoiffeur18
 
I am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdfI am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdfpetercoiffeur18
 
how internal resources and capabilities can be a source of sustainab.pdf
how internal resources and capabilities can be a source of sustainab.pdfhow internal resources and capabilities can be a source of sustainab.pdf
how internal resources and capabilities can be a source of sustainab.pdfpetercoiffeur18
 
For an organism that is growing using glucose as the electron donor, .pdf
For an organism that is growing using glucose as the electron donor, .pdfFor an organism that is growing using glucose as the electron donor, .pdf
For an organism that is growing using glucose as the electron donor, .pdfpetercoiffeur18
 
Exercise 5.6.28. For each of the following descriptions of a function.pdf
Exercise 5.6.28. For each of the following descriptions of a function.pdfExercise 5.6.28. For each of the following descriptions of a function.pdf
Exercise 5.6.28. For each of the following descriptions of a function.pdfpetercoiffeur18
 
Discuss concepts associated with mercantilism demonstrating key poli.pdf
Discuss concepts associated with mercantilism demonstrating key poli.pdfDiscuss concepts associated with mercantilism demonstrating key poli.pdf
Discuss concepts associated with mercantilism demonstrating key poli.pdfpetercoiffeur18
 
C++ Caesar Cipher project. Write your codes for the following functi.pdf
C++ Caesar Cipher project. Write your codes for the following functi.pdfC++ Caesar Cipher project. Write your codes for the following functi.pdf
C++ Caesar Cipher project. Write your codes for the following functi.pdfpetercoiffeur18
 
any idea#includeiostream using stdcout; using stdendl; .pdf
any idea#includeiostream using stdcout; using stdendl; .pdfany idea#includeiostream using stdcout; using stdendl; .pdf
any idea#includeiostream using stdcout; using stdendl; .pdfpetercoiffeur18
 
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdf
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdfa) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdf
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdfpetercoiffeur18
 
A radio station has a power output of 200 watts. What is the intensit.pdf
A radio station has a power output of 200 watts. What is the intensit.pdfA radio station has a power output of 200 watts. What is the intensit.pdf
A radio station has a power output of 200 watts. What is the intensit.pdfpetercoiffeur18
 
21) What are the fundamental particles of lepton and quarks How man.pdf
21) What are the fundamental particles of lepton and quarks How man.pdf21) What are the fundamental particles of lepton and quarks How man.pdf
21) What are the fundamental particles of lepton and quarks How man.pdfpetercoiffeur18
 
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdf
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdfCase 1-A Transition to SupervisorTristan came in on the ground fl.pdf
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdfpetercoiffeur18
 
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdf
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdfx , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdf
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdfpetercoiffeur18
 
Why would a cell want to express genes in an operon Why notSol.pdf
Why would a cell want to express genes in an operon Why notSol.pdfWhy would a cell want to express genes in an operon Why notSol.pdf
Why would a cell want to express genes in an operon Why notSol.pdfpetercoiffeur18
 
When discussing the epidemiology of virus infections, the CDC often .pdf
When discussing the epidemiology of virus infections, the CDC often .pdfWhen discussing the epidemiology of virus infections, the CDC often .pdf
When discussing the epidemiology of virus infections, the CDC often .pdfpetercoiffeur18
 
What relationship is there between gobalization and development.pdf
What relationship is there between gobalization and development.pdfWhat relationship is there between gobalization and development.pdf
What relationship is there between gobalization and development.pdfpetercoiffeur18
 
what is the number between 4.5 and 4.75 on the number linew.pdf
what is the number between 4.5 and 4.75 on the number linew.pdfwhat is the number between 4.5 and 4.75 on the number linew.pdf
what is the number between 4.5 and 4.75 on the number linew.pdfpetercoiffeur18
 
What are the five main goals for Operations Managers, and how do the.pdf
What are the five main goals for Operations Managers, and how do the.pdfWhat are the five main goals for Operations Managers, and how do the.pdf
What are the five main goals for Operations Managers, and how do the.pdfpetercoiffeur18
 

More from petercoiffeur18 (20)

John, a sociologist, will be focusing on how larger societal institu.pdf
John, a sociologist, will be focusing on how larger societal institu.pdfJohn, a sociologist, will be focusing on how larger societal institu.pdf
John, a sociologist, will be focusing on how larger societal institu.pdf
 
Implement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdfImplement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdf
 
In what ways do humans effect the environment Explain in 200 words.pdf
In what ways do humans effect the environment Explain in 200 words.pdfIn what ways do humans effect the environment Explain in 200 words.pdf
In what ways do humans effect the environment Explain in 200 words.pdf
 
I am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdfI am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdf
 
how internal resources and capabilities can be a source of sustainab.pdf
how internal resources and capabilities can be a source of sustainab.pdfhow internal resources and capabilities can be a source of sustainab.pdf
how internal resources and capabilities can be a source of sustainab.pdf
 
For an organism that is growing using glucose as the electron donor, .pdf
For an organism that is growing using glucose as the electron donor, .pdfFor an organism that is growing using glucose as the electron donor, .pdf
For an organism that is growing using glucose as the electron donor, .pdf
 
Exercise 5.6.28. For each of the following descriptions of a function.pdf
Exercise 5.6.28. For each of the following descriptions of a function.pdfExercise 5.6.28. For each of the following descriptions of a function.pdf
Exercise 5.6.28. For each of the following descriptions of a function.pdf
 
Discuss concepts associated with mercantilism demonstrating key poli.pdf
Discuss concepts associated with mercantilism demonstrating key poli.pdfDiscuss concepts associated with mercantilism demonstrating key poli.pdf
Discuss concepts associated with mercantilism demonstrating key poli.pdf
 
C++ Caesar Cipher project. Write your codes for the following functi.pdf
C++ Caesar Cipher project. Write your codes for the following functi.pdfC++ Caesar Cipher project. Write your codes for the following functi.pdf
C++ Caesar Cipher project. Write your codes for the following functi.pdf
 
any idea#includeiostream using stdcout; using stdendl; .pdf
any idea#includeiostream using stdcout; using stdendl; .pdfany idea#includeiostream using stdcout; using stdendl; .pdf
any idea#includeiostream using stdcout; using stdendl; .pdf
 
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdf
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdfa) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdf
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdf
 
A radio station has a power output of 200 watts. What is the intensit.pdf
A radio station has a power output of 200 watts. What is the intensit.pdfA radio station has a power output of 200 watts. What is the intensit.pdf
A radio station has a power output of 200 watts. What is the intensit.pdf
 
21) What are the fundamental particles of lepton and quarks How man.pdf
21) What are the fundamental particles of lepton and quarks How man.pdf21) What are the fundamental particles of lepton and quarks How man.pdf
21) What are the fundamental particles of lepton and quarks How man.pdf
 
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdf
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdfCase 1-A Transition to SupervisorTristan came in on the ground fl.pdf
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdf
 
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdf
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdfx , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdf
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdf
 
Why would a cell want to express genes in an operon Why notSol.pdf
Why would a cell want to express genes in an operon Why notSol.pdfWhy would a cell want to express genes in an operon Why notSol.pdf
Why would a cell want to express genes in an operon Why notSol.pdf
 
When discussing the epidemiology of virus infections, the CDC often .pdf
When discussing the epidemiology of virus infections, the CDC often .pdfWhen discussing the epidemiology of virus infections, the CDC often .pdf
When discussing the epidemiology of virus infections, the CDC often .pdf
 
What relationship is there between gobalization and development.pdf
What relationship is there between gobalization and development.pdfWhat relationship is there between gobalization and development.pdf
What relationship is there between gobalization and development.pdf
 
what is the number between 4.5 and 4.75 on the number linew.pdf
what is the number between 4.5 and 4.75 on the number linew.pdfwhat is the number between 4.5 and 4.75 on the number linew.pdf
what is the number between 4.5 and 4.75 on the number linew.pdf
 
What are the five main goals for Operations Managers, and how do the.pdf
What are the five main goals for Operations Managers, and how do the.pdfWhat are the five main goals for Operations Managers, and how do the.pdf
What are the five main goals for Operations Managers, and how do the.pdf
 

Recently uploaded

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

i need a taking turn method for a player vs computer battleship game.pdf

  • 1. i need a taking turn method for a player vs computer battleship game in java. when a user slects on players board then computer should be able to pick one on the computer board. this should continue to repeat the order until the first one finds all the ship on their board first. Solution import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import java.io.*; import java.lang.Integer; import java.util.Vector; import java.net.*; public class Battleship extends JFrame { private static JButton ok = new JButton("OK"),//closes stats menu done =new JButton("Done");//closes options menu private static JFrame statistics= new JFrame("Statistics"),//holds stats options=new JFrame("Options");//holds opts private static JLabel data,//used for stats menu title;//used for options menu private static JPanel stats=new JPanel(),//used for stats menu opts,//used for options menu inputpanel;//for manually inputting ships private static Container b,c,d;//board and input panel private JPanel input;//input bar private static JMenuItem m,pvp,pvc,cvc;//menu items private static String[] cletters = {" ","A","B","C","D","E","F","G","H","I","J"}, //array of letters used for combo boxes cnumbers = {" ","1","2","3","4","5","6","7","8","9","10"}, //array of numbers used for combo boxes ships = {"Carrier","Battleship","Submarine","Destroyer", "Patrol Boat"},//strings used for ship combo box direction = {"Horizontal","Vertical"},//directions level={"Normal", "Ridiculously Hard"}, layout={"Manual","Automatic"}, colors={"Cyan", "Green", "Yellow", "Magenta", "Pink", "Red", "White"}, first={"Player 1", "Player 2", "Random"};//used for options private JComboBox cshi = new JComboBox(ships),//ships cdir = new JComboBox(direction);//directions private static JComboBox aiLevel=new JComboBox(level), shipLayout=new JComboBox(layout), shipColor=new JComboBox(colors), playsFirst=new JComboBox(first);//used //for options menu private JTextField mbar = new JTextField();//message bar private static int enemy=1, i,j,//counters length=5, you=0,
  • 2. prevcolor=0,//index of previous color prevFirst=0, prevLayout=0, prevLevel=0,//tracks changes in corresponding comboboxes ready=0, sindex=0,//stores index of array dindex=0;//direction private static Player players[]=new Player[2]; private static JButton deploy=new JButton("DEPLOY"); private static int w=0,a=0,s=0,t=0,e=0;//counters to track the use of all ships private static String[][] shiphit=new String[10][10]; private static String user,user2; private static Color[] color={Color.cyan,Color.green,Color.yellow,Color.magenta, Color.pink, Color.red, Color.white}; private static Object selectedValue=" ", gametype; private static BattleshipClient me; private static boolean gameover=false; public Battleship() { setTitle("Battleship"); setDefaultCloseOperation(EXIT_ON_CLOSE); setJMenuBar(createMenuBar()); setResizable(false); //gets user to input name user=JOptionPane.showInputDialog("Enter your name."); int dummy=0; while (((user==null)||(user.equals("")))&&(dummy<3)) { user=JOptionPane.showInputDialog("You have to input something."); if ((user!=null)&&(!user.equals(""))) dummy=4; else dummy++; } if (dummy==3) { JOptionPane.showMessageDialog(null,"Since you're having trouble inp" +"utting your name, I'll just call you stupid.","",JOptionPane.INFORMATION_MESSAGE); user="Stupid"; } players[you]=new Player (user); players[enemy]=new Player ("Computer"); b=getContentPane(); b.add(setBoard(you),BorderLayout.CENTER); c=getContentPane(); d = getContentPane(); inputpanel=shipinput(); d.add(inputpanel,BorderLayout.NORTH); pack(); setVisible(true); } public static boolean getGameOver() { return gameover; } public static void setGameOver(boolean b) { gameover=b; } //method to determine who plays first public void whoGoesFirst() { int x=0; if (playsFirst.getSelectedIndex()!=2) { if (playsFirst.getSelectedIndex()!=you) flipYou(); players[playsFirst.getSelectedIndex()].getTimer().start(); x=playsFirst.getSelectedIndex(); } else { int rand=(int)(Math.random()*2); JOptionPane.showMessageDialog(null,players[rand].getUser()+" will " +"go
  • 3. first.","",JOptionPane.PLAIN_MESSAGE); if (rand!=you) flipYou(); players[rand].getTimer().start(); x=rand; } if ((!players[x].getUser().equals("Computer"))||(!players[x].getUser().equals("CPU1"))||(!players [x].getUser().equals("CPU2"))) players[x].setMove(true); } //returns ship color, as selected by the user public static Color getColor() { return (color[shipColor.getSelectedIndex()]); } //asks if two players are playing on the same computer or over the web public static boolean isLocal() { if ((gametype==pvp)&&(selectedValue.equals("Local"))) return true; else return false; } public static void flipYou() { if (you==1) { you=0; enemy=1; } else { you=1; enemy=0; } } //determines whether or not is shipLayout is set to automatic public static boolean isAutoSet() { if (shipLayout.getSelectedIndex()==0) return false; else return true; } //variable that determines whether or not a carrier has been placed public static int getW() { return w; } //variable that determines whether or not a battleship has been placed public static int getA() { return a; } //variable that determines whether or not a submarine has been placed public static int getS() { return s; } //variable that determines whether or not a destroyer has been placed public static int getT() { return t; } //variable that determines whether or not a patrol boat has been placed public static int getE() { return e; } public static int getReady() { return ready; } public static JFrame getStatistics() { return statistics; } public static void setData(JLabel x) { data=x; } public static JLabel getData() { return data; } public static JPanel getStats() { return stats; } public static void setDeploy(boolean k) { deploy.setEnabled(k); } public static Player getPlayers(int x) { return players[x]; } public static String getDirection(int i) { return direction[i]; } public static String getCletters(int i) { return cletters[i]; } public static String getShips(int i) { return ships[i]; } public static String getCnumbers(int i) { return cnumbers[i]; } public static int getSIndex() { return sindex; } public static int getDIndex() { return dindex; } public static int getYou() { return you; } public static int getEnemy() { return enemy; } public static void
  • 4. setYou(int x) { you=x; } public static void setEnemy(int x) { enemy=x; } //creates Game menu and submenus public JMenuBar createMenuBar() { JMenu menu;//menu // create the menu bar JMenuBar menuBar = new JMenuBar(); // build the Game menu menu = new JMenu("Game"); menuBar.add(menu); m = new JMenu("New Game"); menu.add(m); //submenu of New Game GameListener stuff = new GameListener(); pvp = new JMenuItem("Player vs. Player"); pvp.addActionListener(stuff); m.add(pvp); pvc = new JMenuItem("Player vs. Computer"); pvc.addActionListener(stuff); m.add(pvc); cvc = new JMenuItem("Computer vs. Computer"); cvc.addActionListener(stuff); m.add(cvc); m = new JMenuItem("Rules"); m.addActionListener(new RulesListener()); menu.add(m); m = new JMenuItem("Statistics"); m.addActionListener(new StatsListener()); menu.add(m); m = new JMenuItem("Options"); m.addActionListener(new OptionsListener()); menu.add(m); m = new JMenuItem("Exit"); m.addActionListener(new ExitListener()); menu.add(m); return menuBar; } //creates panels that used to place ships public JPanel shipinput() { input= new JPanel(); mbar.setText("Select a ship, its front position and direction."); mbar.setFont(new Font("Courier New", Font.BOLD, 14)); mbar.setEditable(false); //input.add(mbar); cshi.setSelectedIndex(0); cshi.addActionListener(new ShipsListener()); TitledBorder title;//used for titles around combo boxes title = BorderFactory.createTitledBorder("Ships"); cshi.setBorder(title); input.add(cshi); cdir.setSelectedIndex(0); cdir.addActionListener(new DirectListener()); input.add(cdir); title = BorderFactory.createTitledBorder("Direction"); cdir.setBorder(title); deploy.setEnabled(false); deploy.addActionListener(new DeployListener()); input.add(deploy); return input; } //creates board for manual ship placement public JPanel setBoard(int n) { players[n].setMyBoard(new JPanel(new GridLayout(11,11)));//panel to store board JTextField k; for (i=0;i<11;i++) { for (j=0;j<11;j++) { if ((j!=0)&&(i!=0)) { players[n].getBboard(i-1,j-1).addActionListener(new BoardListener()); players[n].getMyBoard().add(players[n].getBboard(i-1,j-1)); } if (i==0) { if (j!=0) { //used to
  • 5. display row of numbers k= new JTextField(Battleship.getCnumbers(j)); k.setEditable(false); k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT); } else { //used to display column of numbers k= new JTextField(); k.setEditable(false); } players[n].getMyBoard().add(k); } else if (j==0) { k= new JTextField(Battleship.getCletters(i)); k.setEditable(false); k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT); players[n].getMyBoard().add(k); } } } return players[n].getMyBoard(); } //creates board and automatically places ship public JPanel autoBoard(int u,int t) { players[u].setGBoard(new JPanel(new GridLayout(11,11)));//panel to store board JTextField k; if (!players[u].getUser().equals("Unknown")) for (i=0;i<5;i++) { players[u].setBoats(i,players[u].getBoats(i).compinput(i,u)); } for (i=0;i<11;i++) { for (j=0;j<11;j++) { if ((j!=0)&&(i!=0)) { if ((players[u].getUser().equals("Computer"))||(isLocal())) { players[u].getBboard(i-1,j-1).addActionListener(new AttackListener()); } else if ((players[t].getUser().equals("Computer"))||(players[t].getUser().equals("CPU1"))||(players[t]. getUser().equals("CPU2"))||(players[t].getUser().equals("Unknown"))) { if (players[u].getHitOrMiss(i-1,j-1)) players[u].setBboard(i-1,j-1,getColor()); } else { players[u].getBboard(i-1,j-1).addActionListener(new InternetListener()); } players[u].getGBoard().add(players[u].getBboard(i- 1,j-1)); } if (i==0) { if (j!=0) { //used to display row of numbers k= new JTextField(Battleship.getCnumbers(j)); k.setEditable(false);
  • 6. k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT); } else { //used to display column of numbers k= new JTextField(); k.setEditable(false); } players[u].getGBoard().add(k); } else if (j==0) { k= new JTextField(Battleship.getCletters(i)); k.setEditable(false); k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT); players[u].getGBoard().add(k); } } } return players[u].getGBoard(); } //Listener for combo boxes used to layout ships private class ShipsListener implements ActionListener { public void actionPerformed(ActionEvent v) { sindex=cshi.getSelectedIndex(); if (players[you].getBoats(sindex)!=null) cdir.setSelectedIndex(players[you].getBoats(sindex).getDirect()); switch (sindex) { case 0: length=5; break; case 1: length=4; break; case 2: length=3; break; case 3: length=3; break; case 4: length=2; break; } if (players[you].getBoats(sindex) != null) { Ship boat=new Ship(ships[sindex],players[you].getBoats(sindex).getDirect() ,length,players[you].getBoats(sindex).getX(),players[you].getBoats(sindex).getY()); players[you].getBoats(sindex).clearship(); players[you].setBoats(sindex,boat); players[you].getBoats(sindex).placeship(); } } } //Listener for the Direction combo box private class DirectListener implements ActionListener { public void actionPerformed(ActionEvent v) { dindex = cdir.getSelectedIndex(); if (players[you].getBoats(sindex) != null) { Ship boat=new Ship(ships[sindex],dindex,players[you].getBoats(sindex).getLength(), players[you].getBoats(sindex).getX(),players[you].getBoats(sindex).getY()); players[you].getBoats(sindex).clearship(); players[you].setBoats(sindex,boat);
  • 7. players[you].getBoats(sindex).placeship(); } } } //Listener for the buttons on the board private class BoardListener implements ActionListener { public void actionPerformed(ActionEvent v) { if (ready==0) { if (players[you].getBoats(sindex)!=null) players[you].getBoats(sindex).clearship(); Object source = v.getSource(); outer: for (i=0;i<10;i++) { for (j=0;j<10;j++) { if (source==players[you].getBboard(i,j)) { switch (sindex) { case 0: { if (w==0) w++; } break; case 1: { if (a==0) a++; } break; case 2: { if (s==0) s++; } break; case 3: { if (t==0) t++; } break; case 4: { if (e==0) e++; } break; } players[you].setBoats(sindex,new Ship(ships[sindex],dindex,length,i,j)); break outer; } } } players[you].getBoats(sindex).placeship(); } } } //creates a panel that tells whose board is which private JPanel whoseBoard() { JPanel panel=new JPanel(new BorderLayout());
  • 8. panel.add(new JLabel(players[you].getUser()+"'s Board",SwingConstants.LEFT),BorderLayout.WEST); panel.add(new JLabel(players[enemy].getUser()+"'s Board",SwingConstants.RIGHT),BorderLayout.EAST); return panel; } //Listener for exit choice on Game menu private class ExitListener implements ActionListener { public void actionPerformed(ActionEvent e) { int r= JOptionPane.showConfirmDialog(null,"Are you sure you would l" +"ike to exit Battleship?", "Exit?", JOptionPane.YES_NO_OPTION); if (r==0) System.exit(0); } } //listener for New Game submenu private class GameListener implements ActionListener { public void actionPerformed(ActionEvent e) { int q= JOptionPane.showConfirmDialog(null,"Are you sure you would l" +"ike to start a new game?", "New Game?", JOptionPane.YES_NO_OPTION); if (q==0) { //resets variables b.removeAll(); c.removeAll(); d.removeAll(); you=0; enemy=1; ready=0; if (players[you].getTimer()!=null) if (players[you].getTimer().isRunning()) players[you].getTimer().stop(); if (players[enemy].getTimer()!=null) if (players[enemy].getTimer().isRunning()) players[enemy].getTimer().stop(); gametype = e.getSource(); if (gametype==pvp) { if (!selectedValue.equals("no server")) { String[] possibleValues = { "Local", "Online"}; selectedValue = JOptionPane.showInputDialog(null, "Choose one", "Input", JOptionPane.INFORMATION_MESSAGE, null, possibleValues, possibleValues[0]); } if (!players[you].getUser().equals("CPU1")) { if (players[you].getUser().equals("Stupid")) { int w=JOptionPane.showConfirmDialog(null,"Would you" +" like to try inputting your name again?","", JOptionPane.YES_NO_OPTION); if (w==JOptionPane.YES_OPTION) { user=JOptionPane.showInputDialog("Enter your name."); int dummy=0; while
  • 9. (((user==null)||(user.equals("")))&&(dummy<3)) { user=JOptionPane.showInputDialog("You have to input something."); if ((user!=null)&&(!user.equals(""))) dummy=4; else dummy++; } if (dummy==3) { JOptionPane.showMessageDialog(null,"Still a" +"cting stupid. Oh well, we'll run with it." ,"",JOptionPane.INFORMATION_MESSAGE); user="Stupid"; } else JOptionPane.showMessageDialog(null,"That wasn't" +" so hard now, was it?","YEAH!", JOptionPane.INFORMATION_MESSAGE); } } players[you]=new Player (players[you].getUser()); } else players[you]=new Player (user); if (selectedValue.equals("Online")) { players[enemy]=new Player ("Unknown"); if (!isAutoSet()) { b.add(setBoard(you),BorderLayout.CENTER); deploy.setEnabled(false); d.add(inputpanel,BorderLayout.NORTH); } else { b.add(autoBoard(you,enemy),BorderLayout.WEST); c.add(autoBoard(enemy,you),BorderLayout.EAST); ready=1; } } else { //gets user to input name if((players[enemy].getUser().equals("Computer"))||(players[enemy].getUser().equals("CPU2") )||(players[enemy].getUser().equals("Unknown"))) { user2=JOptionPane.showInputDialog("Enter your name."); while ((user2==null)||(user2.equals(""))) { user2=JOptionPane.showInputDialog("You have to input something."); }
  • 10. } else user2=players[enemy].getUser(); players[enemy]=new Player (user2); b.add(autoBoard(you,enemy),BorderLayout.WEST); c.add(autoBoard(enemy,you),BorderLayout.EAST); d.add(whoseBoard(),BorderLayout.NORTH); whoGoesFirst(); ready=1; } //ready=1; } else if (gametype==pvc)//Player vs Computer { if (!players[you].getUser().equals("CPU1")) { if (players[you].getUser().equals("Stupid")) { int w=JOptionPane.showConfirmDialog(null,"Would you" +" like to try inputting your name again?","", JOptionPane.YES_NO_OPTION); if (w==JOptionPane.YES_OPTION) { user=JOptionPane.showInputDialog("Enter your name."); int dummy=0; while (((user==null)||(user.equals("")))&&(dummy<3)) { user=JOptionPane.showInputDialog("You have to input something."); if ((user!=null)&&(!user.equals(""))) dummy=4; else dummy++; } if (dummy==3) { JOptionPane.showMessageDialog(null,"Still a" +"cting stupid. Oh well, we'll run with it." ,"",JOptionPane.INFORMATION_MESSAGE); user="Stupid"; } else JOptionPane.showMessageDialog(null,"That wasn't" +" so hard now, was it?","YEAH!", JOptionPane.INFORMATION_MESSAGE); } } players[you]=new Player (players[you].getUser()); } else players[you]=new Player (user); players[enemy]=new Player ("Computer"); if (!isAutoSet()) {
  • 11. b.add(setBoard(you),BorderLayout.CENTER); deploy.setEnabled(false); d.add(inputpanel,BorderLayout.NORTH); } else { b.add(autoBoard(you,enemy),BorderLayout.WEST); c.add(autoBoard(enemy,you),BorderLayout.EAST); whoGoesFirst (); } } else if (gametype==cvc)//Computer vs Computer { mbar.setText("Battleship Demo"); mbar.setEditable(false); d.add(mbar,BorderLayout.NORTH); players[you]=new Player ("CPU1"); players[enemy]=new Player ("CPU2"); b.add(autoBoard(you,enemy),BorderLayout.WEST); c.add(autoBoard(enemy,you),BorderLayout.EAST); whoGoesFirst(); } pack(); repaint(); } } } //Listener for Rules menu private class RulesListener implements ActionListener { public void actionPerformed(ActionEvent e) { } } //Listener for ok button in statistics menu private class OkListener implements ActionListener { public void actionPerformed(ActionEvent e) { statistics.dispose(); } } //Listener for Stats menu private class StatsListener implements ActionListener { // public void setup() { stats=new JPanel(); ok.addActionListener(new OkListener()); statistics.setSize(300,300); statistics.setResizable(false); statistics.getContentPane().add(ok,BorderLayout.SOUTH); //statistics.setLocation(700,200); } public void actionPerformed(ActionEvent e) { if (data==null) setup(); else stats.removeAll(); stats.setLayout(new GridLayout(6,3)); data=new JLabel(""); stats.add(data); data=new JLabel("Player 1",SwingConstants.CENTER); stats.add(data); data=new JLabel("Player 2",SwingConstants.CENTER); stats.add(data); data=new JLabel("Names"); stats.add(data); if (you == 0) {
  • 12. data=new JLabel(players[you].getUser(),SwingConstants.CENTER); stats.add(data); data=new JLabel(players[enemy].getUser(),SwingConstants.CENTER); stats.add(data); data=new JLabel("Shots Taken"); stats.add(data); data=new JLabel(Integer.toString(players[you].getShots()),SwingConstants.CENTER); stats.add(data); data=new JLabel(Integer.toString(players[enemy].getShots()),SwingConstants.CENTER); stats.add(data); data=new JLabel("Hits"); stats.add(data); data=new JLabel(Integer.toString(players[you].getHits()),SwingConstants.CENTER); stats.add(data); data=new JLabel(Integer.toString(players[enemy].getHits()),SwingConstants.CENTER); stats.add(data); data=new JLabel("Shot Accuracy"); stats.add(data); data=new JLabel(players[you].getAcc(),SwingConstants.CENTER); stats.add(data); data=new JLabel(players[enemy].getAcc(),SwingConstants.CENTER); stats.add(data); data=new JLabel("Ships Left"); stats.add(data); data=new JLabel(Integer.toString(players[you].getShipsLeft()),SwingConstants.CENTER); stats.add(data); data=new JLabel(Integer.toString(players[enemy].getShipsLeft()),SwingConstants.CENTER); stats.add(data); } else { data=new JLabel(players[enemy].getUser(),SwingConstants.CENTER); stats.add(data); data=new JLabel(players[you].getUser(),SwingConstants.CENTER); stats.add(data); data=new JLabel("Shots Taken"); stats.add(data); data=new JLabel(Integer.toString(players[enemy].getShots()),SwingConstants.CENTER); stats.add(data); data=new JLabel(Integer.toString(players[you].getShots()),SwingConstants.CENTER); stats.add(data); data=new JLabel("Hits"); stats.add(data); data=new JLabel(Integer.toString(players[enemy].getHits()),SwingConstants.CENTER); stats.add(data); data=new
  • 13. JLabel(Integer.toString(players[you].getHits()),SwingConstants.CENTER); stats.add(data); data=new JLabel("Shot Accuracy"); stats.add(data); data=new JLabel(players[enemy].getAcc(),SwingConstants.CENTER); stats.add(data); data=new JLabel(players[you].getAcc(),SwingConstants.CENTER); stats.add(data); data=new JLabel("Ships Left"); stats.add(data); data=new JLabel(Integer.toString(players[enemy].getShipsLeft()),SwingConstants.CENTER); stats.add(data); data=new JLabel(Integer.toString(players[you].getShipsLeft()),SwingConstants.CENTER); stats.add(data); } statistics.getContentPane().add(stats); statistics.pack(); statistics.setVisible(true); } } //Listener for Deploy Button private class DeployListener implements ActionListener { public void actionPerformed(ActionEvent v) { int r= JOptionPane.showConfirmDialog(null,"Are you sure you would l" +"ike to deploy your ships?", "Deploy Ships?", JOptionPane.YES_NO_OPTION); if (r==0) { w=0; a=0; s=0; t=0; e=0; d.remove(input); b.add(players[you].getMyBoard(),BorderLayout.WEST); ready=1; c.add(autoBoard(enemy,you),BorderLayout.EAST); d.add(new JPanel(),BorderLayout.CENTER); if (!selectedValue.equals("Online")) whoGoesFirst(); pack(); repaint(); } } } //Listener for Options menu public class OptionsListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (opts==null) setup(); else options.setVisible(true); } public void setup() { opts=new JPanel(new GridLayout(4,2)); title=new JLabel("Computer AI"); opts.add(title); aiLevel.setSelectedIndex(0); opts.add(aiLevel); title=new JLabel("Ship Layout"); opts.add(title); shipLayout.setSelectedIndex(0); opts.add(shipLayout); title=new JLabel("Ship Color"); opts.add(title); shipColor.addActionListener(new SColorListener());
  • 14. shipColor.setSelectedIndex(0); opts.add(shipColor); title=new JLabel("Who Plays First?"); opts.add(title); playsFirst.setSelectedIndex(0); opts.add(playsFirst); options.getContentPane().add(opts,BorderLayout.CENTER); //options.setSize(600,800); options.setResizable(false); done.addActionListener(new DoneListener()); options.getContentPane().add(done,BorderLayout.SOUTH); options.setLocation(200,200); options.pack(); options.setVisible(true); } //Listener for the Colors combo box private class SColorListener implements ActionListener { public void actionPerformed(ActionEvent v) { for (i=0;i<10;i++) for (j=0;j<10;j++) { if (players[you].getBboard(i,j).getBackground()==color[prevcolor]) players[you].setBboard(i,j,color[shipColor.getSelectedIndex()]); if (players[enemy].getBboard(i,j).getBackground() ==color[prevcolor]) players[enemy].setBboard(i,j,color[shipColor.getSelectedIndex()]); } prevcolor=shipColor.getSelectedIndex(); } } //Listener for ok button in statistics menu private class DoneListener implements ActionListener { public void actionPerformed(ActionEvent e) { if ((shipLayout.getSelectedIndex()!=prevLayout)|| (aiLevel.getSelectedIndex()!=prevLevel)|| (playsFirst.getSelectedIndex()!=prevFirst)) { JOptionPane.showMessageDialog(null,"Changes will take"+ " place at the start of a new game.","" ,JOptionPane.PLAIN_MESSAGE); if (shipLayout.getSelectedIndex()!=prevLayout) prevLayout=shipLayout.getSelectedIndex(); if (playsFirst.getSelectedIndex()!=prevFirst) prevFirst=playsFirst.getSelectedIndex(); if (aiLevel.getSelectedIndex()!=prevLevel) prevLevel=aiLevel.getSelectedIndex(); } options.dispose(); } } } public static BattleshipClient getClient() { return me; } public static void main(String[] args){ Battleship gui= new Battleship();
  • 15. while (gui.isActive()) { while (selectedValue.equals(" ")) { } System.out.println("xenophobia"); System.out.println("Object = "+selectedValue); if (selectedValue.equals("Online")) { selectedValue=" "; while (ready!=1) { } try { me=new BattleshipClient(); if (!me.getServerName().equals("invalid")) { me.sendShips(); while (!gameover) { if (!players[you].getMove()) { try { me.listen(); } catch (IOException e){ System.out.println("Aw naw."); } } while (players[you].getMove()) { } me.results(); } } else { b.removeAll(); c.removeAll(); d.removeAll(); players[you]=new Player (user); players[enemy]=new Player ("Computer"); b.add(gui.setBoard(you),BorderLayout.CENTER); inputpanel=gui.shipinput(); d.add(inputpanel,BorderLayout.NORTH); gui.pack(); gui.repaint(); } } catch (IOException e) { System.out.println("You Suck"); } } } //System.out.println("okay"); } }