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:
Methods:
The GameBoard class holds the information about the entire game board:
Instance variable:
Methods:
The class Connect4Game should have
The class GameDriver should have a main method that creates a Connect4Game object and calls its playGame method.
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();
}
}
Code in JAVA You are asked to implement “Connect 4” which is a two player game....
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. 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, 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...
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 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 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. 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...
JAVA Write a class called Pen that contains the following information: 1. Private instance variables for the price of the pen (float) and color of the pen (String). 2. A two-argument constructor to set each of the instance variables above. If the price is negative, throw an IllegalArgumentException stating the argument that is not correct. 3. Get and Set methods for each instance variable with the same error detection as the constructor. public class Pen {
Please try to write the code with Project 1,2 and 3 in mind. And use java language, thank you very much. Create an Edit Menu in your GUI Add a second menu to the GUI called Edit which will have one menu item called Search. Clicking on search should prompt the user using a JOptionPane input dialog to enter a car make. The GUI should then display only cars of that make. You will need to write a second menu...
Create a TicTacToe class that initializes a 3x3 board of "-" values. We will use this class in future exercises to fully build out a Tic Tac Toe game! The TicTacToe class should have a 2D array as an instance variable and a constructor that initializes the 2D array with the "-" value. Add a getter method that returns the private 2D instance variable. public class TicTacToeTester { //You don't need to alter any of the code in this class!...