Write a class to represent a connect 4 game, using a 2-dimensional array (I woul
ID: 3731788 • Letter: W
Question
Write a class to represent a connect 4 game, using a 2-dimensional array (I would recommend an array of strings or chars, with each cell initially set to " ")
Two players, player 1 and player 2, will be playing. Both players are people sitting at the same computer console. Use a string or char of X and O, or * and O, or something similar to represent each player's token.
The board is represented by a 2-dimensional array, 6 rows of 7 columns, of strings or chars.
The value of a " " represents that this space is available; the value X indicates the space is occupied by player 1, the value O indicates the space is occupied by player 2. (Replace X and O with whichever token symbols you choose to use). Hint:Using " " makes your game board print on the screen easily when the player's token is dropped in that spot.
You will need two objects for the game:
A Player object that has the player's name, and their token symbol
A Connect4 object that has the 2-dimensional game board, and several methods:
Play - this method will play the game between the two people represented by two instances of the Player object. The game is played by two people sitting at the computer console, there is no "AI" in this. The Play method will call several other methods outlined below to verify the move is legal, update the board, and check for a winner.
The game board is 6x7, so there are a total of 42 moves possible - loop and prompt for plays from each player in turn. In the play method on your Connect4 object, you will need to loop, and prompt for plays(A6x7 board= 42possible plays),asking which column to"drop"their token into. Make sure the column is a valid column,and that the column isn't full. At each iteration of the loop,you will need to call methods of the Connect4class to update the Connect4object. You need to keep track of who is playing(player1or player2),enforce the rules,check if either player has won the game.
If a player wins,exit the loop and return the winner to the client. You can also present the results of the game. If the game ends in a tie,you should output that result.
In your Connect4 class, you will need to code the following methods:
A default constructor that takes two players who will play the game, and instantiating the 2-dimensional array representing the board
A play method, that will start/play the game
A method that allows a player to make a move; it takes two arguments: the player and the column on the board
A method checking if a play is legal
A method checking if a player has won the game; you can break up that method into several methods if you like (for instance, check if a player has won with vertical 4 in a row, horizontal 4 in a row, / diagonal 4 in a row, or diagonal 4 in a row).
Using Java Write a client (driver) class, where the main method is located, to test all the methods in your class and enable the user to play. In the main method of your client class, your program will simulate a connect-4 game from the command line, doing the following:
Create two Player objects
Create a Connect4 object, and instantiate it
Call the Connect4 object's play method, and report the result of the game. Prompt the users to play again or exit the game.
Using accessor and mutators for the rows and columns
// Some notes i have jotted down for format
Board
Player1
Player2
Rules
Chips
Connect 4 Board
int WIDTH; 7 - can be constant
int HEIGHT; 6 - can be constant
chips [height] [width] board
Player
int numChips; 25
Chips [numChips]
COLOR playerColor
String name
Constructor to create the board
Public board ()
Accessors
* private getRow (int rowNum) - return: chip[width]
* private getColumn (int colNum) - return: chip [height]
* private getDiagonal (int row, int col) - return: chip [2] [6] (length of array will be no greater than the height, may want to create constant about height of the diagonal array
* public getDiagonal (int row, int col)
Will need to return 2 diagonals to check for winning
Array will be created by the
Ask for start position by subtracting a column and subtracting a row until you hit [0] [0] or [6] [7] (end of board).
Array will check if filled, this will determine the winner
Mutators
public setCell (int col, Chip chip) - return: void
Chip
color could be a class (separate file in the source)
public enum COLOR: final
public chip (enum Color)
public checkForWinner () - return: color
-will also need to test for a tie
Connect 4 Engine
Connect 4 Board board
Player player1
Player player2
connect4Engine (Player p1, Player p2)
play ( ) - return: void
play will be a loop until someone wins or a tie
public Draw ( ) - return: void
will draw the board
Play -> Draw -> make p1 move -> draw the board -> check for win/tie -> if winner terminate, if not -> make p2 move -> draw the board ->
Should have connect 4 driver to ask for their names, create 2 players with appropriate color. Creates a game engine.
Might want private method to check rows
private checkRows() - return: COLOR
private checkCols() - return: COLOR
private checkDiag () - return: COLOR
Might want to check diagonals to determine
Explanation / Answer
Player.java
public class Player {
private String name;
private String token;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Player()
{
}
public Player(String name, String token) {
super();
this.name = name;
this.token = token;
}
@Override
public String toString() {
return "Player [name=" + name + ", token=" + token + "]";
}
}
---------------------------------------------------------------------------
connect4.java
import java.util.Scanner;
public class Connet4 {
private Player p1;
private Player p2;
private String[][] board;
public Connet4()
{
}
public Connet4(Player p1, Player p2) {
super();
this.p1 = p1;
this.p2 = p2;
this.board = new String[6][7];
}
public void start() {
System.out.println("Player 1 Name and Token"+this.p1);
System.out.println("Player 2 Name and Token"+this.p2);
System.out.println("-----------Rules--------------");
System.out.println("Player's have to enter their position alternatively with Player1 starting first");
System.out.println("Position should be entered in form 0 0 if Player wishes to select first cell on the board");
System.out.println("--------------------------------");
boolean winner=false;
for(int p=0;p<6;p++)
{
for(int q=0;q<7;q++)
{
this.board[p][q]="";
}
}
Scanner sc2 = new Scanner(System.in);
boolean flag=true;
for(int i=1;i<=42;i++)
{
if(flag)
{
System.out.println("Player 1 Name and Token"+this.p1);
System.out.println("Please Enter your move");
String move=sc2.nextLine();
String[] res = move.split(" ");
boolean valid=this.checkIfMoveIsValid(res[0],res[1]);
if(valid==false)
{
System.out.println("Player 1 try again");
i--;
}
else
{
this.makeMove(res[0],res[1],this.p1.getToken());
this.printBoard();
winner=this.checkWinner(this.p1.getToken());
if(winner)
{
System.out.println("Player 1 is winner");
}
flag=false;
}
}
else
{
System.out.println("Player 2 Name and Token"+this.p2);
System.out.println("Please Enter your move");
String move=sc2.nextLine();
String[] res = move.split(" ");
boolean valid=this.checkIfMoveIsValid(res[0],res[1]);
if(valid==false)
{
System.out.println("Player 2 try again");
i--;
}
else
{
this.makeMove(res[0],res[1],this.p2.getToken());
this.printBoard();
winner=this.checkWinner(this.p2.getToken());
if(winner)
{
System.out.println("Player 2 is winner");
}
flag=true;
}
}
}
if(!(winner))
{
System.out.println("Game is Draw");
}
}
private boolean checkWinner(String token) {
//horizontal 4 in a row
for(int p=0;p<6;p++)
{
boolean rowCheckFlag=false;
int rowCheckCount=0;
for(int q=0;q<7;q++)
{
if(rowCheckCount==4 && rowCheckFlag ==true )
{
return true;
}
if(this.board[p][q].equals(token))
{
rowCheckFlag=true;
rowCheckCount=rowCheckCount+1;
}
else
{
rowCheckFlag=false;
rowCheckCount=0;
}
}
}
//Vertical 4 in a row
for(int p=0;p<6;p++)
{
boolean rowCheckFlag=false;
int rowCheckCount=0;
for(int q=0;q<7;q++)
{
if(rowCheckCount==4 && rowCheckFlag ==true )
{
return true;
}
if(this.board[q][p].equals(token))
{
rowCheckFlag=true;
rowCheckCount=rowCheckCount+1;
}
else
{
rowCheckFlag=false;
rowCheckCount=0;
}
}
}
//diagonal 4 in a row
for(int p=0;p<6;p++)
{
boolean rowCheckFlag=false;
int rowCheckCount=0;
for(int q=0;q<7;q++)
{
try
{
for(int i=0;i<3;i++)
{
if(this.board[p][i].equals(token))
{
rowCheckFlag=true;
rowCheckCount=rowCheckCount+1;
}
else
{
rowCheckFlag=false;
rowCheckCount=0;
}
}
}
catch(Exception e)
{
}
if(rowCheckCount==4 && rowCheckFlag ==true )
{
return true;
}
}
}
//diagonal 4 in a row
for(int p=0;p<6;p++)
{
boolean rowCheckFlag=false;
int rowCheckCount=0;
for(int q=0;q<7;q++)
{
try
{
for(int i=0;i<3;i++)
{
if(this.board[i][p].equals(token))
{
rowCheckFlag=true;
rowCheckCount=rowCheckCount+1;
}
else
{
rowCheckFlag=false;
rowCheckCount=0;
}
}
}
catch(Exception e)
{
}
if(rowCheckCount==4 && rowCheckFlag ==true )
{
return true;
}
}
}
return false;
}
private void printBoard() {
for(int p=0;p<6;p++)
{
for(int q=0;q<7;q++)
{
System.out.print(this.board[p][q]+" ");
}
System.out.print(" ");
}
}
private void makeMove(String po1, String po2, String token) {
int pos1=Integer.parseInt(po1);
int pos2=Integer.parseInt(po2);
this.board[pos1][pos2]=token;
}
private boolean checkIfMoveIsValid(String po1, String po2) {
int pos1=Integer.parseInt(po1);
int pos2=Integer.parseInt(po2);
try
{
if(this.board[pos1][pos2]=="")
{
return true;
}
}
catch(Exception e)
{
System.out.println("Invalid Move: Please Enter Correct X and Y Co ordinate");
return false;
}
return false;
}
}
-------------------------------------------------------------------------------
Driver.java
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Player Player();
Player two = new Player();
System.out.println("Welcome to Connect 4 game- 2 Player Mode");
System.out.println("Enter Player1 Name");
String name = sc.nextLine();
System.out.println("Enter Player1 Token");
String token = sc.nextLine();
one.setName(name);
one.setToken(token);
System.out.println("Enter Player2 Name");
name = sc.nextLine();
System.out.println("Enter Player2 Token");
token = sc.nextLine();
two.setName(name);
two.setToken(token);
Connet4 connect4 = new Connet4(one,two);
System.out.println("Enter on any key to start the Game");
token = sc.nextLine();
connect4.start();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.