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
  • Assignment overview In this assignment, you will implement a simple game of Battleship. If you are...

    Assignment overview In this assignment, you will implement a simple game of Battleship. If you are unfamiliar with the game Battleship, there are tutorials online describing the game. In short, there are two players that each have a 10 by 10 grid where ships are placed. The players take turns taking shots at each other’s ships. A player wins when they have shot at all spaces on their opponent’s grid that are occupied by ship. To sink a ship, you...

  • JAVA Only Help on the sections that say Student provide code. The student Provide code has...

    JAVA Only Help on the sections that say Student provide code. The student Provide code has comments that i put to state what i need help with. import java.util.Scanner; public class TicTacToe {     private final int BOARDSIZE = 3; // size of the board     private enum Status { WIN, DRAW, CONTINUE }; // game states     private char[][] board; // board representation     private boolean firstPlayer; // whether it's player 1's move     private boolean gameOver; // whether...

  • 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...

  • 1 Overview For this assignment you are required to write a Java program that plays (n,...

    1 Overview For this assignment you are required to write a Java program that plays (n, k)-tic-tac-toe; (n, k)-tic- tac-toe is played on a board of size n x n and to win the game a player needs to put k symbols on adjacent positions of the same row, column, or diagonal. The program will play against a human opponent. You will be given code for displaying the gameboard on the screen. 2 The Algorithm for Playing (n, k)-Tic-Tac-Toe The...

  • Problem 3: A Connect Four Player Class In this problem, you will create a Player class...

    Problem 3: A Connect Four Player Class In this problem, you will create a Player class to represent a player of the Connect Four game. In combination with the Board class that you wrote in Problem 2 and some code that you will write in the next problem set, this will enable you to play a game of Connect Four with a friend! Getting started Begin by downloading the file ps11pr3.py and opening it in Sypder or your editor of...

  • For this exercise, you will complete the TicTacToe Board that we started in the 2D Arrays...

    For this exercise, you will complete the TicTacToe Board that we started in the 2D Arrays Lesson. We will add a couple of methods to the TicTacToe class. To track whose turn it is, we will use a counter turn. This is already declared as a private instance variable. Create a getTurn method that returns the value of turn. Other methods to implement: printBoard()- This method should print the TicTacToe array onto the console. The board should include numbers that...

  • In C++. Write a class named FBoard for playing a game, where player x is trying to get her piece to row 7 and player o i...

    In C++. Write a class named FBoard for playing a game, where player x is trying to get her piece to row 7 and player o is trying to make it so player x doesn't have any legal moves. It should have: An 8x8 array of char for tracking the positions of the pieces. A data member called gameState that holds one of the following values: X_WON, O_WON, or UNFINISHED - use an enum type for this, not string (the...

  • Exercise 1 Adjacency Matrix In this part, you will implement the data model to represent a graph. Implement the followi...

    Exercise 1 Adjacency Matrix In this part, you will implement the data model to represent a graph. Implement the following classes Node.java: This class represents a vertex in the graph. It has only a single instance variable of type int which is set in the constructor. Implement hashCode() and equals(..) methods which are both based on the number instance variable Node - int number +Node(int number); +int getNumberO; +int hashCode() +boolean equals(Object o) +String toString0) Edge.java: This class represents a...

  • In Java* Please implement a class called "MyPet". It is designed as shown in the following...

    In Java* Please implement a class called "MyPet". It is designed as shown in the following class diagram. Four private instance variables: name (of the type String), color (of the type String), gender (of the type char) and weight(of the type double). Three overloaded constructors: a default constructor with no argument a constructor which takes a string argument for name, and a constructor with take two strings, a char and a double for name, color, gender and weight respectively. public...

  • Read through the code of the class Player, noting it has two instance variables, name and rank, which are of type String and three further instance variables won, drew and lost which are of type int....

    Read through the code of the class Player, noting it has two instance variables, name and rank, which are of type String and three further instance variables won, drew and lost which are of type int. There is also an attribute of the class, points, which does not have a corresponding instance variable. Also note the constructor and methods of the class and what they do. TournamentAdmin class code: public class RankAdmin {    /**     * Constructor for objects of class...

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