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
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...
1.Write the java code to create a two dimensional String array of sizes 12 by 8;...
1.Write the java code to create a two dimensional String array of sizes 12 by 8; Given the java array:       double[] test = new double[3]; 2.  Write the java code to put the numbers 1.0, 2.0, and 3.0 in to the array so that the 1.0 goes in the first cell, the 2.0 goes in the second cell and the 3.0 goes in the third cell. 3. Can you have different types of data is a three dimensional array? 4....
Create a “Main” method that contains two 2-Dimensional arrays of characters. The first array, which we...
Create a “Main” method that contains two 2-Dimensional arrays of characters. The first array, which we will call our visible field, needs to be 5 by 5 and should initially hold the underscore character “_”.  This will be used in our game of minesweeper to represent the possible locations the player can check. The second array, which we will call our hidden field, should also be 5 by 5 but filled with the capital letter "S” which means safety. However, we...
I'm having trouble programming connect four board game using linked lists, sets and maps in c++....
I'm having trouble programming connect four board game using linked lists, sets and maps in c++. Can you code connect four game using these concepts.
Pandas exercises: 1. Write a python program using Pandas to create and display a one-dimensional array-like...
Pandas exercises: 1. Write a python program using Pandas to create and display a one-dimensional array-like object containing an array of data. 2. Write a python program using Pandas to convert a Panda module Series to Python list and print it's type. (Hint: use ds.tolist() to convert the pandas series ds to a list) 3. Create a pandas dataframe called **my_df** with index as integer numbers between 0 to 10, first column (titled "rnd_int") as 10 integer random numbers between...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT