Question

Code in JAVA You are asked to implement “Connect 4” which is a two player game....

Code in JAVA

You are asked to implement “Connect 4” which is a two player game. The game will be demonstrated in class. The game is played on a 6x7 grid, and is similar to tic-tac-toe, except that instead of getting three in a row, you must get four in a row. To take your turn, you choose a column, and slide a checker of your color into the column that you choose. The checker drops into the slot, falling either all the way to the bottom, or resting on top of the highest checker already in that column. You may not place a checker into a column that is full. You win when you create a row, column or diagonal of four in a row of your color.

Your project should have at least three classes: Cell, GameBoard, Connect4Game and GameDriver.

The Cell class will represent a single location in the game board. It should contain at least the following:

Instance variable:

  • A private variable that indicates whether the location on the game board is empty, holds a red checker, or holds a blue checker. The variable should be of an enumerated type called State, that you define.

Methods:

  • A constructor that takes one argument of type State. This constructor should use its parameter to set the instance variable.
  • An public accessor (getter) method for the instance variable.
  • A public mutator (setter) method for the instance variable.

The GameBoard class holds the information about the entire game board:

Instance variable:

  • A private two-dimensional array of cells.

Methods:

  • A no-argument constructor, that does the necessary initialization of StdDraw. The constructor should initialize the game board to be a 6 by 7 array of Cells, all of which are set to be empty. The constructor should also use StdDraw.setCanvasSize(), StdDraw.setXscale(), and StdDraw.setYscale(). You may choose the default size on the screen of the game board.
  • A constructor with one argument, which is the number of pixels in the height of the game board. This constructor should also do the same necessary initialization as the no-argument constructor.
  • A public boolean method called columnFull that takes a column number as an argument, and returns true if the column is full and false if the column still has space.
  • A public boolean method called addChecker that takes a column and a State, and adds that color checker to the game board. The method returns false if the column was already full, and true otherwise.
  • A public void method called drawGameBoard that displays the game board in its current state. The board should basically look like a Connect 4 game board, but you're free to be artistic.
  • A public boolean method called GameOver that returns true of the game is finished. It takes as parameters the row and column position of the last checker that has been played, and checks to see if there are four in a row of that same color going vertically, horizontally or diagonally through that position.

The class Connect4Game should have

  • an instance variable of type GameBoard
  • A no-argument constructor that does all necessary initialization
  • A public void method called playGame that starts interaction with users, manages turn-taking, gets input from users via the keyboard and console, and controls display of the game board. When taking input from the user, check for validity of the input, and continue asking until valid input is given. Create private methods within this class to divide up the work in an organized way and makes your code easier to read.

The class GameDriver should have a main method that creates a Connect4Game object and calls its playGame method.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

Program code screen shot:

Sample Output:

Program code to copy:

// enum to set the state of the checker
enum State
{
   emptyChecker, redChecker, blueChecker
};

// Cell.java
public class Cell
{
   // instance variable
   State checker;

   // Constructor to set the cell
   // State enum variable
   public Cell(State checkerColor)
   {
       this.checker = checkerColor;
   }

   // getter (accessor) method for the instance variable.
   public State getChecker()
   {
       return checker;
   }

   // setter (mutator) method for the instance variable
   public void setChecker(State checker)
   {
       this.checker = checker;
   }
}


// GameBoard.java
import edu.princeton.cs.algs4.StdDraw;

public class GameBoard
{
   // class instance variable
   Cell cells[][];
   int rowNum;

   // constructor
   public GameBoard()
   {
       cells = new Cell[6][7];
       initializeArray();
       initializeStdDraw(500);
   }

   // parameterized constructor
   public GameBoard(int height)
   {
       cells = new Cell[6][7];
       initializeArray();
       initializeStdDraw(height);
   }

   // initializeStdDraw() to initialize the draw panel
   private void initializeStdDraw(int height)
   {
       StdDraw.setCanvasSize(height, height);
       StdDraw.setXscale(0, 7);
       StdDraw.setYscale(0, 6);
       StdDraw.clear(StdDraw.ORANGE);
   }

   // initializeArray() to initialize the array
   private void initializeArray()
   {
       for (int i = 0; i < cells.length; i++)
       {
           for (int j = 0; j < cells[0].length; j++)
           {
               cells[i][j] = new Cell(State.emptyChecker);
           }
       }
   }

   // getChecker() to get the cell of the checker
   public Cell getChecker(int row, int column)
   {
       if ((row >= 0 && row < cells.length) &&
(column >= 0 && column < cells[0].length))
           return cells[row][column];
       else
           return null;
   }

   // getRowToInsert() to get the row to insert
   public int getRowToInsert(int column)
   {
       int row = cells.length - 1;
       if (!columnFull(column))
       {
           for (int i = 0; i < cells.length; i++)
           {
               if (cells[i][column].getChecker() == State.emptyChecker)
               {
                   row = i;
                   break;
               }
           }
           return row;
       }
       else
       {
           return row;
       }
   }

   // getRowNumber() to get the row number
   public int getRowNumber()
   {
       return rowNum;
   }

   // columnFull() to check whether the column is full or not
   public boolean columnFull(int columnNum)
   {
       if (columnNum < 0 || columnNum > cells[0].length)
       {
           System.out.println("Invalid column number");
           return false;
       }
       else
       {
           for (int i = 0; i < cells.length; i++)
           {
               if (cells[i][columnNum].getChecker() == State.emptyChecker)
                   return false;
           }
           return true;
       }
   }

   // addChecker() to add the checker
   public boolean addChecker(int column, State checkerColor)
   {
       if (columnFull(column))
           return false;
       else
       {
           rowNum = getRowToInsert(column);
           if (cells[rowNum][column].getChecker() == State.emptyChecker)
           {
               cells[rowNum][column].setChecker(checkerColor);
               return true;
           }
           else
           {
               return false;
           }
       }
   }

   // drawGameBoard() to display the board
   public void drawGameBoard()
   {
       for (int i = 0; i < 6; i++)
       {
           for (int j = 0; j < 7; j++)
           {
               if (cells[i][j].getChecker() == State.blueChecker)
                   StdDraw.setPenColor(StdDraw.BLUE);
               else if (cells[i][j].getChecker() == State.redChecker)
                   StdDraw.setPenColor(StdDraw.RED);
               else
                   StdDraw.setPenColor(StdDraw.WHITE);
               StdDraw.filledCircle(j + 0.5, i + 0.5, 0.4);
           }
       }
   }

   // method to check row winners
   private boolean getRowWinners(int row, int column)
   {

       for (int col = 0; col < cells[row].length - 3; col++)
           if (cells[row][col].getChecker() != State.emptyChecker
                   && cells[row][col].getChecker() == cells[row][column].getChecker()
                   && cells[row][col + 1].getChecker() == cells[row][column].getChecker()
                   && cells[row][col + 2].getChecker() == cells[row][column].getChecker()
                   && cells[row][col + 3].getChecker() == cells[row][column].getChecker())
           {
               return true;
           }
       return false;
   }

   // method to check column winners
   private boolean getColumnsWinners(int row, int column)
   {

       for (int i = 0; i < cells.length - 3; i++)
           if (cells[i][column].getChecker() != State.emptyChecker
                   && cells[i][column].getChecker() == cells[row][column].getChecker()
                   && cells[i + 1][column].getChecker() == cells[row][column].getChecker()
                   && cells[i + 2][column].getChecker() == cells[row][column].getChecker()
                   && cells[i + 3][column].getChecker() == cells[row][column].getChecker())
           {
               return true;
           }
       return false;
   }

   // diagonal winner if there is a matching of four disks with same color
   // diagonally.
   private boolean getDiagonalWinners(int row, int column)
   {
       for (int i = 0; i < cells.length - 3; i++)
       {
           for (int j = 0; j < cells[i].length - 3; j++)
           {
               if (cells[i][j].getChecker() != State.emptyChecker
                       && cells[i][j].getChecker() == cells[i + 1][j + 1].getChecker()
                       && cells[i][j].getChecker() == cells[i + 2][j + 2].getChecker()
                       && cells[i][j].getChecker() == cells[i + 3][j + 3].getChecker())
               {
                   return true;
               }
           }
       }
       // Check for win diagonally, from top right
       for (int i = 0; i < cells.length - 3; i++)
       {
           for (int j = 3; j < cells[i].length; j++)
           {
               if (cells[i][j].getChecker() != State.emptyChecker
                       && cells[i][j].getChecker() == cells[i + 1][j - 1].getChecker()
                       && cells[i][j].getChecker() == cells[i][j - 2].getChecker()
                       && cells[i][j].getChecker() == cells[i + 3][j - 3].getChecker())
               {
                   return true;
               }
           }
       }

       // if not return blank
       return false;
   }

   // GameOver() to check for the winner
   public boolean GameOver(int row, int column)
   {      
       if (getRowWinners(row, column))
           return true;
       if (getColumnsWinners(row, column))
           return true;
       if (getDiagonalWinners(row, column))
           return true;
       return false;
   }

   // isFull() to check whether the board is full or not
   public boolean isFull()
   {
       for (int i = 0; i < cells.length; i++)
       {
           for (int j = 0; j < cells[0].length; j++)
               if (cells[i][j].getChecker() == State.emptyChecker)
                   return false;
       }
       return true;
   }
}

  

// Connect4Game.java
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class Connect4Game
{
   // instance variable
   GameBoard gb;

   // constructor
   public Connect4Game()
   {
       gb = new GameBoard();
   }

   // getColumnNumberToInsert() to get the column number to insert
   private int getColumnNumberToInsert(String player)
   {
       int column = 0;
       StdOut.print(player + "\nChoose column (1-7) for a disk: ");
       column = Integer.parseInt(StdIn.readLine());
       return column;
   }

   // isValidColumnNumber(): To check the valid column number
   public boolean isValidColumnNumber(int column)
   {
       // check for validity of the input column number
       if (column < 1 || column > 7)
       {
           // if it is not valid provide the user with an error message
           StdOut.print("Column should be from 1 to 7");
           return false;
       }
       return true;
   }

   // dropCoin() to drop the coin the appropriate cell with the coin
   private void dropCoin(int column, State checker, String str)
   {
       // condition to check whether the column is filled or not and if
       // unfilled, place the disk by calling the
       // placeDisk()
       while (!gb.addChecker(column - 1, checker))
       {
           // if the column is filled; intimate the user with a message
           // regarding the column
           StdOut.print("This column is filled! Choose another one.");
           do
           {
               column = getColumnNumberToInsert(str);
           } while (!isValidColumnNumber(column));
       }      
   }
  
   // checkStatusDisplayWinner() to check the status of the winner
   private boolean checkStatusDisplayWinner(int column)
   {
       int rowVal = gb.getRowNumber();
      
       Cell cell = gb.getChecker(rowVal, column-1);
      
       if(gb.isFull())
       {
           StdOut.println("Draw Game");
           return true;
       }
       else if(gb.GameOver(rowVal, column-1))
       {
           if(cell.getChecker() == State.blueChecker)
           {
               StdOut.println("Blue wins");
           }
           else if(cell.getChecker() == State.redChecker)
           {
               StdOut.println("Red wins");
           }
           return true;
       }
       else
           return false;
   }

   // playGame() method to start the game to play
   public void playGame()
   {
      
       gb.drawGameBoard();
       State checker = null;
       int column;

       // boolean to hold the turns of the player
       boolean isRedTrun = true;
       while (true)
       {
           System.out.println();
           // string to hold the turn of the player name
           String str = "";

           // check who turns it is depending on it set the text to str
           if (isRedTrun)
           {
               str = "Red's turn!";
               checker = State.redChecker;
           }
           else
           {
               str = "Blue's turn!";
               checker = State.blueChecker;
           }

           do
           {
               column = getColumnNumberToInsert(str);
           } while (!isValidColumnNumber(column));
           dropCoin(column, checker, str);
          
           // print the board
           gb.drawGameBoard();
           if(checkStatusDisplayWinner(column))
           {              
               break;
           }      
          
           isRedTrun = !isRedTrun;
       }
   }
}


// GameDriver.java
public class GameDriver
{
   public static void main(String args[])
   {
       Connect4Game c4g = new Connect4Game();
       c4g.playGame();
   }
}

Add a comment
Know the answer?
Add Answer to:
Code in JAVA You are asked to implement “Connect 4” which is a two player game....
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
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