Illegal chess moves second edition

Language: Java

Task:

To create a chess board that updates, is shown on the screen, and can tell if an illegal move is being played or not. It does not assess check, checkmate, en passant or castling.

Parameters:

import java.util.Map;

public class Main {

    public static void main(String[] args) {

        //Set up the chess board creating an map called board that shows the square position of the pieces
        SetUp start = new SetUp();
        Map<String,String>board=start.getBoard();
        //Say whose move it is
        char whoseMove = 'w';
        ChangeBoard.printBoard(board);
        while (true) {
            //Player makes a move giving variables move.moveArray (e.g. e2e4), move.moveFrom (e.g. e2) and move.moveTo
            // (e.g. e4)
            MoveCreator move = new MoveCreator();
            if (!CheckIllegalMove.checker(board, whoseMove, move)){
                continue;
            }
            board = ChangeBoard.boardChanger(move, board);
            if (whoseMove == 'w'){
                whoseMove = 'b';
                System.out.println(whoseMove);
            }
            else {
                whoseMove = 'w';
                System.out.println(whoseMove);
            }
            ChangeBoard.printBoard(board);
        }
    }
}

public class SetUp {

    //class creates a HashMap that gives the piece on each square

    Map<String, String> board = new HashMap<String, String>();

    public SetUp() {

        board.put("a1", "wrook");
        board.put("a2", "wpawn");
        board.put("a3", "empty");
        board.put("a4", "empty");
        board.put("a5", "empty");
        board.put("a6", "empty");
        board.put("a7", "bpawn");
        board.put("a8", "brook");
        board.put("b1", "wknight");
        board.put("b2", "wpawn");
        board.put("b3", "empty");
        board.put("b4", "empty");
        board.put("b5", "empty");
        board.put("b6", "empty");
        board.put("b7", "bpawn");
        board.put("b8", "bknight");
        board.put("c1", "wbishop");
        board.put("c2", "wpawn");
        board.put("c3", "empty");
        board.put("c4", "empty");
        board.put("c5", "empty");
        board.put("c6", "empty");
        board.put("c7", "bpawn");
        board.put("c8", "bbishop");
        board.put("d1", "wqueen");
        board.put("d2", "wpawn");
        board.put("d3", "empty");
        board.put("d4", "empty");
        board.put("d5", "empty");
        board.put("d6", "empty");
        board.put("d7", "bpawn");
        board.put("d8", "bqueen");
        board.put("e1", "wking");
        board.put("e2", "wpawn");
        board.put("e3", "empty");
        board.put("e4", "empty");
        board.put("e5", "empty");
        board.put("e6", "empty");
        board.put("e7", "bpawn");
        board.put("e8", "bking");
        board.put("f1", "wbishop");
        board.put("f2", "wpawn");
        board.put("f3", "empty");
        board.put("f4", "empty");
        board.put("f5", "empty");
        board.put("f6", "empty");
        board.put("f7", "bpawn");
        board.put("f8", "bbishop");
        board.put("g1", "wknight");
        board.put("g2", "wpawn");
        board.put("g3", "empty");
        board.put("g4", "empty");
        board.put("g5", "empty");
        board.put("g6", "empty");
        board.put("g7", "bpawn");
        board.put("g8", "bknight");
        board.put("h1", "wrook");
        board.put("h2", "wpawn");
        board.put("h3", "empty");
        board.put("h4", "empty");
        board.put("h5", "empty");
        board.put("h6", "empty");
        board.put("h7", "bpawn");
        board.put("h8", "brook");

    }
    public Map<String,String>getBoard(){
        return board;
    }

}

public class MoveCreator {

    //When the move is made this class takes the moveArray list and creates variables that are the square the piece is
    //moving from and the square the piece is moving to.

    char[] moveArray = ChessMove.makeMove();
    String moveTo = MoveCreator.setMoveTo(moveArray);
    String moveFrom = MoveCreator.setMoveFrom(moveArray);

    public MoveCreator() {
    }

    public static String setMoveFrom(char[]moveArray) {
        StringBuilder tempFrom = new StringBuilder();
        tempFrom.append(moveArray[0]);
        tempFrom.append(moveArray[1]);
        String moveFrom = tempFrom.toString();

        return moveFrom;
    }

    public static String setMoveTo(char[]moveArray) {
        StringBuilder tempTo = new StringBuilder();
        tempTo.append(moveArray[2]);
        tempTo.append(moveArray[3]);
        String moveTo = tempTo.toString();

        return moveTo;
    }

}

import javax.swing.*;

public class ChessMove {

    public static char[] makeMove() {
        //Create loop to repeat process until a legal format is made.
        while (true){
        String move = JOptionPane.showInputDialog("What is your chess move? Please give it in the format b1-c3 (name and" +
                " number of square moved from, a hyphen, and the name and number of the square moved to.");
        move = move.toLowerCase();
        //Check to see if letters are between a and h, that numbers are between 1 and 8, that there is a hyphen in the
            //middle and there are five characters e.g. e2-e4
            int squareOne = Character.getNumericValue(move.charAt(0));
            int squareTwo = Character.getNumericValue(move.charAt(1));
            int squareThree = Character.getNumericValue(move.charAt(2));
            int squareFour = Character.getNumericValue(move.charAt(3));
            int squareFive = Character.getNumericValue(move.charAt(4));

        if (squareOne<10 || squareOne>17|| squareFour<10 || squareFour>17|| squareThree!=-1||
                move.length()<5 || move.length()>5 || squareTwo<1 || squareTwo>8 || squareFive<1 ||
                squareFive>8 || squareOne == squareFour && squareTwo == squareFive)
                {
                    //repeat process if the move is illegal
                    System.out.println("This is illegal");
                    System.out.println("Illegal move");
                    makeMove();
        }
        else {
            //create an array of the characters, removing hyphen
            char[]moveArray={move.charAt(0),move.charAt(1),move.charAt(3),move.charAt(4)};
            return moveArray;
        }
                }
    }
}

import java.util.Map;

public class CheckIllegalMove {
//This class checks the move to see whether it is legal or not

    public CheckIllegalMove(Map<String,String> board, char whoseMove, MoveCreator move){
    }

    public static boolean checker(Map<String,String> board, char whoseMove, MoveCreator move) {

        //Create boolean to represent whether the move is legal or not
        boolean legal = false;
        //runs checks if the piece is a rook
        if (board.get(move.moveFrom) == "wrook" || board.get(move.moveFrom) == "brook") {
            //runs check to see if it is moving in the correct direction
            if (!Rook.moveDirectionChecker(move.moveArray)) {
                System.out.println("Illegal move.");
                return false;
            } else if (!Rook.pieceJumpingChecker(move.moveArray, move, board, whoseMove)) {
                System.out.println("Illegal move.");
                return false;
            } else {
                return true;
            }
        }
        if (board.get(move.moveFrom) == "wbishop" || board.get(move.moveFrom) == "bbishop") {
            //runs check to see if it is moving in the correct direction
            if (!Bishop.moveDirectionChecker(move.moveArray)) {
                System.out.println("Illegal move.");
                return false;
            } else if (!Bishop.pieceJumpingChecker(move.moveArray, move, board, whoseMove)) {
                System.out.println("Illegal move.");
                return false;
            } else {
                return true;
            }
        }
        if (board.get(move.moveFrom) == "wqueen" || board.get(move.moveFrom) == "bqueen" ||
                board.get(move.moveFrom) == "wking" || board.get(move.moveFrom) == "bking") {
            //runs check to see if it is moving in the correct direction
            StringBuffer buffer = new StringBuffer(board.get(move.moveFrom));
            buffer.deleteCharAt(0);
            String piece = buffer.toString();
            if (!QueenAndKing.moveDirectionChecker(move.moveArray, piece)) {
                System.out.println("Illegal move.");
                return false;
            } else if (!QueenAndKing.pieceJumpingChecker(move.moveArray, move, board, whoseMove)) {
                System.out.println("Illegal move.");
                return false;
            } else {
                return true;
            }
        }
        if (board.get(move.moveFrom) == "wknight" || board.get(move.moveFrom) == "bknight") {
            //runs check to see if it is moving in the correct direction
            if (!Knight.moveDirectionChecker(move.moveArray)) {
                System.out.println("Illegal move.");
                return false;
            } else if (!Knight.examine(move, board, whoseMove)) {
                System.out.println("Illegal move.");
                return false;
            } else {
                return true;
            }
        }
        if (board.get(move.moveFrom) == "wpawn" || board.get(move.moveFrom) == "bpawn") {
            //runs check to see if it is moving in the correct direction
            if (!Pawn.moveDirectionChecker(move.moveArray, board, whoseMove)) {
                System.out.println("Illegal move.");
                return false;
            } else {
                return true;
            }
        }
        return true;
    }
}

import java.util.Map;

public class Bishop {
    //Class to check the move patterns of the bishop

    public Bishop() {
    }

    public static boolean moveDirectionChecker(char[] moveArray) {
        int squareOne = Character.getNumericValue(moveArray[0]) + 87;
        int squareTwo = Character.getNumericValue(moveArray[1]);
        int squareThree = Character.getNumericValue(moveArray[2]) + 87;
        int squareFour = Character.getNumericValue(moveArray[3]);
        int horizontalMoved = Math.abs(squareFour-squareTwo);
        //checks to see if the letter or the number has stayed the same
        if (squareOne + horizontalMoved!=squareThree && squareOne-horizontalMoved!=squareThree) {
            return false;
        }
        return true;
    }

    public static boolean pieceJumpingChecker(char[] moveArray, MoveCreator move, Map<String, String> board,
                                              char whoseMove) {
        //create numeric values for the characters to cut down code
        int squareOne = Character.getNumericValue(moveArray[0]) + 87;
        int squareTwo = Character.getNumericValue(moveArray[1]);
        int squareThree = Character.getNumericValue(moveArray[2]) + 87;
        int squareFour = Character.getNumericValue(moveArray[3]);
        //check to see if the bishop is moving left and down
        if (squareOne > squareThree && squareTwo > squareFour) {
            //loop through each square
            for (int i = squareTwo - 1; i >= squareFour; i--) {
                if (!examine(i, squareTwo, squareOne, squareThree, squareFour, board, whoseMove, move, "leftdown")){

                    return false;
                }
            }
        }
        //check to see if the bishop is moving left and up
        if (squareOne > squareThree && squareTwo < squareFour) {
            //loop through each square
            for (int i = squareTwo+1; i <= squareFour; i++) {
                if (!examine(i, squareTwo, squareOne, squareThree, squareFour, board, whoseMove, move, "leftup")){
                    System.out.println("ended here");

                    return false;
                }
            }
        }
        //check to see if the bishop is moving right and up
        if (squareOne < squareThree && squareTwo < squareFour) {
            //loop through each square
            for (int i = squareTwo + 1; i <= squareFour; i++) {
                if (!examine(i, squareTwo, squareOne, squareThree, squareFour, board, whoseMove, move, "rightup")){
                    System.out.println("ended here2");

                    return false;
                }
            }
        }
        //check to see if the bishop is moving right and down
        if (squareOne < squareThree && squareTwo>squareFour) {
            //loop through each square to see if (i) a piece is in the way and (ii) the piece landing on is not the
            //colour of the piece being moved
            //create square that i is currently on
            for (int i = squareTwo - 1; i >= squareFour; i--) {
                if (!examine(i, squareTwo, squareOne, squareThree, squareFour, board, whoseMove, move, "rightdown")){
                    System.out.println("ended here3");

                    return false;
                }
            }
        }
        return true;
    }

    public static boolean examine(int i, int squareTwo, int squareOne, int squareThree, int SquareFour,
                                  Map<String, String> board, char whoseMove, MoveCreator move,
                                  String direction) {
        //create a string of the square currently being  looked at as we work our way through. This will allow
        //us to check for pieces blocking the way etc
        StringBuilder sb = new StringBuilder();
        if ("leftdown".equals(direction)) {
            sb.append((char) (i+97));
            sb.append(i);
        }
        if ("leftup".equals(direction)) {
            sb.append((char) (((i-squareTwo)*-1)+102));
            sb.append(i);

        }
        if ("rightup".equals(direction)) {
            sb.append((char) (i+97));
            sb.append(i);
        }
        if ("rightdown".equals(direction)){
            sb.append((char) (((i-squareTwo)*-1)+102));
            sb.append(i);
        }
        String currentSquare = sb.toString();
        //create variables to make the if statement below easier. These include any piece that is on the square
        //and the colour of the piece on the square
        char colourOnSquare = (board.get(currentSquare)).charAt(0);
        //returns false (illegal move) if the current square the piece is going on is the same colour, has a
        //piece there but it is not the square they are trying to land on.
        if (colourOnSquare == whoseMove || colourOnSquare!=whoseMove && !move.moveTo.equals(currentSquare) &&
                colourOnSquare!='e'){
            return false;
        }
        return true;
    }
}

import java.util.Map;

public class Rook {
    //Class to check th move patterns of the rook

    public Rook() {
    }

    public static boolean moveDirectionChecker(char[] moveArray) {
        //checks to see if the letter or the number has stayed the same
        if (moveArray[0] != moveArray[2] && moveArray[1] != moveArray[3]) {
            return false;
        }
        return true;
    }

    public static boolean pieceJumpingChecker(char[] moveArray, MoveCreator move, Map<String, String> board,
                                              char whoseMove) {
        //create numeric values for the characters to cut down code
        int squareOne = Character.getNumericValue(moveArray[0]) + 87;
        int squareTwo = Character.getNumericValue(moveArray[1]);
        int squareThree = Character.getNumericValue(moveArray[2]) + 87;
        int squareFour = Character.getNumericValue(moveArray[3]);
        //check to see if the rook is moving left
        if (squareOne > squareThree) {
            //loop through each square
            for (int i = squareOne - 1; i >= squareThree; i--) {
                if (!examine(i, squareTwo, squareOne, board, whoseMove, move, "horizontal")){
                    return false;
                }
            }
        }
        //check to see if the rook is moving right
        if (squareThree > squareOne) {
            //loop through each square
            for (int i = squareOne + 1; i <= squareThree; i++) {
                if (!examine(i, squareTwo, squareOne, board, whoseMove, move, "horizontal")){
                    return false;
                }
            }
        }
        //check to see if the rook is moving up
        if (squareFour > squareTwo) {
            //loop through each square
            for (int i = squareTwo + 1; i <= squareFour; i++) {
                if (!examine(i, squareTwo, squareOne, board, whoseMove, move, "vertical")){
                    return false;
                }
            }
        }
        if (squareTwo > squareFour) {
            //loop through each square to see if (i) a piece is in the way and (ii) the piece landing on is not the
            //colour of the piece being moved
            //create square that i is currently on
            for (int i = squareTwo - 1; i >= squareFour; i--) {
                if (!examine(i, squareTwo, squareOne, board, whoseMove, move, "vertical")){
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean examine(int i, int squareTwo, int squareOne, Map<String, String> board, char whoseMove, MoveCreator move,
                                  String direction) {
        //create a string of the square currently being  looked at as we work our way through. This will allow
        //us to check for pieces blocking the way etc
        StringBuilder sb = new StringBuilder();
        if ("horizontal".equals(direction)) {
            sb.append((char) i);
            sb.append(squareTwo);
        }
        else{
            sb.append(move.moveFrom.charAt(0));
            sb.append(i);
        }
        String currentSquare = sb.toString();
        //create variables to make the if statement below easier. These include any piece that is on the square
        //and the colour of the piece on the square
        char colourOnSquare = (board.get(currentSquare)).charAt(0);
        //returns false (illegal move) if the current square the piece is going on is the same colour, has a
        //piece there but it is not the square they are trying to land on.
        if (colourOnSquare == whoseMove || colourOnSquare!=whoseMove && !move.moveTo.equals(currentSquare) &&
                colourOnSquare!='e'){
            return false;
        }
        return true;
    }
}

public class Pawn {
    //Class to check the move patterns of the pawn

    public Pawn() {
    }

    public static boolean moveDirectionChecker(char[] moveArray, Map<String, String> board, char whoseMove) {
        //checks to see if the letter or the number has stayed the same
        Integer distanceMovedHorizontal = Math.abs(Character.getNumericValue(moveArray[0]) -
                Character.getNumericValue(moveArray[2]));
        Integer distanceMovedVertical = Math.abs(Character.getNumericValue(moveArray[1]) -
                Character.getNumericValue(moveArray[3]));
        if (distanceMovedHorizontal > 0 && distanceMovedHorizontal != 1 || distanceMovedVertical > 2 ||
                distanceMovedVertical == 2 && Character.getNumericValue(moveArray[1]) != 2 && whoseMove=='w' ||
                distanceMovedVertical == 2 && Character.getNumericValue(moveArray[1]) != 7 && whoseMove=='b'||
                distanceMovedHorizontal > 1) {
            return false;
        }
        char opponentMove;
        Integer directionAddOn = 1;
        if (whoseMove == 'w') {
            opponentMove = 'b';
        } else {
            opponentMove = 'w';
            directionAddOn = -1;
        }
        //Create all squares that have to be checke
        StringBuilder sbOneInFront = new StringBuilder();
        sbOneInFront.append(moveArray[0]);
        sbOneInFront.append((char)((moveArray[1])+(1*directionAddOn)));
        String squareOneInFront = sbOneInFront.toString();
        StringBuilder sbTwoInFront = new StringBuilder();
        sbTwoInFront.append(moveArray[0]);
        sbTwoInFront.append((char)((moveArray[1])+(2*directionAddOn)));
        String squareTwoInFront = sbTwoInFront.toString();
        StringBuilder sbSquareTo = new StringBuilder();
        sbSquareTo.append(moveArray[2]);
        sbSquareTo.append(moveArray[3]);
        String squareTo = sbSquareTo.toString();
        StringBuilder sbOneDiagonalLeft = new StringBuilder();
        int a = 10;
        sbOneDiagonalLeft.append((char)(moveArray[0]-1));
        sbOneDiagonalLeft.append((char) (moveArray[1]+(1*directionAddOn)));
        String squareOneDiagonalLeft = sbOneDiagonalLeft.toString();
        StringBuilder sbOneDiagonalRight = new StringBuilder();
        sbOneDiagonalRight.append((char)(moveArray[0]+1));
        sbOneDiagonalRight.append((char) (moveArray[1]+(1*directionAddOn)));
        String squareOneDiagonalRight = sbOneDiagonalRight.toString();
        //Stop pawn moving diagonal unless it is an opponent's piece
        if (squareOneDiagonalLeft.equals(squareTo) && board.get(squareOneDiagonalLeft).charAt(0) != opponentMove) {

            return false;
        }
        if (squareOneDiagonalRight.equals(squareTo) && board.get(squareOneDiagonalRight).charAt(0) !=opponentMove){

            return false;
        }
        //stop pawn moving two squares unless it hasn't moved
        if (squareTo.equals(squareTwoInFront) && moveArray[1] != '2' && whoseMove=='w' ||
        squareTo.equals(squareTwoInFront) && moveArray[1] != '7' && whoseMove=='b' ){
            return false;
        }
        //stop pawn moving one square onto a square that contains their opponents piece
        if (squareTo.equals(squareOneInFront) && board.get(squareTo).charAt(0) != 'e') {
            return false;
        }
        //stop pawn moving two squares onto a square that contains their opponents piece
        if (squareTo.equals(squareTwoInFront) && board.get(squareTo).charAt(0) != 'e') {
            return false;
        }
        //stop the pawn moving two squares to jump over a piece
        if (squareTo.equals(squareTwoInFront) && board.get(squareOneInFront).charAt(0) != 'e') {
            return false;
        }
        return true;
    }
}
import java.util.Map;
import java.lang.Math;

public class QueenAndKing {
    
    //class to check the move patterns of the queen or king

    public QueenAndKing() {
    }

    public static boolean moveDirectionChecker(char[] moveArray,String piece) {
        Integer squareOne = Character.getNumericValue(moveArray[0]);
        Integer squareTwo = Character.getNumericValue(moveArray[1]);
        Integer squareThree = Character.getNumericValue(moveArray[2]);
        Integer squareFour = Character.getNumericValue(moveArray[3]);
        Integer distanceMovedHorizontal = Math.abs(squareOne-squareThree);
        Integer distanceMovedVertical = Math.abs(squareTwo-squareFour);
        if (piece == "king" && distanceMovedHorizontal == 1 || distanceMovedVertical ==1 && piece == "king"){
            return true;
        }
        else if (piece == "king"){
            return false;
        }
        //Use both rook and bishop move direction checkers to check direction
        if (!Rook.moveDirectionChecker(moveArray) && !Bishop.moveDirectionChecker(moveArray)){
            return false;
        }
        return true;
    }

    public static boolean pieceJumpingChecker(char[] moveArray, MoveCreator move, Map<String, String> board,
                                              char whoseMove) {
        if (Character.getNumericValue(moveArray[0])==Character.getNumericValue(moveArray[2])||
                Character.getNumericValue(moveArray[1])==Character.getNumericValue(moveArray[3])){
            if (!Rook.pieceJumpingChecker(move.moveArray, move, board, whoseMove)){
                return false;
            }
        }
        else{
            if (!Bishop.pieceJumpingChecker(move.moveArray, move, board, whoseMove)){
                return false;
        }
        }
        return true;
    }
}

Improvements: Primarily this project needs to be taken further to produce a computer program that can play chess. Initially, this is to test several alternative combinations in a code efficient manner, tested to see which position is best.

Source: Own project