//JAVA PROGRAM FOR CONNECT 4 GAME
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!");
}
}
}
Create a connect four board game in java. Use multiple methods and 2d arrays. The purpose...
Code in JAVA You are asked to implement “Connect 4” which is a two player game. The game will be demonstrated in class. The game is played on a 6x7 grid, and is similar to tic-tac-toe, except that instead of getting three in a row, you must get four in a row. To take your turn, you choose a column, and slide a checker of your color into the column that you choose. The checker drops into the slot, falling...
Create a game of Hangman that will use arrays, loops, user-defined methods, recursion, inheritance, objects and classes, input/output, memory management. All has to be compiled as one java code.
For this exercise, you will complete the TicTacToe Board that we started in the 2D Arrays Lesson. We will add a couple of methods to the TicTacToe class. To track whose turn it is, we will use a counter turn. This is already declared as a private instance variable. Create a getTurn method that returns the value of turn. Other methods to implement: printBoard()- This method should print the TicTacToe array onto the console. The board should include numbers that...
Must use JOPTIONPANE. Using arrays and methods create a JAVA program. Create a java program that holds an array for the integer values 1-10. Pass the array to a method that will calculate the values to the power of 2 of each element in the array. Then return the list of calculated values back to the main method and print the values
Connect 4 is a 2 player game where each player has a set of colored tokens (red or yellow). Players take turns during which they place a single token into one of the columns of an n by m grid (where n is the number of rows and m is the number of columns. They place their token into a slot at the top of the column and it falls into the lowest unoccupied slot in that column. A player...
Use Java language to create this program Write a program that allows two players to play a game of tic-tac-toe. Using a two-dimensional array with three rows and three columns as the game board. Each element of the array should be initialized with a number from 1 - 9 (like below): 1 2 3 4 5 6 7 8 9 The program should run a loop that Displays the contents of the board array allows player 1 to select the...
I need help writing a Java program for a game of TicTacToe. It is a two player game, and the rules are as follows: 1. The game begins with an empty, 3 × 3 grid. 2. The two players then take turns placing a mark in an empty grid cell. Player O will use the ‘O’ (letter ‘O’, not zero) mark and Player X will use the ‘X’ mark. Player O moves first. 3. The game is over in either...
c++ help please!
Create a 2D character array in your main function and
use nested for loops to fill the array with the letter ‘e’ to
represent empty spaces.
Create a function to print the board on the screen using
a nested for loop. The function header is:
void printBoard (char board [][3])
Create a function that checks whether a particular space
has already been filled. If the space is filled it returns a
boolean value of true, otherwise false....
Question 3: A smaller version of Connect 4 is played on a vertical board 3-row high and 3-column wide. The two players Maxim and Minnie alternately drop a black and white disc, respectively, from the top of any column, and it will fall to the lowest open row. A player wins when three of his/her discs are aligned either horizontally, vertically, or diagonally; otherwise the game is a draw. Consider the sample game below, where the first four moves have...
The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the other opponent cannot see them. In order to attack, each player takes turns calling out coordinates on a grid. If the attacker calls out a coordinate that hits their opponent's ship, they must call out, "Hit." You are going to be developing a computer program to mimic this game. Use the Gridlayout that is six columns by six...