SlideShare a Scribd company logo
1 of 13
Download to read offline
**NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN
WITH NO ERRORS**
**TO CREATE THIS JAVA PROGRAM USE ECLIPSE NEON**
The assignment is as follows:
Connect four is a two-player board game in which the players alternately drop colored disks into
a seven-column, six-row vertically-suspended grid.
The objective of the game is to connect four same-colored disks in a row, a column, or a
diagonal before your opponent can do likewise. The program prompts a player to drop a RED
disk onto a column 0-6. Whenever a disk is dropped, the program redisplays the board on the
console and determines the status of the game (win, draw, or continue). The computer player will
RANDOMLY choose a column to drop a YELLOW disk onto. If a player tries to drop a disk on
a column that is full, the turn is lost.
In other words, create a "1 player" version of the game,"Connect four." After the player is
prompted to drop a disc (R). The computer will automatically drop the other disc (Y) in a
random spot.
Sample output:
import java.util.Scanner;
/**
* Chapter 8 Exercise 20:
*
* (Game: connect four) Connect four is a two-player board game
* in which the players alternately drop colored disks into a seven-column,
* six-row vertically suspended grid, as shown below.
* The objective of the game is to connect four same-colored disks in a row,
* a column, or a diagonal before your opponent can do likewise. The program
* prompts two players to drop a red or yellow disk alternately. In the preceding
* figure, the red disk is shown in a dark color and the yellow in a light color.
* Whenever a disk is dropped, the program re-displays the board on the console
* and determines the status of the game (win, draw, or continue).
*
*/
public class Connect4 {
static boolean isPlayer1Turn = true;
static boolean hasWon = false;
public static void main(String[] args) {
String[][] m = createGrid(6,7);
Scanner input = new Scanner(System.in);
int column;
while (!hasWon) {
String diskColor = (isPlayer1Turn) ? "red" : "yellow";
displayMatrix(m);
boolean isFirstInput = true;
do {
if (!isFirstInput) {
System.out.println("COLUMN IS FULL. Try again...");
}
System.out.print("Drop a " + diskColor + " at column (0–6): ");
column = input.nextInt();
isFirstInput = false;
} while (!dropDisk(m, column));
if (isConsecutiveFour(m)) {
displayMatrix(m);
System.out.print("The "+diskColor+" player won! Do you want to play again? (y/n)");
char s = input.next().charAt(0);
if (s == 'y' || s == 'Y') {
m = createGrid(6, 7);
isPlayer1Turn = false;
} else {
System.exit(0);
}
}
isPlayer1Turn = !isPlayer1Turn;
}
}
public static void displayMatrix(String[][] m) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
System.out.print(m[i][j]);
}
System.out.println("");
}
}
public static String[][] createGrid(int row, int column) {
String[][] m = new String[row][column];
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
if (j == 0)
m[i][j] = "| |";
else
m[i][j] = " |";
}
}
return m;
}
public static boolean isConsecutiveFour(String[][] m) {
String s = (isPlayer1Turn) ? "R" : "Y";
int occurrence = 0;
// (m[0].length - 3) --> reason: only checking occurrences of 4
for (int j = 0; j < m[0].length - 3; j++) {
int y = m.length - 1; // row always starts on last row
int x = j;
while (x < m[0].length && y >= 0) {
if (m[y][x].contains(s)) { // | | | | | |R|R|
occurrence++; // | | | | |R|R|R|
if (occurrence == 4) return true; // | | | |R|R|R|R|
} else { // | | |R|R|R|R| |
occurrence = 0; // | |R|R|R|R| | |
} // |R|R|R|R| | | |
x++;
y--;
}
}
// (m.length - 2) --> reason: only checking occurrences of 4
// and last row has already been checked
for (int i = m.length - 2; i > 2; i--) {
int x = 0; // column always starts on the left side
int y = i;
occurrence = 0;
while (x < m[0].length && y >= 0) { // | | | |R|R| | |
// | | |R|R| | | |
// | |R|R| | | | |
if (m[y][x].contains(s)) { // |R|R| | | | | |
occurrence++; // |R| | | | | | |
if (occurrence == 4) return true; // | | | | | | | |
} else {
occurrence = 0;
}
x++;
y--;
}
}
// j >= 3 --> reason: only checking occurrences of 4
for (int j = m[0].length - 1; j >= 3; j--) {
int y = m.length -1; // row always starts on last row
int x = j;
occurrence = 0;
while (x >= 0 && y >= 0) {
// |L|L| | | | | |
if (m[y][x].contains(s)) { // |L|L|L| | | | |
occurrence++; // |L|L|L|L| | | |
if (occurrence == 4) return true; // | |L|L|L|L| | |
} else { // | | |L|L|L|L| |
occurrence = 0; // | | | |L|L|L|L|
}
x--;
y--;
}
}
// i > 2 --> reason: only checking occurrences of 4
for (int i = m.length - 2; i > 2; i--) {
int x = m[0].length - 1;
int y = i;
occurrence = 0;
while (x >= 0 && y >= 0) { // | | |L|L| | | |
// | | | |L|L| | |
if (m[y][x].contains(s)) { // | | | | |L|L| |
occurrence++; // | | | | | |L|L|
if (occurrence == 4) return true; // | | | | | | |L|
} else { // | | | | | | | |
occurrence = 0;
}
x--;
y--;
}
}
return false;
}
public static boolean dropDisk(String[][] m, int column) {
// figure out which disk to drop
String s;
if (isPlayer1Turn) {
s = (column > 0) ? "R|" : "|R|";
} else {
s = (column > 0) ? "Y|" : "|Y|";
}
boolean didRowUpdate = false;
int row = 0;
// check if there is a disk in column
// if there is get the proper row index
for (int i = 0; i < m.length; i++) {
if (isClear(m[i][column])) {
didRowUpdate = true;
row = i;
}
}
if (!didRowUpdate) return false;
m[row][column] = s;
return true;
}
public static boolean isClear(String s) {
return s.contains("| |") || s.contains(" |");
}
}
Solution
Here is the complete code for the game. Comments are inline. Please do rate the answer if you
are happy with the program. Thanks. Sample output also attached
========================================================
import java.util.Random;
import java.util.Scanner;
/**
* Chapter 8 Exercise 20:
*
* (Game: connect four) Connect four is a two-player board game
* in which the players alternately drop colored disks into a seven-column,
* six-row vertically suspended grid, as shown below.
* The objective of the game is to connect four same-colored disks in a row,
* a column, or a diagonal before your opponent can do likewise. The program
* prompts two players to drop a red or yellow disk alternately. In the preceding
* figure, the red disk is shown in a dark color and the yellow in a light color.
* Whenever a disk is dropped, the program re-displays the board on the console
* and determines the status of the game (win, draw, or continue).
*
*
*Intially a game is created and its grid is initialized to all '0'. Using only a char array
*because we only need to store the letter 'R' or 'Y'. This makes comparisons easy later. Each
time
*depending on the color , that user gets to choose the column. For computer's turn, a random
number is generated
*within the range. If the color for any player was successfull, then the status for the game is
updated and the
*color is toggled to other color. When the status is updated, we check that color occurs in 4
possible ways, horizontal,
*vertical, diagonally right or diagonally left. If any of this happens, it means that color wins.
Also if that didn't occur
*we need to see we there were any empty spots to continue further or its a draw. Each time the
grid is displayed and also
*finally before showing the results.
*/
public class Connect4 {
static final int ROWS=6;
static final int COLUMNS=7;
//Game status codes
static final int DRAW=0;
static final int WIN=1;
static final int CONTINUE=2;
char grid[][];
int status;
char winningColor;
public Connect4()
{
grid=new char[ROWS][COLUMNS];
//initialize the grid
for(int i=0;i=0;i--)
{
if(grid[i][column]=='0') //found an empty place
{
grid[i][column]=color;
return true; //success in dropping color
}
}
//the previous return would have not executed at this point here... so was not able to place
//color
return false;
}
private void displayGrid()
{
for(int i=0;i=0) //make sure not to go out of bounds of matrix
{
if(grid[i+k][j-k]==color)
occurs++;
else{
if(grid[i+k][j-k]=='0')
emptySpots=true;
}
}
}
if(occurs==4) //found 4 occurences diagonally left i.e row increasing column
decreasing
{
status=WIN;
winningColor=color;
}
}
}
}
}
}
//check if no spots to continue further, then its a draw
if(status==CONTINUE)
if(!emptySpots)
status=DRAW;
}
public void play()
{
Scanner input=new Scanner(System.in);
int column;
char color='R';
Random rand=new Random();
while(status==CONTINUE)
{
//display grid each time
displayGrid();
//if player's turn
if(color=='R')
{
System.out.println(" Drop a red disk at column(0-6):");
column=input.nextInt();
}
else
{
//generate a random column for computer
column=rand.nextInt()%COLUMNS;
if(column<0) //if we got negative random number
column=-column;
System.out.println(" Computer choose coloumn:"+column);
}
if(!drop(color,column))
System.out.println(" Column full! Lost Turn");
else
{
updateStatus(color);
}
// change the color for next turn
color=color=='R'?'Y':'R';
}
input.close();
displayGrid();
if(status==WIN)
{
if(winningColor=='R')
System.out.println(" Player 1 (Red) wins the game!");
else
System.out.println(" Computer (Yellow) wins the game!");
}
else
{
System.out.println("Its a DRAW !");
}
System.out.println("GAME OVER!");
}
public static void main(String a[])
{
Connect4 game=new Connect4();
game.play();
}
}
================================
output:
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
Drop a red disk at column(0-6):
0
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | | | | |
Computer choose coloumn:2
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| |Y| | | | |
Drop a red disk at column(0-6):
2
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R| | | | |
|R| |Y| | | | |
Computer choose coloumn:6
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R| | | | |
|R| |Y| | | |Y|
Drop a red disk at column(0-6):
3
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R| | | | |
|R| |Y|R| | |Y|
Computer choose coloumn:3
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R|Y| | | |
|R| |Y|R| | |Y|
Drop a red disk at column(0-6):
4
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R|Y| | | |
|R| |Y|R|R| |Y|
Computer choose coloumn:1
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R|Y| | | |
|R|Y|Y|R|R| |Y|
Drop a red disk at column(0-6):
4
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R|Y|R| | |
|R|Y|Y|R|R| |Y|
Computer choose coloumn:3
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |Y| | | |
| | |R|Y|R| | |
|R|Y|Y|R|R| |Y|
Drop a red disk at column(0-6):
4
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |Y|R| | |
| | |R|Y|R| | |
|R|Y|Y|R|R| |Y|
Computer choose coloumn:5
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |Y|R| | |
| | |R|Y|R| | |
|R|Y|Y|R|R|Y|Y|
Drop a red disk at column(0-6):
4
| | | | | | | |
| | | | | | | |
| | | | |R| | |
| | | |Y|R| | |
| | |R|Y|R| | |
|R|Y|Y|R|R|Y|Y|
Player 1 (Red) wins the game!
GAME OVER!

More Related Content

Similar to NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf

The following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdfThe following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdfeyelineoptics
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdfkavithaarp
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdffonecomp
 
Can someone help me setup this in JAVA Im new to java. Thanks.pdf
Can someone help me setup this in JAVA Im new to java. Thanks.pdfCan someone help me setup this in JAVA Im new to java. Thanks.pdf
Can someone help me setup this in JAVA Im new to java. Thanks.pdfjeeteshmalani1
 
Tic tac toe on c++ project
Tic tac toe on c++ projectTic tac toe on c++ project
Tic tac toe on c++ projectUtkarsh Aggarwal
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfasif1401
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfFashionColZone
 
Introduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdfIntroduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdffeelinggifts
 
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfudit652068
 
Write a program in java in which you will build the“Sink theShipsGam.pdf
Write a program in java in which you will build the“Sink theShipsGam.pdfWrite a program in java in which you will build the“Sink theShipsGam.pdf
Write a program in java in which you will build the“Sink theShipsGam.pdfarchanenterprises
 
C# using Visual studio - Windows Form. If possible step-by-step inst.pdf
C# using Visual studio - Windows Form. If possible step-by-step inst.pdfC# using Visual studio - Windows Form. If possible step-by-step inst.pdf
C# using Visual studio - Windows Form. If possible step-by-step inst.pdffazalenterprises
 
i have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfi have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfpoblettesedanoree498
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfaoneonlinestore1
 
import javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdfimport javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdfADITIEYEWEAR
 
Need help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdfNeed help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdfhainesburchett26321
 
ch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.pptch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.pptMahyuddin8
 

Similar to NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf (16)

The following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdfThe following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdf
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdf
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdf
 
Can someone help me setup this in JAVA Im new to java. Thanks.pdf
Can someone help me setup this in JAVA Im new to java. Thanks.pdfCan someone help me setup this in JAVA Im new to java. Thanks.pdf
Can someone help me setup this in JAVA Im new to java. Thanks.pdf
 
Tic tac toe on c++ project
Tic tac toe on c++ projectTic tac toe on c++ project
Tic tac toe on c++ project
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdf
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdf
 
Introduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdfIntroduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdf
 
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
 
Write a program in java in which you will build the“Sink theShipsGam.pdf
Write a program in java in which you will build the“Sink theShipsGam.pdfWrite a program in java in which you will build the“Sink theShipsGam.pdf
Write a program in java in which you will build the“Sink theShipsGam.pdf
 
C# using Visual studio - Windows Form. If possible step-by-step inst.pdf
C# using Visual studio - Windows Form. If possible step-by-step inst.pdfC# using Visual studio - Windows Form. If possible step-by-step inst.pdf
C# using Visual studio - Windows Form. If possible step-by-step inst.pdf
 
i have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfi have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdf
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
 
import javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdfimport javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdf
 
Need help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdfNeed help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdf
 
ch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.pptch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.ppt
 

More from fms12345

Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdfExercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdffms12345
 
Describe the procedure you would use in the laboratory to determine .pdf
Describe the procedure you would use in the laboratory to determine .pdfDescribe the procedure you would use in the laboratory to determine .pdf
Describe the procedure you would use in the laboratory to determine .pdffms12345
 
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdfCHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdffms12345
 
Could you implement this please. I was told to use pointers as the d.pdf
Could you implement this please. I was told to use pointers as the d.pdfCould you implement this please. I was told to use pointers as the d.pdf
Could you implement this please. I was told to use pointers as the d.pdffms12345
 
A piece of malware is running on a Windows 7 machine via process inj.pdf
A piece of malware is running on a Windows 7 machine via process inj.pdfA piece of malware is running on a Windows 7 machine via process inj.pdf
A piece of malware is running on a Windows 7 machine via process inj.pdffms12345
 
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdfCompany names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdffms12345
 
2. The Lorenz curve measures inequality in person income distribution.pdf
2. The Lorenz curve measures inequality in person income distribution.pdf2. The Lorenz curve measures inequality in person income distribution.pdf
2. The Lorenz curve measures inequality in person income distribution.pdffms12345
 
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdffms12345
 
1.The shrimping industry needs female shrimp for production purposes.pdf
1.The shrimping industry needs female shrimp for production purposes.pdf1.The shrimping industry needs female shrimp for production purposes.pdf
1.The shrimping industry needs female shrimp for production purposes.pdffms12345
 
Who are the stakeholders in an income statement and whySolution.pdf
Who are the stakeholders in an income statement and whySolution.pdfWho are the stakeholders in an income statement and whySolution.pdf
Who are the stakeholders in an income statement and whySolution.pdffms12345
 
Which company maintains natural habitats while B allowing us to live .pdf
Which company maintains natural habitats while B allowing us to live .pdfWhich company maintains natural habitats while B allowing us to live .pdf
Which company maintains natural habitats while B allowing us to live .pdffms12345
 
When multiple strains of the same bacterial species are sequenced, w.pdf
When multiple strains of the same bacterial species are sequenced, w.pdfWhen multiple strains of the same bacterial species are sequenced, w.pdf
When multiple strains of the same bacterial species are sequenced, w.pdffms12345
 
What specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdfWhat specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdffms12345
 
What does the metaphor meaning for the Iron curtainSolutionIr.pdf
What does the metaphor meaning for the Iron curtainSolutionIr.pdfWhat does the metaphor meaning for the Iron curtainSolutionIr.pdf
What does the metaphor meaning for the Iron curtainSolutionIr.pdffms12345
 
What are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdfWhat are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdffms12345
 
Using the Web or another research tool, search for alternative means.pdf
Using the Web or another research tool, search for alternative means.pdfUsing the Web or another research tool, search for alternative means.pdf
Using the Web or another research tool, search for alternative means.pdffms12345
 
Using Array Approach, Linked List approach, and Delete Byte Approach.pdf
Using Array Approach, Linked List approach, and Delete Byte Approach.pdfUsing Array Approach, Linked List approach, and Delete Byte Approach.pdf
Using Array Approach, Linked List approach, and Delete Byte Approach.pdffms12345
 
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdfTV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdffms12345
 
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdfTim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdffms12345
 
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdfThe Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdffms12345
 

More from fms12345 (20)

Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdfExercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
 
Describe the procedure you would use in the laboratory to determine .pdf
Describe the procedure you would use in the laboratory to determine .pdfDescribe the procedure you would use in the laboratory to determine .pdf
Describe the procedure you would use in the laboratory to determine .pdf
 
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdfCHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
 
Could you implement this please. I was told to use pointers as the d.pdf
Could you implement this please. I was told to use pointers as the d.pdfCould you implement this please. I was told to use pointers as the d.pdf
Could you implement this please. I was told to use pointers as the d.pdf
 
A piece of malware is running on a Windows 7 machine via process inj.pdf
A piece of malware is running on a Windows 7 machine via process inj.pdfA piece of malware is running on a Windows 7 machine via process inj.pdf
A piece of malware is running on a Windows 7 machine via process inj.pdf
 
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdfCompany names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
 
2. The Lorenz curve measures inequality in person income distribution.pdf
2. The Lorenz curve measures inequality in person income distribution.pdf2. The Lorenz curve measures inequality in person income distribution.pdf
2. The Lorenz curve measures inequality in person income distribution.pdf
 
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
 
1.The shrimping industry needs female shrimp for production purposes.pdf
1.The shrimping industry needs female shrimp for production purposes.pdf1.The shrimping industry needs female shrimp for production purposes.pdf
1.The shrimping industry needs female shrimp for production purposes.pdf
 
Who are the stakeholders in an income statement and whySolution.pdf
Who are the stakeholders in an income statement and whySolution.pdfWho are the stakeholders in an income statement and whySolution.pdf
Who are the stakeholders in an income statement and whySolution.pdf
 
Which company maintains natural habitats while B allowing us to live .pdf
Which company maintains natural habitats while B allowing us to live .pdfWhich company maintains natural habitats while B allowing us to live .pdf
Which company maintains natural habitats while B allowing us to live .pdf
 
When multiple strains of the same bacterial species are sequenced, w.pdf
When multiple strains of the same bacterial species are sequenced, w.pdfWhen multiple strains of the same bacterial species are sequenced, w.pdf
When multiple strains of the same bacterial species are sequenced, w.pdf
 
What specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdfWhat specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdf
 
What does the metaphor meaning for the Iron curtainSolutionIr.pdf
What does the metaphor meaning for the Iron curtainSolutionIr.pdfWhat does the metaphor meaning for the Iron curtainSolutionIr.pdf
What does the metaphor meaning for the Iron curtainSolutionIr.pdf
 
What are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdfWhat are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdf
 
Using the Web or another research tool, search for alternative means.pdf
Using the Web or another research tool, search for alternative means.pdfUsing the Web or another research tool, search for alternative means.pdf
Using the Web or another research tool, search for alternative means.pdf
 
Using Array Approach, Linked List approach, and Delete Byte Approach.pdf
Using Array Approach, Linked List approach, and Delete Byte Approach.pdfUsing Array Approach, Linked List approach, and Delete Byte Approach.pdf
Using Array Approach, Linked List approach, and Delete Byte Approach.pdf
 
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdfTV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
 
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdfTim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
 
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdfThe Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
 

Recently uploaded

Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationNeilDeclaro1
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 

Recently uploaded (20)

Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 

NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf

  • 1. **NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WITH NO ERRORS** **TO CREATE THIS JAVA PROGRAM USE ECLIPSE NEON** The assignment is as follows: Connect four is a two-player board game in which the players alternately drop colored disks into a seven-column, six-row vertically-suspended grid. The objective of the game is to connect four same-colored disks in a row, a column, or a diagonal before your opponent can do likewise. The program prompts a player to drop a RED disk onto a column 0-6. Whenever a disk is dropped, the program redisplays the board on the console and determines the status of the game (win, draw, or continue). The computer player will RANDOMLY choose a column to drop a YELLOW disk onto. If a player tries to drop a disk on a column that is full, the turn is lost. In other words, create a "1 player" version of the game,"Connect four." After the player is prompted to drop a disc (R). The computer will automatically drop the other disc (Y) in a random spot. Sample output: import java.util.Scanner; /** * Chapter 8 Exercise 20: * * (Game: connect four) Connect four is a two-player board game * in which the players alternately drop colored disks into a seven-column, * six-row vertically suspended grid, as shown below. * The objective of the game is to connect four same-colored disks in a row, * a column, or a diagonal before your opponent can do likewise. The program * prompts two players to drop a red or yellow disk alternately. In the preceding * figure, the red disk is shown in a dark color and the yellow in a light color. * Whenever a disk is dropped, the program re-displays the board on the console * and determines the status of the game (win, draw, or continue). * */ public class Connect4 { static boolean isPlayer1Turn = true; static boolean hasWon = false; public static void main(String[] args) {
  • 2. String[][] m = createGrid(6,7); Scanner input = new Scanner(System.in); int column; while (!hasWon) { String diskColor = (isPlayer1Turn) ? "red" : "yellow"; displayMatrix(m); boolean isFirstInput = true; do { if (!isFirstInput) { System.out.println("COLUMN IS FULL. Try again..."); } System.out.print("Drop a " + diskColor + " at column (0–6): "); column = input.nextInt(); isFirstInput = false; } while (!dropDisk(m, column)); if (isConsecutiveFour(m)) { displayMatrix(m); System.out.print("The "+diskColor+" player won! Do you want to play again? (y/n)"); char s = input.next().charAt(0); if (s == 'y' || s == 'Y') { m = createGrid(6, 7); isPlayer1Turn = false; } else { System.exit(0); } } isPlayer1Turn = !isPlayer1Turn; } } public static void displayMatrix(String[][] m) { for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++) { System.out.print(m[i][j]); } System.out.println("");
  • 3. } } public static String[][] createGrid(int row, int column) { String[][] m = new String[row][column]; for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++) { if (j == 0) m[i][j] = "| |"; else m[i][j] = " |"; } } return m; } public static boolean isConsecutiveFour(String[][] m) { String s = (isPlayer1Turn) ? "R" : "Y"; int occurrence = 0; // (m[0].length - 3) --> reason: only checking occurrences of 4 for (int j = 0; j < m[0].length - 3; j++) { int y = m.length - 1; // row always starts on last row int x = j; while (x < m[0].length && y >= 0) { if (m[y][x].contains(s)) { // | | | | | |R|R| occurrence++; // | | | | |R|R|R| if (occurrence == 4) return true; // | | | |R|R|R|R| } else { // | | |R|R|R|R| | occurrence = 0; // | |R|R|R|R| | | } // |R|R|R|R| | | | x++; y--; } } // (m.length - 2) --> reason: only checking occurrences of 4 // and last row has already been checked for (int i = m.length - 2; i > 2; i--) { int x = 0; // column always starts on the left side
  • 4. int y = i; occurrence = 0; while (x < m[0].length && y >= 0) { // | | | |R|R| | | // | | |R|R| | | | // | |R|R| | | | | if (m[y][x].contains(s)) { // |R|R| | | | | | occurrence++; // |R| | | | | | | if (occurrence == 4) return true; // | | | | | | | | } else { occurrence = 0; } x++; y--; } } // j >= 3 --> reason: only checking occurrences of 4 for (int j = m[0].length - 1; j >= 3; j--) { int y = m.length -1; // row always starts on last row int x = j; occurrence = 0; while (x >= 0 && y >= 0) { // |L|L| | | | | | if (m[y][x].contains(s)) { // |L|L|L| | | | | occurrence++; // |L|L|L|L| | | | if (occurrence == 4) return true; // | |L|L|L|L| | | } else { // | | |L|L|L|L| | occurrence = 0; // | | | |L|L|L|L| } x--; y--; } } // i > 2 --> reason: only checking occurrences of 4 for (int i = m.length - 2; i > 2; i--) { int x = m[0].length - 1; int y = i;
  • 5. occurrence = 0; while (x >= 0 && y >= 0) { // | | |L|L| | | | // | | | |L|L| | | if (m[y][x].contains(s)) { // | | | | |L|L| | occurrence++; // | | | | | |L|L| if (occurrence == 4) return true; // | | | | | | |L| } else { // | | | | | | | | occurrence = 0; } x--; y--; } } return false; } public static boolean dropDisk(String[][] m, int column) { // figure out which disk to drop String s; if (isPlayer1Turn) { s = (column > 0) ? "R|" : "|R|"; } else { s = (column > 0) ? "Y|" : "|Y|"; } boolean didRowUpdate = false; int row = 0; // check if there is a disk in column // if there is get the proper row index for (int i = 0; i < m.length; i++) { if (isClear(m[i][column])) { didRowUpdate = true; row = i; } } if (!didRowUpdate) return false; m[row][column] = s; return true;
  • 6. } public static boolean isClear(String s) { return s.contains("| |") || s.contains(" |"); } } Solution Here is the complete code for the game. Comments are inline. Please do rate the answer if you are happy with the program. Thanks. Sample output also attached ======================================================== import java.util.Random; import java.util.Scanner; /** * Chapter 8 Exercise 20: * * (Game: connect four) Connect four is a two-player board game * in which the players alternately drop colored disks into a seven-column, * six-row vertically suspended grid, as shown below. * The objective of the game is to connect four same-colored disks in a row, * a column, or a diagonal before your opponent can do likewise. The program * prompts two players to drop a red or yellow disk alternately. In the preceding * figure, the red disk is shown in a dark color and the yellow in a light color. * Whenever a disk is dropped, the program re-displays the board on the console * and determines the status of the game (win, draw, or continue). * * *Intially a game is created and its grid is initialized to all '0'. Using only a char array *because we only need to store the letter 'R' or 'Y'. This makes comparisons easy later. Each time *depending on the color , that user gets to choose the column. For computer's turn, a random number is generated *within the range. If the color for any player was successfull, then the status for the game is updated and the *color is toggled to other color. When the status is updated, we check that color occurs in 4
  • 7. possible ways, horizontal, *vertical, diagonally right or diagonally left. If any of this happens, it means that color wins. Also if that didn't occur *we need to see we there were any empty spots to continue further or its a draw. Each time the grid is displayed and also *finally before showing the results. */ public class Connect4 { static final int ROWS=6; static final int COLUMNS=7; //Game status codes static final int DRAW=0; static final int WIN=1; static final int CONTINUE=2; char grid[][]; int status; char winningColor; public Connect4() { grid=new char[ROWS][COLUMNS]; //initialize the grid for(int i=0;i=0;i--) { if(grid[i][column]=='0') //found an empty place { grid[i][column]=color; return true; //success in dropping color } } //the previous return would have not executed at this point here... so was not able to place //color return false;
  • 8. } private void displayGrid() { for(int i=0;i=0) //make sure not to go out of bounds of matrix { if(grid[i+k][j-k]==color) occurs++; else{ if(grid[i+k][j-k]=='0') emptySpots=true; } } } if(occurs==4) //found 4 occurences diagonally left i.e row increasing column decreasing { status=WIN; winningColor=color; } } } } } } //check if no spots to continue further, then its a draw if(status==CONTINUE) if(!emptySpots) status=DRAW; }
  • 9. public void play() { Scanner input=new Scanner(System.in); int column; char color='R'; Random rand=new Random(); while(status==CONTINUE) { //display grid each time displayGrid(); //if player's turn if(color=='R') { System.out.println(" Drop a red disk at column(0-6):"); column=input.nextInt(); } else { //generate a random column for computer column=rand.nextInt()%COLUMNS; if(column<0) //if we got negative random number column=-column; System.out.println(" Computer choose coloumn:"+column); } if(!drop(color,column)) System.out.println(" Column full! Lost Turn"); else { updateStatus(color); }
  • 10. // change the color for next turn color=color=='R'?'Y':'R'; } input.close(); displayGrid(); if(status==WIN) { if(winningColor=='R') System.out.println(" Player 1 (Red) wins the game!"); else System.out.println(" Computer (Yellow) wins the game!"); } else { System.out.println("Its a DRAW !"); } System.out.println("GAME OVER!"); } public static void main(String a[]) { Connect4 game=new Connect4(); game.play(); } } ================================ output: | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Drop a red disk at column(0-6):
  • 11. 0 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |R| | | | | | | Computer choose coloumn:2 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |R| |Y| | | | | Drop a red disk at column(0-6): 2 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |R| | | | | |R| |Y| | | | | Computer choose coloumn:6 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |R| | | | | |R| |Y| | | |Y| Drop a red disk at column(0-6): 3 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |R| | | | |
  • 12. |R| |Y|R| | |Y| Computer choose coloumn:3 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |R|Y| | | | |R| |Y|R| | |Y| Drop a red disk at column(0-6): 4 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |R|Y| | | | |R| |Y|R|R| |Y| Computer choose coloumn:1 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |R|Y| | | | |R|Y|Y|R|R| |Y| Drop a red disk at column(0-6): 4 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |R|Y|R| | | |R|Y|Y|R|R| |Y| Computer choose coloumn:3 | | | | | | | | | | | | | | | | | | | | | | | | | | | |Y| | | |
  • 13. | | |R|Y|R| | | |R|Y|Y|R|R| |Y| Drop a red disk at column(0-6): 4 | | | | | | | | | | | | | | | | | | | | | | | | | | | |Y|R| | | | | |R|Y|R| | | |R|Y|Y|R|R| |Y| Computer choose coloumn:5 | | | | | | | | | | | | | | | | | | | | | | | | | | | |Y|R| | | | | |R|Y|R| | | |R|Y|Y|R|R|Y|Y| Drop a red disk at column(0-6): 4 | | | | | | | | | | | | | | | | | | | | |R| | | | | | |Y|R| | | | | |R|Y|R| | | |R|Y|Y|R|R|Y|Y| Player 1 (Red) wins the game! GAME OVER!