โปรแกรมเกม Connect 4
โจทย์
Connect 4 is a turn-based 2-player game played on a 6x7 board. Each player places their checkers from the lowest row until the highest one. The goal is to align four checkers horizontally, vertically, or diagonally.
The players are denoted as “Red” and “Yellow”. Your task is to write a program to return who is the winner (either “Red” or “Yellow”). The first player that can align four checkers is the winner.
The input consists of three parts: 1) a start player, 2) number of moves in the following list and 3) sequence of move in column number (ranged from 0-6) where a checker is dropped alternately between two players.
The output is the winner player returned as a String “Red” or “Yellow”. Noted that if the winner is found, the game must stop and no need to continue evaluating the board.
| Input | Output |
|---|---|
| Red 7 3 4 3 4 3 4 3 | Red |
| Yellow 7 0 1 0 1 0 1 0 | Yellow |
โค้ด
import java.util.*;
public class Program {
private static final int ROWS = 6;
private static final int COLS = 7;
private static char[][] board = new char[ROWS][COLS];
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String startPlayer = scanner.next();
int numMoves = scanner.nextInt();
int[] moves = new int[numMoves];
for (int i = 0; i < numMoves; i++) {
moves[i] = scanner.nextInt();
}
String winner = findWinner(startPlayer, moves);
System.out.println(winner);
}
private static String findWinner(String startPlayer, int[] moves) {
for (int i = 0; i < ROWS; i++) {
Arrays.fill(board[i], '.');
}
char red = 'R';
char yellow = 'Y';
char currentPlayer = startPlayer.equals("Red") ? red : yellow;
for (int move : moves) {
int row = dropPiece(move, currentPlayer);
if (row == -1) continue;
if (checkWinner(row, move, currentPlayer)) {
return currentPlayer == red ? "Red" : "Yellow";
}
currentPlayer = (currentPlayer == red) ? yellow : red;
}
return "No Winner";
}
private static int dropPiece(int col, char player) {
for (int row = ROWS - 1; row >= 0; row--) {
if (board[row][col] == '.') {
board[row][col] = player;
return row;
}
}
return -1;
}
private static boolean checkWinner(int row, int col, char player) {
return checkDirection(row, col, player, 1, 0) // Vertical
|| checkDirection(row, col, player, 0, 1) // Horizontal
|| checkDirection(row, col, player, 1, 1) // Diagonal (\)
|| checkDirection(row, col, player, 1, -1); // Diagonal (/)
}
private static boolean checkDirection(int row, int col, char player, int dRow, int dCol) {
int count = 1;
count += countConsecutive(row, col, player, dRow, dCol);
count += countConsecutive(row, col, player, -dRow, -dCol);
return count >= 4;
}
private static int countConsecutive(int row, int col, char player, int dRow, int dCol) {
int count = 0;
int r = row + dRow, c = col + dCol;
while (r >= 0 && r < ROWS && c >= 0 && c < COLS && board[r][c] == player) {
count++;
r += dRow;
c += dCol;
}
return count;
}
}