What's new

Java Pahelp naman po sa chess game

Aircon

Forum Guru
Elite
Joined
Jun 1, 2018
Posts
1,296
Reaction
6,066
Points
1,130
pahelp naman po sa code ko yung method ng logic moves ng mga piece is okay na ang problem ko po is papaano yung correct code for this para magkaroon ng winner at maicheck yung kings ?


import java.util.Scanner;

public class Chess2 {
private static final int BOARD_SIZE = 8;
private static char[][] board = new char[BOARD_SIZE][BOARD_SIZE];
private static char[][] cellColors = new char[BOARD_SIZE][BOARD_SIZE];
private static char[][] marks = new char[BOARD_SIZE][BOARD_SIZE];
private static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
initializeBoard();
printBoard();

while (true) {
playerMove("White");
if (isGameOver("White")) {
System.out.println("Game over. White wins!");
break;
}

playerMove("Black");
if (isGameOver("Black")) {
System.out.println("Game over. Black wins!");
break;
}
}

scanner.close();
}

private static void initializeBoard() {
// Initialize the chess board with pieces in their starting positions
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[j] = 0;
cellColors[j] = (i + j) % 2 == 0 ? 'W' : 'B'; // 'W' for white, 'B' for black
marks[j] = '-';
}
}

// Example initialization:
placePiece('R', 0, 0, "White"); // White rooks
placePiece('N', 0, 1, "White"); // White knights
placePiece('B', 0, 2, "White"); // White bishops
placePiece('Q', 0, 3, "White"); // White queen
placePiece('K', 0, 4, "White"); // White king
placePiece('B', 0, 5, "White");
placePiece('N', 0, 6, "White");
placePiece('R', 0, 7, "White");

placePiece('r', 7, 0, "Black"); // Black rooks
placePiece('n', 7, 1, "Black"); // Black knights
placePiece('b', 7, 2, "Black"); // Black bishops
placePiece('q', 7, 3, "Black"); // Black queen
placePiece('k', 7, 4, "Black"); // Black king
placePiece('b', 7, 5, "Black");
placePiece('n', 7, 6, "Black");
placePiece('r', 7, 7, "Black");

for (int i = 0; i < BOARD_SIZE; i++) {
placePiece('P', 1, i, "White"); // White pawns
placePiece('p', 6, i, "Black"); // Black pawns
}
}

private static void printBoard() {
// Print the current state of the chess board with ranks
System.out.println("\n a b c d e f g h");
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.print((8 - i) + " ");
for (int j = 0; j < BOARD_SIZE; j++) {
char piece = board[j];
char color = cellColors[j];

System.out.print(color == 'W' ? "[" : "{"); // Use '[' for white cells, '{' for black cells
System.out.print(piece != 0 ? piece : marks[j]); // Print piece or mark
System.out.print(color == 'W' ? "]" : "}"); // Use ']' for white cells, '}' for black cells
System.out.print(" ");
}
System.out.println();
}
}


private static void playerMove(String player) {
while (true) {
System.out.println("");
System.out.println("BLACK : BIG LETTERS , WHITE : SMALL LETTERS ");
System.out.println(player + "'s move (example move : a2-a4): ");
String move = scanner.nextLine().toLowerCase();

if (isValidMove(move, player)) {
makeMove(move);
printBoard();
break;
} else {
System.out.println("Invalid move. Try again.");
}
}
}

private static boolean isValidMove(String move, String player) {
if (isValidMoveSyntax(move)) {
int fromRow = 8 - Character.getNumericValue(move.charAt(1));
int fromCol = move.charAt(0) - 'a';
int toRow = 8 - Character.getNumericValue(move.charAt(4));
int toCol = move.charAt(3) - 'a';

char piece = board[fromRow][fromCol];
char targetPiece = board[toRow][toCol];

// Check if the target cell is occupied by an ally piece
if (Character.isUpperCase(piece) && Character.isUpperCase(targetPiece)) {
System.out.println("You cannot eat your own piece.");
return false;
} else if (Character.isLowerCase(piece) && Character.isLowerCase(targetPiece)) {
System.out.println("You cannot eat your own piece.");
return false;
}

// Check the specific rules for each piece
switch (Character.toUpperCase(piece)) {
case 'P':
return isValidPawnMove(fromRow, fromCol, toRow, toCol, player);
case 'R':
return isValidRookMove(fromRow, fromCol, toRow, toCol);
case 'N':
return isValidKnightMove(fromRow, fromCol, toRow, toCol);
case 'B':
return isValidBishopMove(fromRow, fromCol, toRow, toCol);
case 'Q':
return isValidQueenMove(fromRow, fromCol, toRow, toCol);
case 'K':
return isValidKingMove(fromRow, fromCol, toRow, toCol);
default:
// Invalid piece type
return false;
}
} else {
return false;
}
}

private static boolean isValidMoveSyntax(String move) {
// Validate the syntax of the move
return move.matches("[a-h][1-8]-[a-h][1-8]");
}

private static void makeMove(String move) {
// Update the board based on the user's move
int fromRow = 8 - Character.getNumericValue(move.charAt(1));
int fromCol = move.charAt(0) - 'a';
int toRow = 8 - Character.getNumericValue(move.charAt(4));
int toCol = move.charAt(3) - 'a';

char piece = board[fromRow][fromCol];
board[fromRow][fromCol] = 0;
board[toRow][toCol] = piece;

// Mark the destination cell based on its color
marks[toRow][toCol] = (cellColors[toRow][toCol] == 'W') ? 'X' : 'O';
}

private static boolean isGameOver(String player) {
// Check if the game is over for the specified player (e.g., checkmate, stalemate)

if (isCheckmate(player)) {
System.out.println("Checkmate! " + player + " wins!");
return true;
} else if (isStalemate(player)) {
System.out.println("Stalemate! The game is a draw.");
return true;
}

return false;
}

private static boolean isCheckmate(String player) {
// Check if the player's king is in checkmate
return isKingChecked(player) && isNoLegalMoves(player);
}

private static boolean isStalemate(String player) {
// Check if the player is in stalemate
return !isKingChecked(player) && isNoLegalMoves(player);
}

private static boolean isKingChecked(String player) {
// Implement this method based on your existing logic
// Example: Check if the king of the specified player is in check
// This is a placeholder; replace it with your logic
return false;
}

private static boolean isNoLegalMoves(String player) {
// Implement this method based on your existing logic
// Example: Check if the player has no legal moves
// This is a placeholder; replace it with your logic
return false;
}

private static void placePiece(char piece, int row, int col, String player) {
if (player.equalsIgnoreCase("White")) {
board[row][col] = piece;
} else if (player.equalsIgnoreCase("Black")) {
board[row][col] = Character.toLowerCase(piece);
}
}

private static boolean isValidPawnMove(int fromRow, int fromCol, int toRow, int toCol, String player) {
// Pawn movement rules
int direction = (player.equalsIgnoreCase("White")) ? -1 : 1;

// Moving forward
if (fromCol == toCol && board[toRow][toCol] == 0) {
if (fromRow + direction == toRow) {
return true;
}
// First move option
if ((player.equalsIgnoreCase("White") && fromRow == 6) || (player.equalsIgnoreCase("Black") && fromRow == 1)) {
if (fromRow + 2 * direction == toRow) {
return true;
}
}
}

// Capturing diagonally
if (Math.abs(fromCol - toCol) == 1 && fromRow + direction == toRow) {
char targetPiece = board[toRow][toCol];
return (targetPiece != 0 && Character.isLowerCase(targetPiece) == player.equalsIgnoreCase("White"));
}

return false;
}

private static boolean isValidRookMove(int fromRow, int fromCol, int toRow, int toCol) {
// Rook movement rules
if (fromRow == toRow || fromCol == toCol) {
// Horizontal or vertical movement
int step = (fromRow == toRow) ? (toCol > fromCol ? 1 : -1) : (toRow > fromRow ? 1 : -1);

for (int i = fromRow + step; i != toRow; i += step) {
if (board[toCol] != 0) {
return false; // Path is blocked
}
}
return true;
}
return false; // Invalid movement
}

private static boolean isValidKnightMove(int fromRow, int fromCol, int toRow, int toCol) {
// Knight movement rules
int rowDiff = Math.abs(toRow - fromRow);
int colDiff = Math.abs(toCol - fromCol);
return (rowDiff == 2 && colDiff == 1) || (rowDiff == 1 && colDiff == 2);
}

private static boolean isValidBishopMove(int fromRow, int fromCol, int toRow, int toCol) {
// Bishop movement rules
if (Math.abs(toRow - fromRow) == Math.abs(toCol - fromCol)) {
int rowStep = (toRow > fromRow) ? 1 : -1;
int colStep = (toCol > fromCol) ? 1 : -1;

for (int i = 1; i < Math.abs(toRow - fromRow); i++) {
if (board[fromRow + i * rowStep][fromCol + i * colStep] != 0) {
return false; // Path is blocked
}
}
return true;
}
return false; // Invalid movement
}

private static boolean isValidQueenMove(int fromRow, int fromCol, int toRow, int toCol) {
// Queen movement rules (combination of rook and bishop)
return isValidRookMove(fromRow, fromCol, toRow, toCol) || isValidBishopMove(fromRow, fromCol, toRow, toCol);
}

private static boolean isValidKingMove(int fromRow, int fromCol, int toRow, int toCol) {
// King movement rules
int rowDiff = Math.abs(toRow - fromRow);
int colDiff = Math.abs(toCol - fromCol);
return (rowDiff <= 1 && colDiff <= 1);
}
}
 
To add the logic for checking if there is a winner and checking the kings, you can modify the isGameOver method and add the isKingChecked and isNoLegalMoves methods.

Here's an updated version of the code with the modifications:

```java
import java.util.Scanner;

public class Chess2 {
private static final int BOARD_SIZE = 8;
private static char[][] board = new char[BOARD_SIZE][BOARD_SIZE];
private static char[][] cellColors = new char[BOARD_SIZE][BOARD_SIZE];
private static char[][] marks = new char[BOARD_SIZE][BOARD_SIZE];
private static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
initializeBoard();
printBoard();

while (true) {
playerMove("White");
if (isGameOver("White")) {
System.out.println("Game over. White wins!");
break;
}

playerMove("Black");
if (isGameOver("Black")) {
System.out.println("Game over. Black wins!");
break;
}
}

scanner.close();
}

private static void initializeBoard() {
// Initialize the chess board with pieces in their starting positions
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[j] = 0;
cellColors[j] = (i + j) % 2 == 0 ? 'W' : 'B'; // 'W' for white, 'B' for black
marks[j] = '-';
}
}

// Example initialization:
placePiece('R', 0, 0, "White"); // White rooks
placePiece('N', 0, 1, "White"); // White knights
placePiece('B', 0, 2, "White"); // White bishops
placePiece('Q', 0, 3, "White"); // White queen
placePiece('K', 0, 4, "White"); // White king
placePiece('B', 0, 5, "White");
placePiece('N', 0, 6, "White");
placePiece('R', 0, 7, "White");

placePiece('r', 7, 0, "Black"); // Black rooks
placePiece('n', 7, 1, "Black"); // Black knights
placePiece('b', 7, 2, "Black"); // Black bishops
placePiece('q', 7, 3, "Black"); // Black queen
placePiece('k', 7, 4, "Black"); // Black king
placePiece('b', 7, 5, "Black");
placePiece('n', 7, 6, "Black");
placePiece('r', 7, 7, "Black");

for (int i = 0; i < BOARD_SIZE; i++) {
placePiece('P', 1, i, "White"); // White pawns
placePiece('p', 6, i, "Black"); // Black pawns
}
}

private static void printBoard() {
// Print the current state of the chess board with ranks
System.out.println("\n a b c d e f g h");
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.print((8 - i) + " ");
for (int j = 0; j < BOARD_SIZE; j++) {
char piece = board[j];
char color = cellColors[j];

System.out.print(color == 'W' ? "[" : "{"); // Use '[' for white cells, '{' for black cells
System.out.print(piece != 0 ? piece : marks[j]); // Print piece or mark
System.out.print(color == 'W' ? "]" : "}"); // Use ']' for white cells, '}' for black cells
System.out.print(" ");
}
System.out.println();
}
}

private static void playerMove(String player) {
while (true) {
System.out.println("");
System.out.println("BLACK : BIG LETTERS , WHITE : SMALL LETTERS ");
System.out.println(player + "'s move (example move : a2-a4): ");
String move = scanner.nextLine().toLowerCase();

if (isValidMove(move, player)) {
makeMove(move);
printBoard();
break;
} else {
System.out.println("Invalid move. Try again.");
}
}
}

private static boolean isValidMove(String move, String player) {
if (isValidMoveSyntax(move)) {
int fromRow = 8 - Character.getNumericValue(move.charAt(1));
int fromCol = move.charAt(0) - 'a';
int toRow = 8 - Character.getNumericValue(move.charAt(4));
int toCol = move.charAt(3) - 'a';

char piece = board[fromRow][fromCol];
char targetPiece = board[toRow][toCol];

// Check if the target cell is occupied by an ally piece
if (Character.isUpperCase(piece) && Character.isUpperCase(targetPiece)) {
System.out.println("You cannot eat your own piece.");
return false;
} else if (Character.isLowerCase(piece) && Character.isLowerCase(targetPiece)) {
System.out.println("You cannot eat your own piece.");
return false;
}

// Check the specific rules for each piece
switch (Character.toUpperCase(piece)) {
case 'P':
return isValidPawnMove(fromRow, fromCol, toRow, toCol, player);
case 'R':
return isValidRookMove(fromRow, fromCol, toRow, toCol);
case 'N':
return isValidKnightMove(fromRow, fromCol, toRow, toCol);
case 'B':
return isValidBishopMove(fromRow, fromCol, toRow, toCol);
case 'Q':
return isValidQueenMove(fromRow,
 
Here is a simple way to check if the game is over (either by checkmate or stalemate), by checking if a king is present on the board for both players:


private static boolean isGameOver() {
// Check if there is a king for both black and white
boolean whiteKing = false;
boolean blackKing = false;
for (char[] row : board) {
for (char cell : row) {
if (cell == 'k' || cell == 'K') {
if (Character.isLowerCase(cell)) blackKing = true;
else whiteKing = true;
}
}
}
// Return true (game over) if either king is missing
if (!whiteKing) {
System.out.println("Game over. Black wins!");
return true;
}else if (!blackKing){
System.out.println("Game over. White wins!");
return true;
}
return false;
}
This will simply look for any king ('k' or 'K') on the board. If it is unable to find a king, it means that one player has won, returning true and ending the game.
Remember to update your main while loop:


while (!isGameOver()) {
playerMove("White");
playerMove("Black");
}

Note: This approach is simple, but it does not check for checkmate or stalemate where the king is not taken but the player has no legal moves. It checks for the condition where one King is gone. Implementing full chess rules including check, checkmate, castling, pawn promotion, and en passant is quite a bit more complex.

baka maka help
 

Similar threads

Back
Top