Files
oopuebung/uebung09/src/chess/ChessApp.java
2025-06-12 11:59:41 +02:00

96 lines
3.3 KiB
Java

package chess;
import java.io.InputStream;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class ChessApp {
private static final String HELP = "h";
private static final String CHECK = "c";
private static final String ABORT = "a";
private static final String WHITE_QUEEN = "q";
private static final String BLACK_QUEEN = "Q";
private static final String WHITE_KNIGHT = "n";
private static final String BLACK_KNIGHT = "N";
private static final String ITERATOR = "i";
private final Scanner scanner;
private final Board board;
public static void main(String[] args) {
new ChessApp(System.in, new Board()).playChess();
}
private ChessApp(InputStream in, Board board) {
scanner = new Scanner(in);
this.board = board;
}
private void playChess() {
board.printBoard();
commandLoop();
System.out.println("Terminated");
}
private void commandLoop() {
while (true) {
System.out.printf("Type in command (%s for help):%n", HELP);
try {
final String command = scanner.next();
if (ABORT.equals(command)) return;
switch (command) {
case HELP -> help();
case CHECK -> board.check();
case BLACK_QUEEN -> addQueen(Color.black);
case WHITE_QUEEN -> addQueen(Color.white);
case BLACK_KNIGHT -> addKnight(Color.black);
case WHITE_KNIGHT -> addKnight(Color.white);
case ITERATOR -> iterate();
default -> System.out.println("Invalid command " + command);
}
}
catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
catch (NoSuchElementException ex) {
return;
}
}
}
private void addKnight(Color color) {
final int row = scanner.nextInt();
final int col = scanner.nextInt();
new Knight(color, board, row, col);
board.printBoard();
}
private void addQueen(Color color) {
final int row = scanner.nextInt();
final int col = scanner.nextInt();
new Queen(color, board, row, col);
board.printBoard();
}
private void iterate() {
final Iterator<Piece> it = board.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
private void help() {
System.out.println("Commands:");
System.out.println(ABORT + ": terminate the program");
System.out.println(CHECK + ": check the pieces on the board");
System.out.println(WHITE_KNIGHT + " <int> <int>: place a new white knight at specified position");
System.out.println(BLACK_KNIGHT + " <int> <int>: place a new black knight at specified position");
System.out.println(WHITE_QUEEN + " <int> <int>: place a new white queen at specified position");
System.out.println(BLACK_QUEEN + " <int> <int>: place a new black queen at specified position");
System.out.println(ITERATOR + ": iterate over the board and print all pieces to the console");
}
}