Question

In: Computer Science

**NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WITH NO ERRORS** **TO CREATE...

**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:

 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 
Drop a red disk at column (0-6): 0
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 | R |   |   |   |   |   |   |
 
Computer chose column 4
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 | R |   |   |   | Y |   |   |
 
Drop a red disk at column (0-6): 0
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 | R |   |   |   |   |   |   |
 | R |   |   |   | Y |   |   |
 
Computer chose column 5
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 | R |   |   |   |   |   |   |
 | R |   |   |   | Y | Y |   |
 
Drop a red disk at column (0-6): 0
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 | R |   |   |   |   |   |   |
 | R |   |   |   |   |   |   |
 | R |   |   |   | Y | Y |   |
 
Computer chose column 6
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 | R |   |   |   |   |   |   |
 | R |   |   |   |   |   |   |
 | R |   |   |   | Y | Y | Y |
 
Drop a red disk at column (0-6): 0
 |   |   |   |   |   |   |   |
 |   |   |   |   |   |   |   |
 | R |   |   |   |   |   |   |
 | R |   |   |   |   |   |   |
 | R |   |   |   |   |   |   |
 | R |   |   |   | Y | Y | Y |
 
Red wins!

Use this code to help:

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(" |");
}


}

Solutions

Expert 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<ROWS;i++)
           for(int j=0;j<COLUMNS;j++)
               grid[i][j]='0';
      
       //initial game status continue
       status=CONTINUE;
       winningColor=' ';
   }
  
   private boolean drop(char color,int column)
   {
       //check from last row backwards to find the empty row
       for(int i=ROWS-1;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<ROWS;i++)
       {
           System.out.print("\n|");
           for(int j=0;j<COLUMNS;j++)
               if(grid[i][j]=='0')
                   System.out.print(" |");
               else
                  
                   System.out.print(grid[i][j]+"|");
       }
   }
   private void updateStatus(char color)
   {
       int occurs;
      
       //keep track of empty spots to know if the game should continue or its a draw
       boolean emptySpots=false;
      
       for(int i=0;i<ROWS;i++)
       {
           for(int j=0;j<COLUMNS;j++)
           {
               occurs=0;
              
               //check horizontal
               for(int k=0;k<4;k++)
               {
                   if(j+k<COLUMNS) //check if column withing matrix range
                   {
                       if(grid[i][j+k]==color)
                           occurs++;
                       else
                       {
                           if(grid[i][j+k]=='0')
                               emptySpots=true;
                          
                       }
                   }
               }
               if(occurs==4) //found 4 occurences horizontally
               {
                   status=WIN;
                   winningColor=color;
               }
               else
               {
                   occurs=0;
                   //check vertically
                   for(int k=0;k<4;k++)
                   {
                       if(i+k<ROWS) //check if row in matrix range
                       {
                           if(grid[i+k][j]==color)
                           occurs++;
                           else{
                              
                               if(grid[i+k][j]=='0')
                                   emptySpots=true;
                                  
                           }
                       }
                   }
                   if(occurs==4) //found 4 occurences vertically
                   {
                       status=WIN;
                       winningColor=color;
                   }
                   else
                   {
                       occurs=0;
                       //check diagonally right
                       for(int k=0;k<4;k++)
                       {
                           if(i+k< ROWS && j+k<COLUMNS) //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 right i.e. column increasing row increasing
                       {
                           status=WIN;
                           winningColor=color;
                       }
                       else
                       {
                           occurs=0;
                           //check diagonally left
                           for(int k=0;k<4;k++)
                           {
                               if(i+k< ROWS && j-k>=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("\nDrop 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("\nComputer choose coloumn:"+column);
           }
           if(!drop(color,column))
               System.out.println("\nColumn 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("\nPlayer 1 (Red) wins the game!");
           else
               System.out.println("\nComputer (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!


Related Solutions

find all the errors c++ should be able to be compiled and run to perform the...
find all the errors c++ should be able to be compiled and run to perform the task #include iostream #include <string> Using namespace std; class Customer { // Constructor void Customer(string name, string address) : cust_name(name), cust_address(address) { acct_number = this.getNextAcctNumber(); } // Accessor to get the account number const int getAcctNumber() { return acct_number; } // Accessor to get the customer name string getCustName(} const { return cust_name; } // Accessor to get the customer address string getCustAddress() const...
Write a 2-3 page paper that answers the question, "Who are you?" The paper should be...
Write a 2-3 page paper that answers the question, "Who are you?" The paper should be written from the viewpoint of you (the person) as a system in the environment. Include consideration of your subsystems: biological (stage of physical development, sex, sexual orientation, relationship to the natural world), psychological (stages of psychological development), and spiritual/religious (moral development). Your paper should discuss these subsystems with an awareness of the impact of diversity on your own human behavior.
Answer the following questions. Your answers should address all parts of the question and be approximately...
Answer the following questions. Your answers should address all parts of the question and be approximately 300-400 words each. Make sure to thoroughly support all answers with accurate details and relevant evidence from the textbook and other resources. Search the Internet and find a company that offers medical professional liability (MPL) policies in your state for your area of practice. Provide a link to the company. Summarize their available coverage and limits of coverage. What optional coverage is available for...
Answer the following questions. Your answers should address all parts of the questions and be approximately...
Answer the following questions. Your answers should address all parts of the questions and be approximately 300-400 words each. Make sure to thoroughly support all answers with accurate details and relevant evidence from the textbook and other resources. 1. Several coworkers are in the lunchroom on their lunch break. Sam and his friend George are having a rather loud conversation about the party they attended over the past weekend. George relates a joke that he heard at the party; it...
Question1: All ANSWERS SHOULD BE HANDWRITTEN AND DIAGRAMS PROVIDED. DRAW A SQUARE AROUND THE FINAL ANSWER....
Question1: All ANSWERS SHOULD BE HANDWRITTEN AND DIAGRAMS PROVIDED. DRAW A SQUARE AROUND THE FINAL ANSWER. The value of zα/2 when determine the 92% confidence interval for p. The decision rule (aka, the rejection region) for testing the following pair of hypotheses at the .05 level of significance when the population standard deviation is unknown and a random sample of size 28 is taken. H0: µ = 18 Ha: µ < 18 The value of tα/2 when determine the 99%...
There are 3 short answer questions in this paper. Type your answers where indicated. Your answers...
There are 3 short answer questions in this paper. Type your answers where indicated. Your answers can be in bullet point form. A local resort in the Blue Mountains is for sale. What are the potential valuation effects of COVID-19 and of the bad bushfire season the year before? Identify how these events would be taken into consideration in a valuation model. Be sure to identify positive or negative valuation effects and whether these effects are short term or long...
Short Answer Writing Assignment All answers should be complete sentences. In the Week 2 Lab, you...
Short Answer Writing Assignment All answers should be complete sentences. In the Week 2 Lab, you found the mean and the standard deviation for the SLEEP variable for both males and females. Use those values for follow these directions to calculate the numbers again. (From Week 2 Lab: Calculate descriptive statistics for the variable Sleep by Gender. Sort the data by gender by clicking on Data and then Sort. Copy the Sleep of the males from the data file into...
1. Select all the answers that apply.  _____________ refers to how errors or uncertainty in one variable...
1. Select all the answers that apply.  _____________ refers to how errors or uncertainty in one variable multiply when that variable becomes part of a function involving other variables that might involve a certain degree of uncertainty or error as well. IAMs include _______ of the parameters to solve this problem. Propagation of Error; probability distributions Uncertainty Explosions; discount rates Uncertainty Explosions; probability distributions Cascading Uncertainties; discount rates 2.The problem with program-specific CBAs is that _________________________. the benefits are perceived in...
< > a paper of approximately 750 words that answers all of the following questions. Use...
< > a paper of approximately 750 words that answers all of the following questions. Use the contemporary economic issue with Cuba What is the economic issue? Why is it important? Which principles of economics apply? Choose from each of the areas: decision making, interaction, and how the economy works. How do the forces of supply impact the issue? How do the forces of demand impact the issue? How does elasticity apply to the issue? If appropriate, include a calculation...
Bio One sentence answers would suffice All about lipids  Be able to list all hydrophobic...
Bio One sentence answers would suffice All about lipids  Be able to list all hydrophobic macromolecules, 6 classes – fatty acids, triglycerides, phospholipids, Glycolipids, steroids, Terpenes, saturated, unsaturated, R groups in phosphoglycerides – serine, ethanolamine, choline, inositol, sphingolipids, sphingosine, cholesterol, steroid hormones, isoprene  Understand the structure and function of triglycerides, phospholipids and cholesterol.  Know what are saturated, unsaturated and trans fats  Explain how fats function as energy-storage molecules.  Apply knowledge of the structure of phospholipids...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT