Question

In: Computer Science

Create a game of Connect Four using a two dimensional array (that has 6 rows and...

Create a game of Connect Four using a two dimensional array (that has 6 rows and 7 columns) as a class variable. It should be user friendly and be a two person game. It should have clear directions and be visually appealing. The code MUST have a minimum of 3 methods (other than the main method). The player should be able to choose to play again.

**Code must be written in Java**

Solutions

Expert Solution

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// we are going to create a simple 2-players Connect Four implementation in Java 8
public class ConnectFour {

  // we define characters for players (R for Red, Y for Yellow)
  private static final char[] PLAYERS = {'R', 'Y'};
  // dimensions for our board
  private final int width, height;
  // grid for the board
  private final char[][] grid;
  // we store last move made by a player
  private int lastCol = -1, lastTop = -1;

  public ConnectFour(int w, int h) {
    width = w;
    height = h;
    grid = new char[h][];

    // init the grid will blank cell
    for (int i = 0; i < h; i++) {
      Arrays.fill(grid[i] = new char[w], '.');
    }
  }

  // we use Streams to make a more concise method 
  // for representing the board
  public String toString() {
    return IntStream.range(0,  width).
           mapToObj(Integer::toString).
           collect(Collectors.joining()) + 
           "\n" +
           Arrays.stream(grid).
           map(String::new).
           collect(Collectors.joining("\n"));
  }

  // get string representation of the row containing 
  // the last play of the user
  public String horizontal() {
    return new String(grid[lastTop]);
  }

  // get string representation fo the col containing 
  // the last play of the user
  public String vertical() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      sb.append(grid[h][lastCol]);
    }

    return sb.toString();
  }

  // get string representation of the "/" diagonal 
  // containing the last play of the user
  public String slashDiagonal() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      int w = lastCol + lastTop - h;

      if (0 <= w && w < width) {
        sb.append(grid[h][w]);
      }
    }

    return sb.toString();
  }

  // get string representation of the "\" 
  // diagonal containing the last play of the user
  public String backslashDiagonal() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      int w = lastCol - lastTop + h;

      if (0 <= w && w < width) {
        sb.append(grid[h][w]);
      }
    }

    return sb.toString();
  }

  // static method checking if a substring is in str
  public static boolean contains(String str, String substring) {
    return str.indexOf(substring) >= 0;
  }

  // now, we create a method checking if last play is a winning play
  public boolean isWinningPlay() {
    if (lastCol == -1) {
      System.err.println("No move has been made yet");
      return false;
    }

    char sym = grid[lastTop][lastCol];
    // winning streak with the last play symbol
    String streak = String.format("%c%c%c%c", sym, sym, sym, sym);

    // check if streak is in row, col, 
    // diagonal or backslash diagonal
    return contains(horizontal(), streak) || 
           contains(vertical(), streak) || 
           contains(slashDiagonal(), streak) || 
           contains(backslashDiagonal(), streak);
  }

  // prompts the user for a column, repeating until a valid choice is made
  public void chooseAndDrop(char symbol, Scanner input) {
    do {
      System.out.println("\nPlayer " + symbol + " turn: ");
      int col = input.nextInt();

      // check if column is ok
      if (!(0 <= col && col < width)) {
        System.out.println("Column must be between 0 and " + (width - 1));
        continue;
      }

      // now we can place the symbol to the first 
      // available row in the asked column
      for (int h = height - 1; h >= 0; h--) {
        if (grid[h][col] == '.') {
          grid[lastTop = h][lastCol = col] = symbol;
          return;
        }
      }

      // if column is full ==> we need to ask for a new input
      System.out.println("Column " + col + " is full.");
    } while (true);
  }

  public static void main(String[] args) {
    // we assemble all the pieces of the puzzle for 
    // building our Connect Four Game
    try (Scanner input = new Scanner(System.in)) {
      // we define some variables for our game like 
      // dimensions and nb max of moves
      int height = 6; int width = 8; int moves = height * width;

      // we create the ConnectFour instance
      ConnectFour board = new ConnectFour(width, height);

      // we explain users how to enter their choices
      System.out.println("Use 0-" + (width - 1) + " to choose a column");
      // we display initial board
      System.out.println(board);

      // we iterate until max nb moves be reached
      // simple trick to change player turn at each iteration
      for (int player = 0; moves-- > 0; player = 1 - player) {
        // symbol for current player
        char symbol = PLAYERS[player];

        // we ask user to choose a column
        board.chooseAndDrop(symbol, input);

        // we display the board
        System.out.println(board);

        // we need to check if a player won. If not, 
        // we continue, otherwise, we display a message
        if (board.isWinningPlay()) {
          System.out.println("\nPlayer " + symbol + " wins!");
          return;
        }
      }
 
      System.out.println("Game over. No winner. Try again!");
    }
  }

}
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// we are going to create a simple 2-players Connect Four implementation in Java 8
public class ConnectFour {

  // we define characters for players (R for Red, Y for Yellow)
  private static final char[] PLAYERS = {'R', 'Y'};
  // dimensions for our board
  private final int width, height;
  // grid for the board
  private final char[][] grid;
  // we store last move made by a player
  private int lastCol = -1, lastTop = -1;

  public ConnectFour(int w, int h) {
    width = w;
    height = h;
    grid = new char[h][];

    // init the grid will blank cell
    for (int i = 0; i < h; i++) {
      Arrays.fill(grid[i] = new char[w], '.');
    }
  }

  // we use Streams to make a more concise method 
  // for representing the board
  public String toString() {
    return IntStream.range(0,  width).
           mapToObj(Integer::toString).
           collect(Collectors.joining()) + 
           "\n" +
           Arrays.stream(grid).
           map(String::new).
           collect(Collectors.joining("\n"));
  }

  // get string representation of the row containing 
  // the last play of the user
  public String horizontal() {
    return new String(grid[lastTop]);
  }

  // get string representation fo the col containing 
  // the last play of the user
  public String vertical() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      sb.append(grid[h][lastCol]);
    }

    return sb.toString();
  }

  // get string representation of the "/" diagonal 
  // containing the last play of the user
  public String slashDiagonal() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      int w = lastCol + lastTop - h;

      if (0 <= w && w < width) {
        sb.append(grid[h][w]);
      }
    }

    return sb.toString();
  }

  // get string representation of the "\" 
  // diagonal containing the last play of the user
  public String backslashDiagonal() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      int w = lastCol - lastTop + h;

      if (0 <= w && w < width) {
        sb.append(grid[h][w]);
      }
    }

    return sb.toString();
  }

  // static method checking if a substring is in str
  public static boolean contains(String str, String substring) {
    return str.indexOf(substring) >= 0;
  }

  // now, we create a method checking if last play is a winning play
  public boolean isWinningPlay() {
    if (lastCol == -1) {
      System.err.println("No move has been made yet");
      return false;
    }

    char sym = grid[lastTop][lastCol];
    // winning streak with the last play symbol
    String streak = String.format("%c%c%c%c", sym, sym, sym, sym);

    // check if streak is in row, col, 
    // diagonal or backslash diagonal
    return contains(horizontal(), streak) || 
           contains(vertical(), streak) || 
           contains(slashDiagonal(), streak) || 
           contains(backslashDiagonal(), streak);
  }

  // prompts the user for a column, repeating until a valid choice is made
  public void chooseAndDrop(char symbol, Scanner input) {
    do {
      System.out.println("\nPlayer " + symbol + " turn: ");
      int col = input.nextInt();

      // check if column is ok
      if (!(0 <= col && col < width)) {
        System.out.println("Column must be between 0 and " + (width - 1));
        continue;
      }

      // now we can place the symbol to the first 
      // available row in the asked column
      for (int h = height - 1; h >= 0; h--) {
        if (grid[h][col] == '.') {
          grid[lastTop = h][lastCol = col] = symbol;
          return;
        }
      }

      // if column is full ==> we need to ask for a new input
      System.out.println("Column " + col + " is full.");
    } while (true);
  }

  public static void main(String[] args) {
    // we assemble all the pieces of the puzzle for 
    // building our Connect Four Game
    try (Scanner input = new Scanner(System.in)) {
      // we define some variables for our game like 
      // dimensions and nb max of moves
      int height = 6; int width = 8; int moves = height * width;

      // we create the ConnectFour instance
      ConnectFour board = new ConnectFour(width, height);

      // we explain users how to enter their choices
      System.out.println("Use 0-" + (width - 1) + " to choose a column");
      // we display initial board
      System.out.println(board);

      // we iterate until max nb moves be reached
      // simple trick to change player turn at each iteration
      for (int player = 0; moves-- > 0; player = 1 - player) {
        // symbol for current player
        char symbol = PLAYERS[player];

        // we ask user to choose a column
        board.chooseAndDrop(symbol, input);

        // we display the board
        System.out.println(board);

        // we need to check if a player won. If not, 
        // we continue, otherwise, we display a message
        if (board.isWinningPlay()) {
          System.out.println("\nPlayer " + symbol + " wins!");
          return;
        }
      }
 
      System.out.println("Game over. No winner. Try again!");
    }
  }

}
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// we are going to create a simple 2-players Connect Four implementation in Java 8
public class ConnectFour {

  // we define characters for players (R for Red, Y for Yellow)
  private static final char[] PLAYERS = {'R', 'Y'};
  // dimensions for our board
  private final int width, height;
  // grid for the board
  private final char[][] grid;
  // we store last move made by a player
  private int lastCol = -1, lastTop = -1;

  public ConnectFour(int w, int h) {
    width = w;
    height = h;
    grid = new char[h][];

    // init the grid will blank cell
    for (int i = 0; i < h; i++) {
      Arrays.fill(grid[i] = new char[w], '.');
    }
  }

  // we use Streams to make a more concise method 
  // for representing the board
  public String toString() {
    return IntStream.range(0,  width).
           mapToObj(Integer::toString).
           collect(Collectors.joining()) + 
           "\n" +
           Arrays.stream(grid).
           map(String::new).
           collect(Collectors.joining("\n"));
  }

  // get string representation of the row containing 
  // the last play of the user
  public String horizontal() {
    return new String(grid[lastTop]);
  }

  // get string representation fo the col containing 
  // the last play of the user
  public String vertical() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      sb.append(grid[h][lastCol]);
    }

    return sb.toString();
  }

  // get string representation of the "/" diagonal 
  // containing the last play of the user
  public String slashDiagonal() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      int w = lastCol + lastTop - h;

      if (0 <= w && w < width) {
        sb.append(grid[h][w]);
      }
    }

    return sb.toString();
  }

  // get string representation of the "\" 
  // diagonal containing the last play of the user
  public String backslashDiagonal() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      int w = lastCol - lastTop + h;

      if (0 <= w && w < width) {
        sb.append(grid[h][w]);
      }
    }

    return sb.toString();
  }

  // static method checking if a substring is in str
  public static boolean contains(String str, String substring) {
    return str.indexOf(substring) >= 0;
  }

  // now, we create a method checking if last play is a winning play
  public boolean isWinningPlay() {
    if (lastCol == -1) {
      System.err.println("No move has been made yet");
      return false;
    }

    char sym = grid[lastTop][lastCol];
    // winning streak with the last play symbol
    String streak = String.format("%c%c%c%c", sym, sym, sym, sym);

    // check if streak is in row, col, 
    // diagonal or backslash diagonal
    return contains(horizontal(), streak) || 
           contains(vertical(), streak) || 
           contains(slashDiagonal(), streak) || 
           contains(backslashDiagonal(), streak);
  }

  // prompts the user for a column, repeating until a valid choice is made
  public void chooseAndDrop(char symbol, Scanner input) {
    do {
      System.out.println("\nPlayer " + symbol + " turn: ");
      int col = input.nextInt();

      // check if column is ok
      if (!(0 <= col && col < width)) {
        System.out.println("Column must be between 0 and " + (width - 1));
        continue;
      }

      // now we can place the symbol to the first 
      // available row in the asked column
      for (int h = height - 1; h >= 0; h--) {
        if (grid[h][col] == '.') {
          grid[lastTop = h][lastCol = col] = symbol;
          return;
        }
      }

      // if column is full ==> we need to ask for a new input
      System.out.println("Column " + col + " is full.");
    } while (true);
  }

  public static void main(String[] args) {
    // we assemble all the pieces of the puzzle for 
    // building our Connect Four Game
    try (Scanner input = new Scanner(System.in)) {
      // we define some variables for our game like 
      // dimensions and nb max of moves
      int height = 6; int width = 8; int moves = height * width;

      // we create the ConnectFour instance
      ConnectFour board = new ConnectFour(width, height);

      // we explain users how to enter their choices
      System.out.println("Use 0-" + (width - 1) + " to choose a column");
      // we display initial board
      System.out.println(board);

      // we iterate until max nb moves be reached
      // simple trick to change player turn at each iteration
      for (int player = 0; moves-- > 0; player = 1 - player) {
        // symbol for current player
        char symbol = PLAYERS[player];

        // we ask user to choose a column
        board.chooseAndDrop(symbol, input);

        // we display the board
        System.out.println(board);

        // we need to check if a player won. If not, 
        // we continue, otherwise, we display a message
        if (board.isWinningPlay()) {
          System.out.println("\nPlayer " + symbol + " wins!");
          return;
        }
      }
 
      System.out.println("Game over. No winner. Try again!");
    }
  }

}
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// we are going to create a simple 2-players Connect Four implementation in Java 8
public class ConnectFour {

  // we define characters for players (R for Red, Y for Yellow)
  private static final char[] PLAYERS = {'R', 'Y'};
  // dimensions for our board
  private final int width, height;
  // grid for the board
  private final char[][] grid;
  // we store last move made by a player
  private int lastCol = -1, lastTop = -1;

  public ConnectFour(int w, int h) {
    width = w;
    height = h;
    grid = new char[h][];

    // init the grid will blank cell
    for (int i = 0; i < h; i++) {
      Arrays.fill(grid[i] = new char[w], '.');
    }
  }

  // we use Streams to make a more concise method 
  // for representing the board
  public String toString() {
    return IntStream.range(0,  width).
           mapToObj(Integer::toString).
           collect(Collectors.joining()) + 
           "\n" +
           Arrays.stream(grid).
           map(String::new).
           collect(Collectors.joining("\n"));
  }

  // get string representation of the row containing 
  // the last play of the user
  public String horizontal() {
    return new String(grid[lastTop]);
  }

  // get string representation fo the col containing 
  // the last play of the user
  public String vertical() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      sb.append(grid[h][lastCol]);
    }

    return sb.toString();
  }

  // get string representation of the "/" diagonal 
  // containing the last play of the user
  public String slashDiagonal() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      int w = lastCol + lastTop - h;

      if (0 <= w && w < width) {
        sb.append(grid[h][w]);
      }
    }

    return sb.toString();
  }

  // get string representation of the "\" 
  // diagonal containing the last play of the user
  public String backslashDiagonal() {
    StringBuilder sb = new StringBuilder(height);

    for (int h = 0; h < height; h++) {
      int w = lastCol - lastTop + h;

      if (0 <= w && w < width) {
        sb.append(grid[h][w]);
      }
    }

    return sb.toString();
  }

  // static method checking if a substring is in str
  public static boolean contains(String str, String substring) {
    return str.indexOf(substring) >= 0;
  }

  // now, we create a method checking if last play is a winning play
  public boolean isWinningPlay() {
    if (lastCol == -1) {
      System.err.println("No move has been made yet");
      return false;
    }

    char sym = grid[lastTop][lastCol];
    // winning streak with the last play symbol
    String streak = String.format("%c%c%c%c", sym, sym, sym, sym);

    // check if streak is in row, col, 
    // diagonal or backslash diagonal
    return contains(horizontal(), streak) || 
           contains(vertical(), streak) || 
           contains(slashDiagonal(), streak) || 
           contains(backslashDiagonal(), streak);
  }

  // prompts the user for a column, repeating until a valid choice is made
  public void chooseAndDrop(char symbol, Scanner input) {
    do {
      System.out.println("\nPlayer " + symbol + " turn: ");
      int col = input.nextInt();

      // check if column is ok
      if (!(0 <= col && col < width)) {
        System.out.println("Column must be between 0 and " + (width - 1));
        continue;
      }

      // now we can place the symbol to the first 
      // available row in the asked column
      for (int h = height - 1; h >= 0; h--) {
        if (grid[h][col] == '.') {
          grid[lastTop = h][lastCol = col] = symbol;
          return;
        }
      }

      // if column is full ==> we need to ask for a new input
      System.out.println("Column " + col + " is full.");
    } while (true);
  }

  public static void main(String[] args) {
    // we assemble all the pieces of the puzzle for 
    // building our Connect Four Game
    try (Scanner input = new Scanner(System.in)) {
      // we define some variables for our game like 
      // dimensions and nb max of moves
      int height = 6; int width = 8; int moves = height * width;

      // we create the ConnectFour instance
      ConnectFour board = new ConnectFour(width, height);

      // we explain users how to enter their choices
      System.out.println("Use 0-" + (width - 1) + " to choose a column");
      // we display initial board
      System.out.println(board);

      // we iterate until max nb moves be reached
      // simple trick to change player turn at each iteration
      for (int player = 0; moves-- > 0; player = 1 - player) {
        // symbol for current player
        char symbol = PLAYERS[player];

        // we ask user to choose a column
        board.chooseAndDrop(symbol, input);

        // we display the board
        System.out.println(board);

        // we need to check if a player won. If not, 
        // we continue, otherwise, we display a message
        if (board.isWinningPlay()) {
          System.out.println("\nPlayer " + symbol + " wins!");
          return;
        }
      }
 
      System.out.println("Game over. No winner. Try again!");
    }
  }

}

i hope you understood the concept well. if you did, please click on the 'like' button.

Also if you have any doubt regarding any concept taught above, do mention in the comments. i will try to answer it as soon as possible.


Related Solutions

Create a two-dimensional array A using random integers from 1 to 10. Create a two-dimensional array B using random integers from -10 to 0.
This program is for C.Create a two-dimensional array A using random integers from 1 to 10. Create a two-dimensional array B using random integers from -10 to 0. Combine the elements of A + B to create two- dimensional array C = A + B. Display array A, B and C to the screen for comparison. (Note a[0] + b[0] = c[0], a[1] + b[1] = c[1], etc.)
Imagine we are using a two-dimensional array as the basis for creating the game battleship. In...
Imagine we are using a two-dimensional array as the basis for creating the game battleship. In the game of battleship a '~' character entry in the array represents ocean (i.e., not a ship), a '#' character represents a place in the ocean where part of a ship is present, and an 'H' character represents a place in the ocean where part of a ship is present and has been hit by a torpedo. Thus, a ship with all 'H' characters...
C++ ASSIGNMENT: Two-dimensional array Problem Write a program that create a two-dimensional array initialized with test...
C++ ASSIGNMENT: Two-dimensional array Problem Write a program that create a two-dimensional array initialized with test data. The program should have the following functions: getTotal - This function should accept two-dimensional array as its argument and return the total of all the values in the array. getAverage - This function should accept a two-dimensional array as its argument and return the average of values in the array. getRowTotal - This function should accept a two-dimensional array as its first argument...
How to create a two-dimensional array, initializing elements in the array and access an element in...
How to create a two-dimensional array, initializing elements in the array and access an element in the array using PHP, C# and Python? Provide code examples for each of these programming languages. [10pt] PHP C# Python Create a two-dimensional array Initializing elements in the array Access an element in the array
you will create a dynamic two dimensional array of mult_div_values structs (defined below). The two dimensional...
you will create a dynamic two dimensional array of mult_div_values structs (defined below). The two dimensional array will be used to store the rows and columns of a multiplication and division table. Note that the table will start at 1 instead of zero, to prevent causing a divide-by-zero error in the division table! struct mult_div_values { int mult; float div; }; The program needs to read the number of rows and columns from the user as command line arguments. You...
In C++ using a single dimensional array Create a program that uses a for loop to...
In C++ using a single dimensional array Create a program that uses a for loop to input the day, the high temperature, and low temperature for each day of the week. The day, high, and low will be placed into three elements of the array. For each loop the day, high, and low will be placed into the next set of elements of the array. After the days and temps for all seven days have been entered into the array,...
In JAVA Use a two-dimensional array to solve the following problem: A company has four salespeople...
In JAVA Use a two-dimensional array to solve the following problem: A company has four salespeople - Sales Person 1, Sales Person 2, Sales Person 3, and Sales Person 4. The company sells 5 products - Product 1, Product 2, Product 3, Product 4, and Product 5. Each day, a sales person hands in a slip with the following information: Sales Person Number (1,2,3, or 4), Product Number (1,2,3,4, or 5), and dollar value of that product sold. This dollar...
Create a class called “Array” that implements a fixed-sized two-dimensional array of floating-point numbers.
Programing in Scala language: Create a class called “Array” that implements a fixed-sized two-dimensional array of floating-point numbers. Write separate methods to get an element (given parametersrow and col), set an element (given parametersrow, col, and value), and output the matrix to the console formatted properly in rows and columns. Next, provide an immutable method to perform array addition given two same-sized array.
In C, build a connect 4 game with no GUI. Use a 2D array as the...
In C, build a connect 4 game with no GUI. Use a 2D array as the Data structure. First, build the skeleton of the game. Then, build the game. Some guidelines include... SKELETON: Connect Four is a game that alternates player 1 and player 2. You should keep track of whose turn it is next. Create functions: Initialization – print “Setting up the game”. Ask each player their name. Teardown – print “Destroying the game” Accept Input – accept a...
JAVA LANGUAGE Write a program that declares a 2-Dimensional Array with 4 rows and 4 columns...
JAVA LANGUAGE Write a program that declares a 2-Dimensional Array with 4 rows and 4 columns to store integer values, and then: fill elements with values as the sum of its column index and row index, e.g., the element at row index 0 and column index 0 is (0+0=0), the element at row index 0 and column index 1 is (0+1=1). compute the sum of elements at the second row. compute the sum of elements at the third column. compute...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT