Exercises/chess/game/Game.java

110 lines
4.2 KiB
Java
Raw Permalink Normal View History

2025-02-26 10:09:45 +01:00
package de.vivi.chess.game;
import de.vivi.chess.board.Board;
import de.vivi.chess.board.Field;
import de.vivi.chess.pieces.Color;
import de.vivi.chess.pieces.Piece;
2025-03-01 16:04:59 +01:00
import java.util.Scanner;
2025-02-26 10:09:45 +01:00
2025-03-01 16:04:59 +01:00
import static de.vivi.chess.pieces.Color.BLACK;
2025-02-26 10:09:45 +01:00
import static de.vivi.chess.pieces.Color.WHITE;
public class Game {
private final Board board;
private Color player;
2025-03-01 16:04:59 +01:00
private int count = 0;
2025-02-26 10:09:45 +01:00
/**
* TODO: implement
*/
public Game() {
board = new Board();
player = null;
}
/**
* TODO: implement
* <p>
* Starts the game and should process the game like it is
* specified inside example-output.txt.
*/
public void play() {
2025-03-01 16:04:59 +01:00
System.out.println("Welcome to Vivi's Chess Game!");
System.out.println(board);
player = ((count % 2) == 0) ? WHITE : BLACK;
System.out.println("It is white's turn: [from:to]");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
scanner.useDelimiter(":\\s*");
String fromString = scanner.nextLine();
char[] arrayInRange = fromString.toCharArray();
if ((arrayInRange[0] == 'A' ||
arrayInRange[0] == 'B' ||
arrayInRange[0] == 'C' ||
arrayInRange[0] == 'D' ||
arrayInRange[0] == 'E' ||
arrayInRange[0] == 'F' ||
arrayInRange[0] == 'G' ||
arrayInRange[0] == 'H' ) &&
(arrayInRange[1] == '0' ||
arrayInRange[1] == '1' ||
arrayInRange[1] == '2' ||
arrayInRange[1] == '3' ||
arrayInRange[1] == '4' ||
arrayInRange[1] == '5' ||
arrayInRange[1] == '6' ||
arrayInRange[1] == '7' ||
arrayInRange[1] == '8' )) {
StringBuilder sb=new StringBuilder(fromString);
int l=sb.length();
if (l == 2) {
String toString = scanner.nextLine();
Field from = Field.fromString(fromString);
Field to = Field.fromString(toString);
if (player == WHITE && board.getPiece(from).getColor() == WHITE) {
if (board.getPiece(from).isValidMove(board, from,to)) {
//System.out.println(board.getPiece(from).isValidMove(board, from,to));
count++;
board.move(from, to);
System.out.println("Moving white " + board.getPiece(to).getType()
+ " from " + fromString + " to " + toString);
}
System.out.println(board);
} else if (player == BLACK && board.getPiece(from).getColor() == BLACK) {
if (board.getPiece(from).isValidMove(board, from,to)) {
count++;
board.move(from, to);
System.out.println("Moving black " + board.getPiece(to).getType()
+ " from " + fromString + " to " + toString);
}
System.out.println(board);
} else {
System.err.println("Illegal move, try again: ");
}
player = ((count % 2) == 0) ? WHITE : BLACK;
if (player == BLACK) {
System.out.println("It is black's turn: [from:to]");
} else {
System.out.println("It is white's turn: [from:to]");
}
} else {
System.err.println("Illegal move, try again: ");
}
} else
System.err.println("Illegal move, try again: ");
}
2025-02-26 10:09:45 +01:00
}
}