Question

The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the o...

  1. The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the other opponent cannot see them. In order to attack, each player takes turns calling out coordinates on a grid. If the attacker calls out a coordinate that hits their opponent's ship, they must call out, "Hit." You are going to be developing a computer program to mimic this game. Use the Gridlayout that is six columns by six rows. Randomly make one row or one column all ones. The other cells will be 0. The user should not see these values. When a user selects a cell, expose the value. The game is over when the user correctly selects all of the cells with 1s in them. Call this class Battleship.java.
  2. Tic-Tac-Toe is a game played on a grid that contains three rows by three columns. When a player gets three of their values across, down, or diagonal, they have won the game. Create a java version of this game by using Gridlayout that is constructed with three columns and three rows. The user will go first. When the user selects a cell, put an "x" in that cell. Next, randomly add a 0 to a cell to mock the computer playing. Call this class TicTacToe.java.
  3. Place the following files in a folder (Battleship.java and TicTacToe.java), and label it "Lesson 7." Zip the folder as described in the Syllabus.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

TicTacToe.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.JOptionPane;
public class TicTacToe extends JFrame
{
   JButton[][] buttons = new JButton[3][3];
   JFrame frame = new JFrame("TicTacToe"); //Global frame and grid button variables
   JButton reset = new JButton("Reset"); //Create reset button for game
   JOptionPane turn;
   int moveCounter = 9;
   boolean gameWon = false;
   int WhoseTurn = 1;
   public TicTacToe() //Tic tac default constructor which adds and dimensions Jframe
   {
       super();
       frame.setSize(350, 355);
       frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //Setting dimension of Jframe and setting parameters
       frame.setVisible(true);
       frame.setResizable(false);
       JButton[][] buttons = new JButton[3][3];
       JFrame frame = new JFrame("TicTacToe"); //Global frame and grid button variables
       JButton reset = new JButton("Reset"); //Create reset button for game
       JOptionPane turn;
   }
   private void checkWin(int row, int col)
   {
       try {
           if (buttons[0][2].getText()==buttons[1][2].getText()&& buttons[1][2].getText()==buttons[2][2].getText()&& buttons[2][2].getText()==buttons[0][2].getText()&& buttons[1][2].getText()!="")
           {
               gameWon = true;
               WhoseTurn = 0;
               System.out.println(buttons[1][2].getText()+ " wins!!!");
               JOptionPane.showMessageDialog(frame, buttons[1][2].getText()+ " wins!!!");
           }
           if (buttons[0][1].getText()==buttons[1][1].getText()&& buttons[1][1].getText()==buttons[2][1].getText()&& buttons[2][1].getText()==buttons[0][1].getText()&& buttons[1][1].getText()!="")
           {
               gameWon = true;
               WhoseTurn = 0;
               System.out.println(buttons[1][1].getText()+ " wins!!!");
               JOptionPane.showMessageDialog(frame, buttons[1][1].getText()+ " wins!!!");
           }
           if (buttons[0][0].getText()==buttons[1][0].getText()&& buttons[1][0].getText()==buttons[2][0].getText()&& buttons[2][0].getText()==buttons[0][0].getText()&& buttons[1][0].getText()!="")
           {
               gameWon = true;
               WhoseTurn = 0;
               System.out.println(buttons[1][0].getText()+ " wins!!!");
               JOptionPane.showMessageDialog(frame, buttons[1][0].getText()+ " wins!!!");
           }
           if (buttons[2][0].getText()==buttons[2][1].getText()&& buttons[2][1].getText()==buttons[2][2].getText()&& buttons[2][2].getText()==buttons[2][0].getText()&& buttons[2][1].getText()!="")
           {
               gameWon = true;
               WhoseTurn = 0;
               System.out.println(buttons[2][1].getText()+ " wins!!!");
               JOptionPane.showMessageDialog(frame, buttons[2][1].getText()+ " wins!!!");
           }
           if (buttons[1][0].getText()==buttons[1][1].getText()&& buttons[1][1].getText()==buttons[1][2].getText()&& buttons[1][2].getText()==buttons[1][0].getText()&& buttons[1][1].getText()!="")
           {
               gameWon = true;
               WhoseTurn = 0;
               System.out.println(buttons[1][1].getText()+ " wins!!!");
               JOptionPane.showMessageDialog(frame, buttons[1][1].getText()+ " wins!!!");
           }
           if (buttons[0][0].getText()==buttons[0][1].getText()&& buttons[0][1].getText()==buttons[0][2].getText()&& buttons[0][2].getText()==buttons[0][0].getText()&& buttons[0][1].getText()!="")
           {
               gameWon = true;
               WhoseTurn = 0;
               System.out.println(buttons[0][1].getText()+ " wins!!!");
               JOptionPane.showMessageDialog(frame, buttons[0][1].getText()+ " wins!!!");
           }
           if (buttons[0][0].getText()==buttons[1][1].getText()&& buttons[1][1].getText()==buttons[2][2].getText()&& buttons[2][2].getText()==buttons[0][0].getText()&& buttons[1][1].getText()!="")
           {
               gameWon = true;
               WhoseTurn = 0;
               System.out.println(buttons[1][1].getText()+ " wins!!!");
               JOptionPane.showMessageDialog(frame, buttons[1][1].getText()+ " wins!!!");
           }
           if (buttons[0][2].getText()==buttons[1][1].getText()&& buttons[1][1].getText()==buttons[2][0].getText()&& buttons[2][0].getText()==buttons[0][2].getText()&& buttons[1][1].getText()!="")
           {
               gameWon = true;
               WhoseTurn = 0;
               System.out.println(buttons[1][1].getText()+ " wins!!!");
               JOptionPane.showMessageDialog(frame, buttons[1][1].getText()+ " wins!!!");
           }
       }catch(Exception e) {
           gameWon = true;
           WhoseTurn = 0;
           System.out.println("Stalemate");
           JOptionPane.showMessageDialog(frame, "Stalemate");
       }
   }
   private void compTurn(int count)
   {
       int randomMove=count;
       Random num = new Random();
       randomMove = num.nextInt(randomMove)+1;
       while(gameWon ==false & WhoseTurn ==2)
       {
           for(int i = 0; i < 3; i++) //Create grid of buttons for tic tac toe game
           {
               for(int j = 0; j < 3; j++)
               {
                   if(buttons[i][j].isEnabled()==true)
                   {
                       randomMove--;
                       if(randomMove==0 )
                       {
                           buttons[i][j].setText("O");
                           buttons[i][j].setEnabled(false);
                           moveCounter--;
                           checkWin(i, j);
                           WhoseTurn = 1;
                       }
                   }
               }
           }
       }
   }
   private void initialize() //Initialize tic tac toe game board
   {
       JPanel mainPanel = new JPanel(new BorderLayout()); //create main panel container to put layer others on top
       JPanel menu = new JPanel(new BorderLayout());
       JPanel game = new JPanel(new GridLayout(3,3)); //Create two more panels with layouts for buttons
       frame.add(mainPanel); //add main container panel to frame
       mainPanel.setPreferredSize(new Dimension(325,425));
       menu.setPreferredSize(new Dimension(300,50)); //Setting dimensions of panels
       game.setPreferredSize(new Dimension(300,300));
       mainPanel.add(menu, BorderLayout.NORTH); //Add two panels to the main container panel
       mainPanel.add(game, BorderLayout.SOUTH);
       //Add both start/reset buttons to menu container panel
       menu.add(reset, BorderLayout.NORTH);
       reset.addActionListener(new myActionListener());
       for(int i = 0; i < 3; i++) //Create grid of buttons for tic tac toe game
       {
           for(int j = 0; j < 3; j++)
           {
               buttons[i][j] = new JButton(); //Instantiating buttons
               buttons[i][j].setText("");
               buttons[i][j].setVisible(true);
               game.add(buttons[i][j]);
               buttons[i][j].addActionListener(new myActionListener()); //Adding response event to buttons
           }
       }
   }
   private class myActionListener implements ActionListener
   { //Implementing action listener for buttons
       public void actionPerformed(ActionEvent a)
       {
           //Display X's or O's on the buttons
           if(gameWon == false)
           {
               if(a.getSource() == buttons[0][0]) //Checking which button is pressed
               {
                   buttons[0][0].setText("X");
                   buttons[0][0].setEnabled(false);
                   WhoseTurn = 2;
                   moveCounter--;
                   compTurn(moveCounter);
                   checkWin(0,0);
               }
               else if(a.getSource() == buttons[0][1])
               {
                   buttons[0][1].setText("X");
                   buttons[0][1].setEnabled(false);
                   WhoseTurn = 2;
                   moveCounter--;
                   compTurn(moveCounter);
                   checkWin(0,1);
               }
               else if(a.getSource() == buttons[1][0])
               {
                   buttons[1][0].setText("X");
                   buttons[1][0].setEnabled(false);
                   WhoseTurn = 2;
                   moveCounter--;
                   compTurn(moveCounter);
                   checkWin(1,0);
               }
               else if(a.getSource() == buttons[1][1])
               {
                   buttons[1][1].setText("X");
                   buttons[1][1].setEnabled(false);
                   WhoseTurn = 2;
                   moveCounter--;
                   compTurn(moveCounter);
                   checkWin(1,1);
               }
               else if(a.getSource() == buttons[1][2])
               {
                   buttons[1][2].setText("X");
                   buttons[1][2].setEnabled(false);
                   WhoseTurn = 2;
                   moveCounter--;
                   compTurn(moveCounter);
                   checkWin(1,2);
               }
               else if(a.getSource() == buttons[2][2])
               {
                   buttons[2][2].setText("X");
                   buttons[2][2].setEnabled(false);
                   WhoseTurn = 2;
                   moveCounter--;
                   compTurn(moveCounter);
                   checkWin(2,2);
               }
               else if(a.getSource() == buttons[0][2])
               {
                   buttons[0][2].setText("X");
                   buttons[0][2].setEnabled(false);
                   WhoseTurn = 2;
                   moveCounter--;
                   compTurn(moveCounter);
                   checkWin(0,2);
               }
               else if(a.getSource() == buttons[2][1])
               {
                   buttons[2][1].setText("X");
                   buttons[2][1].setEnabled(false);
                   WhoseTurn = 2;
                   moveCounter--;
                   compTurn(moveCounter);
                   checkWin(2,1);
               }
               else if(a.getSource() == buttons[2][0])
               {
                   buttons[2][0].setText("X");
                   buttons[2][0].setEnabled(false);
                   WhoseTurn = 2;
                   moveCounter--;
                   compTurn(moveCounter);
                   checkWin(2,0);
               }
           }
           if(a.getSource() == reset)
           {
               for(int i = 0; i < 3; i++)
               {
                   for(int j = 0; j < 3; j++)
                   {
                       gameWon = false;
                       buttons[i][j].setText("");
                       buttons[i][j].setEnabled(true);
                       moveCounter = 9;
                       WhoseTurn = 1;
                   }
               }
           }
       }
   }
   public static void main(String[] args)
   {
       TicTacToe game = new TicTacToe(); //main method and instantiating tic tac object and calling initialize function
       game.initialize();
   }
}

Output:

TicTacToe Reset

Battleship.java:


import java.util.Random;
import java.util.Scanner;
public class Battleship {
   public static void main(String[] args) {
       Random rand = new Random();
       Scanner sc=new Scanner(System.in);
       int row,col;
       int[][] grid=new int[6][6];
       int correct_count=0;
       char ch;
       for(int i=0;i<6;i++) {
           for(int j=0;j<6;j++) {
               grid[i][j]=0;
           }
       }
       row = rand.nextInt(5) + 1;
       for(int i=0;i<6;i++) {
           grid[row][i]=1;
       }
       for(int i=0;i<6;i++) {
           for(int j=0;j<6;j++) {
               System.out.print(grid[i][j]+" ");
           }
           System.out.println();
       }
     
       while(correct_count<6) {
           System.out.print("Enter row number: ");
           row=sc.nextInt();
           System.out.print("Enter column number: ");
           col=sc.nextInt();
           if(grid[row][col]==1) {
               correct_count++;
           }
           if(correct_count!=6) {
               System.out.print("Do you want to continue(Y/N): ");
               ch=sc.next().charAt(0);
               ch=Character.toUpperCase(ch);
               if(ch=='N') {
                   break;
               }
            
           }
        
       }
       if(correct_count==6) {
           System.out.println("You win!!!!Congrats");
       }
       else {
           System.out.println("You Lost!!!!");
       }
   }
}

Output:

Enter row number: 3 Enter column number 0 Do you want to continue (Y/N) : y Enter row number: 3 Enter column number 1 Do you

Add a comment
Know the answer?
Add Answer to:
The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the o...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The game Battleship is played on a grid board. Each opponent has multiple ships that are...

    The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the other opponent cannot see them. In order to attack, each player takes turns calling out coordinates on a grid. If the attacker calls out a coordinate that hits their opponent's ship, they must call out, "Hit." You are going to be developing a computer program to mimic this game. Use the Gridlayout that is six columns by six...

  • For your Project, you will develop a simple battleship game. Battleship is a guessing game for...

    For your Project, you will develop a simple battleship game. Battleship is a guessing game for two players. It is played on four grids. Two grids (one for each player) are used to mark each players' fleets of ships (including battleships). The locations of the fleet (these first two grids) are concealed from the other player so that they do not know the locations of the opponent’s ships. Players alternate turns by ‘firing torpedoes’ at the other player's ships. The...

  • Assignment - Battleship In 1967, Hasbro toys introduced a childrens game named “Battleship”. In the next...

    Assignment - Battleship In 1967, Hasbro toys introduced a childrens game named “Battleship”. In the next two assignments you will be creating a one-player version of the game. The game is extremely simple. Each player arranges a fleet of ships in a grid. The grid is hidden from the opponent. Here is an ASCII representation of a 10x10 grid. The ‘X’s represent ships, the ‘~’s represent empty water. There are three ships in the picture: A vertical ship with a...

  • Connect 4 is a 2 player game where each player has a set of colored tokens...

    Connect 4 is a 2 player game where each player has a set of colored tokens (red or yellow). Players take turns during which they place a single token into one of the columns of an n by m grid (where n is the number of rows and m is the number of columns. They place their token into a slot at the top of the column and it falls into the lowest unoccupied slot in that column. A player...

  • Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game....

    Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game. The objective of this project is to demonstrate your understanding of various programming concepts including Object Oriented Programming (OOP) and design. Tic Tac Toe is a two player game. In your implementation one opponent will be a human player and the other a computer player. ? The game is played on a 3 x 3 game board. ? The first player is known as...

  • C#: Implement a multiplayer Battleship game with AI The rules are the same as before. The...

    C#: Implement a multiplayer Battleship game with AI The rules are the same as before. The game is played on an NxN grid. Each player will place a specified collection of ships: The ships will vary in length (size) from 2 to 5; There can be any number or any size ship. There may be no ships of a particular size; EXCEPT the battleship – which there will always be 1 and only 1. Player order will be random but...

  • Instructions This assignment has to be completed by each student individually. NO COLLABORATION I...

    I need help creating a class diagram for this please: I am not sure what more you want? it has 2 classes at least Connect4 and Connect4TextConsole. Instructions This assignment has to be completed by each student individually. NO COLLABORATION IS ALLOWED Submit YourASURitelD ProjectDeliverable2.zip compressed folder should contain the following files following This the 1. 2. Connect4.java 〔Game Logic Module) Connect4TextConsole.java (Console-based Ul to test the gamel 3. JavaDoc documentation files index.html and all other supporting files such as.cs5...

  • Enhance and correct a Tic Tac Toe game. The game is intended to be played against...

    Enhance and correct a Tic Tac Toe game. The game is intended to be played against a computer. The object TicTacToeBoard is initialized to indicate if the computer is the player 1 or player 2. Your task is to allow turns between the player and computer and to determine if a winner exists. Keyboard input implies using the Scanner object. Review Section 7.7 in the textbook. Ideally, do 1 task at a time and test the results. The tasks are...

  • Objective: Write a program that implements the Game of Life cellular automata system invented by John...

    Objective: Write a program that implements the Game of Life cellular automata system invented by John Conway. 1. Create two game grids of size at least 50x50. These grid cells can be either Boolean or integer. In the following, I’ll refer to these as gridOne and gridTwo. 2. Set all cells in both grids to false. 3. Start by initializing gridOne. Allow the user to specify two different ways of initializing the grid: 1) by specifying a pattern file to...

  • Using C programming REQUIREMENTS: This program is a letter guessing game where a simple Al opponent...

    Using C programming REQUIREMENTS: This program is a letter guessing game where a simple Al opponent generates a secret letter for the user to guess. The user must be able to take turns guessing the secret letter, with the Al responding to the user's guesses. After successfully guessing, the user must be allowed to play again. The Al must count how many turns the user has taken. Here is an example of a game in progress where the human user...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT