Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • master
  • sdas
2 results

Target

Select target project
No results found
Select Git revision
  • master
  • sdas
2 results
Show changes

Commits on Source 2

60 files
+ 1693
0
Compare changes
  • Side-by-side
  • Inline

Files

+6 −0
Original line number Diff line number Diff line
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
	<classpathentry kind="src" path=""/>
	<classpathentry kind="output" path=""/>
</classpath>
+17 −0
Original line number Diff line number Diff line
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
	<name>projetechecs-master</name>
	<comment></comment>
	<projects>
	</projects>
	<buildSpec>
		<buildCommand>
			<name>org.eclipse.jdt.core.javabuilder</name>
			<arguments>
			</arguments>
		</buildCommand>
	</buildSpec>
	<natures>
		<nature>org.eclipse.jdt.core.javanature</nature>
	</natures>
</projectDescription>
+34 −0
Original line number Diff line number Diff line
public class Bishop extends Piece {

    public Bishop(int x, int y, Player owner){
		super(x, y, owner);
		
    }

    public boolean isMoveAuthorized(Board board, Coordinates destination){
	int dx = destination.getX();
	int dy = destination.getY();
	int ox = this.getX();
	int oy = this.getY();
	Coordinates origin = new Coordinates(ox,oy);
	for(int i=0; i<=7;i++) {
		for(int j=0; j<=7;j++) {
			if(board.sameDiagonalNothingBetween(origin, destination) &&(dx-ox)%(dy-oy)==0) {return true;}
		}
	}


	return false;
    }

    @Override
    public Type getType() {
	return Type.BISHOP;
    }

    @Override
    public int getValue() {
	return 3;
    }
    
}
+143 −0
Original line number Diff line number Diff line
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;

public class Board{
    private Piece[][] array;
    
    public Board(String fileName, Player white, Player black){
	int pieceType;
	int col;
	int row;
	String nextWord;
	Player owner;
	
	this.array = new Piece[8][8];
	try {
	    File file = new File(fileName);
    	    if(file.exists()==false) {
		System.err.println("Error: Cannot find file "+ fileName);
		System.exit(1);		
            } 

	    Scanner in = new Scanner(file);
	    while(in.hasNext()) {
		if ((nextWord = in.nextLine()).length()>2) {
		    pieceType = nextWord.charAt(0);
		    col = nextWord.charAt(1)-'0';
		    row = nextWord.charAt(2)-'0';
		    
		    owner = black;
		    if (pieceType >= 'a' && pieceType <= 'z')
    			owner = white;
		    switch(pieceType) {
		    case 'K' : case 'k' :  
    			{ this.addPiece(new King(col, row, owner)); break;}
		    case 'Q' : case 'q' :  
			{ this.addPiece(new Queen(col, row, owner)); break;}
		    case 'B' : case 'b' :  
			{ this.addPiece(new Bishop(col, row, owner)); break;}
		    case 'R' : case 'r' :  
			{ this.addPiece(new Rook(col, row, owner)); break;}
		    case 'N' : case 'n' :  
			{ this.addPiece(new Knight(col, row, owner)); break;}
			case 'P' : case 'p' :  
			{ this.addPiece(new Pawn(col, row, owner)); break;}
	    	}
	    	}	    	
	    }
	    in.close();
	}
	catch(FileNotFoundException e) {
	    System.err.println("Error file not found : "+e);
	    System.exit(1);	
	}
    }
    
    public List<Coordinates> getAllCoordinates(){
        List<Coordinates> allCoordinates = new ArrayList<>();
        for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) allCoordinates.add(new Coordinates(j, i));
        return allCoordinates;
    }
    
    public List<Piece> getPieces(Player player) {
    	List<Piece> pieces = new ArrayList<>();
        List<Piece> all = getPieces();
        for (Piece piece : all) if (player.equals(piece.getOwner())) pieces.add(piece);
        return pieces;
    }

    public List<Piece> getPieces() {
        List<Piece> all = new ArrayList<>();
        for (Piece[] pieces : array) for (Piece piece : pieces) if (piece != null) all.add(piece);
        return all;
    }

    public void addPiece(Piece piece){
    	array[piece.getY()][piece.getX()] = piece;
    }

    public Piece getPiece(Coordinates coordinates){
    	return array[coordinates.getY()][coordinates.getX()];
    }

    public Piece getPiece(int x, int y){
    	return array[y][x];
    }

    public void emptyCell(Coordinates coordinates){
    	array[coordinates.getY()][coordinates.getX()] = null;
    }
    
    public boolean isEmptyCell(Coordinates coordinates){
    	return array[coordinates.getY()][coordinates.getX()] == null;
    }
    
    public boolean isEmptyCell(int x, int y){
    	return array[y][x] == null;
    }
    
    public boolean sameColumnNothingBetween(Coordinates origin, Coordinates destination){
        if (origin.equals(destination)) return false;
        if (origin.getX() != destination.getX()) return false;
        int min = Math.min(origin.getY(), destination.getY());
        int max = Math.max(origin.getY(), destination.getY());
        for (int i = min ; i <= max; i++) {
            if (!isEmptyCell(origin.getX(), i)) return false;
        }
        return true;
    }
    
    public boolean sameRowNothingBetween(Coordinates origin, Coordinates destination){
        if (origin.equals(destination)) return false;
        if (origin.getY() != destination.getY()) return false;
        int min = Math.min(origin.getX(), destination.getX());
        int max = Math.max(origin.getX(), destination.getX());
        for (int i = min + 1; i < max; i++) {
            if (!isEmptyCell(i, origin.getY())) return false;
        }
        return true;
    }

    public boolean sameDiagonalNothingBetween(Coordinates origin, Coordinates destination){
        if (origin.equals(destination)) return false;
        int lenX = Math.abs(origin.getX() - destination.getX());
        int lenY = Math.abs(origin.getY() - destination.getY());
        if (lenX != lenY) return false;
        if (origin.getX() - destination.getX() > 1) {
            if (origin.getY() - destination.getY() > 1)
                for (int i = 1; i < lenX; i++) if (!isEmptyCell(origin.getX() - i, origin.getY() - i)) return false;
            if (origin.getY() - destination.getY() < -1)
                for (int i = 1; i < lenX; i++) if (!isEmptyCell(origin.getX() - i, origin.getY() + i)) return false;
        }
        if (origin.getX() - destination.getX() < -1) {
            if (origin.getY() - destination.getY() > 1)
                for (int i = 1; i < lenX; i++) if (!isEmptyCell(origin.getX() + i, origin.getY() - i)) return false;
            if (origin.getY() - destination.getY() < -1)
                for (int i = 1; i < lenX; i++) if (!isEmptyCell(origin.getX() + i, origin.getY() + i)) return false;
        }
        return true;
    }
}
+41 −0
Original line number Diff line number Diff line
import java.util.Random;

public class ChessBot extends Player {
    
    Board board;

    public ChessBot(ChessColor color){
        super(color);
        board = null;
    }

    public void setBoard(Board board){
        this.board = board;
    }

    @Override
    public FromTo getFromTo() {
        Random rd = new Random();
        FromTo chosenMove = new FromTo(0,0,0,0);
        int max = -1;
        int scorePiece;
        
        for(Move move : getAllMoves(board)) { 
            if(move.pieceAtDestination == null) {
                scorePiece = 0;
            } else {
                scorePiece = move.pieceAtDestination.getValue();
            }

            if(this.isCheck && move.pieceAtOrigin.getType() == Piece.Type.KING)
                scorePiece += 100;
                
            if (scorePiece > max || (scorePiece == max && rd.nextBoolean())) {
                chosenMove = new FromTo(move.origin.getX(),move.origin.getY(),move.destination.getX(),move.destination.getY());
                max = scorePiece;
            }
        }
        
        return chosenMove;
    }
}
+213 −0
Original line number Diff line number Diff line
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class ChessUI extends JFrame implements MouseListener, MouseMotionListener {
    JLayeredPane layeredPane;
    JPanel chessBoard;
    int cellSize;

    private ImageIcon[] chessIcons;
    private JLabel[] pieceLabels;

    JLabel movingChessPiece;
    int originXMove;
    int originYMove;
    int destXMove;
    int destYMove;

    boolean moveFreshness;

    int xAdjustment;
    int yAdjustment;


    public ChessUI(){
        this.cellSize = 60;
        Dimension boardSize = new Dimension(8 * cellSize, 8 * cellSize);

        //  Use a Layered Pane for this this application
        layeredPane = new JLayeredPane();
        getContentPane().add(layeredPane);
        layeredPane.setPreferredSize(boardSize);
        layeredPane.addMouseListener(this);
        layeredPane.addMouseMotionListener(this);

        //Add a chess board to the Layered Pane

        chessBoard = new JPanel();
        layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
        chessBoard.setLayout( new GridLayout(8, 8) );
        chessBoard.setPreferredSize( boardSize );
        chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);

        for (int i = 0; i < 64; i++) {
            JPanel square = new JPanel( new BorderLayout() );
            chessBoard.add( square );

            square.setBackground( (i + i / 8) % 2 == 1 ? Color.GRAY : Color.WHITE );
        }

        initIcons();
        initPieceLabels();

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        pack();
        setResizable(true);
        setLocationRelativeTo( null );
        setVisible(true);
    }

    /** ---------------------------------------------------------------------------------
     * Chess piece graphics **/

    private void initIcons() {
        chessIcons = new ImageIcon[] {
                new ImageIcon("./img/Chess_kdt60.png"),
                new ImageIcon("./img/Chess_qdt60.png"),
                new ImageIcon("./img/Chess_rdt60.png"),
                new ImageIcon("./img/Chess_bdt60.png"),
                new ImageIcon("./img/Chess_ndt60.png"),
                new ImageIcon("./img/Chess_pdt60.png"),
                new ImageIcon("./img/Chess_klt60.png"),
                new ImageIcon("./img/Chess_qlt60.png"),
                new ImageIcon("./img/Chess_rlt60.png"),
                new ImageIcon("./img/Chess_blt60.png"),
                new ImageIcon("./img/Chess_nlt60.png"),
                new ImageIcon("./img/Chess_plt60.png")
        };
    }

    private void initPieceLabels() {
        pieceLabels = new JLabel[64];

        for(int k = 0; k < 64; k++) {
            JLabel label = new JLabel();
            label.setVisible(false);
            label.setSize(cellSize, cellSize);
            pieceLabels[k] = label;
            JPanel panel = (JPanel)chessBoard.getComponent(k);
            panel.add(label);
        }
    }

    private JLabel getPieceLabel(int row, int column) {
        return pieceLabels[row * 8 + column];
    }

    private ImageIcon getImageIcon(Piece.Type type, ChessColor color) {
        return chessIcons[type.ordinal() + (color == ChessColor.WHITE ? Piece.Type.values().length : 0)];
    }

    /**
     * This method takes a piece of a color and places it in the specified coordinates.
     * @param type Desired type
     * @param color Desired color (should only be either Color.white or Color.black)
     * @param coord Coordinates of the piece
     */
    public void placePiece(Piece.Type type, ChessColor color, Coordinates coord) {
        getPieceLabel(coord.getY(), coord.getX()).setIcon(getImageIcon(type, color));
        getPieceLabel(coord.getY(), coord.getX()).setVisible(true);
    }

    /**
     * This method removes the piece at the specified position, if there is any.
     * @param coord Coordinates of the piece
     */
    public void removePiece(Coordinates coord) {
        getPieceLabel(coord.getY(), coord.getX()).setVisible(false);
    }

    /** ---------------------------------------------------------------------------------
     * Events management **/

    /**
     * This method waits for the player to enter a move in the UI. Calling this is blocking.
     */
    public FromTo waitForPlayerMove() {
        moveFreshness = false;

        while(! moveFreshness)
            try {
                synchronized (this.getClass()) {
                    this.getClass().wait();
                }
            }
            catch (Exception e) {
                System.err.println("ERROR : interrupted while waiting for chess move");
                System.err.println(e);
                System.exit(-1);
            }

        return new FromTo(originXMove, originYMove, destXMove, destYMove);
    }

    public void mousePressed(MouseEvent e){
        movingChessPiece = null;

        originXMove = e.getX() / cellSize;
        originYMove = e.getY() / cellSize;

        xAdjustment = - e.getX() + originXMove * cellSize;
        yAdjustment = - e.getY() + originYMove * cellSize;

        movingChessPiece = new JLabel(getPieceLabel(originYMove, originXMove).getIcon());
        movingChessPiece.setVisible(getPieceLabel(originYMove, originXMove).isVisible());

        movingChessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
        if(movingChessPiece.getIcon() != null)
            movingChessPiece.setSize(movingChessPiece.getIcon().getIconWidth(), movingChessPiece.getIcon().getIconHeight());
        layeredPane.add(movingChessPiece, JLayeredPane.DRAG_LAYER);
    }

    //Move the chess piece around

    public void mouseDragged(MouseEvent me) {
        if (movingChessPiece == null) return;
        movingChessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);
    }

    //Drop the chess piece back onto the chess board

    public void mouseReleased(MouseEvent e) {
        if(movingChessPiece == null) return;

        movingChessPiece.setVisible(false);

        layeredPane.remove(movingChessPiece);
        movingChessPiece = null;

        destXMove = e.getX() / cellSize;
        destYMove = e.getY() / cellSize;

        moveFreshness = true;

        synchronized (this.getClass()) {
            this.getClass().notifyAll();
        }
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e) {}

    public static void main(String[] args) {
        ChessUI ui = new ChessUI();
        ui.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        for(int k = 0; k < Piece.Type.values().length; k++)
            ui.placePiece(Piece.Type.values()[k], ChessColor.BLACK, new Coordinates(k, 0));

        for(int k = 0; k < Piece.Type.values().length; k++)
            ui.placePiece(Piece.Type.values()[k], ChessColor.WHITE, new Coordinates(k, 1));

        ui.pack();
        ui.setResizable(true);
        ui.setLocationRelativeTo( null );
        ui.setVisible(true);
    }
}
+29 −0
Original line number Diff line number Diff line
public class Coordinates{
    private int x;
    private int y;
    
    public Coordinates(int x, int y){
    	this.x = x;
    	this.y = y;
    }

    public int getX(){
	return x;
    }
    public int getY(){
	return y;
    }

    @Override
    public String toString(){
	return "x= "+x+" y= "+y;
    }

    @Override
    public boolean equals(Object o) {
        if (this.getClass() != o.getClass()) return false;
    	if(this==o) return true;
    	Coordinates oCords = (Coordinates)o;
    	return this.x == oCords.x && this.y == oCords.y;
    }
}
+17 −0
Original line number Diff line number Diff line
public class FromTo {
    private final Coordinates from;
    private final Coordinates to;
    
    public FromTo(int ox, int oy, int dx, int dy) {
	from = new Coordinates(ox,oy);
	to = new Coordinates(dx,dy);
    }

    public Coordinates getFrom() {
        return this.from;
    }

    public Coordinates getTo() {
        return this.to;
    }
}
+150 −0
Original line number Diff line number Diff line
import java.util.List;
import java.util.Stack;




public class GameUI {
    public Board board;
    private Player white;
    private Player black;
    private Player currentPlayer;
    private ChessUI ui;
    private Stack<Move> history;
    
    public GameUI(ChessUI ui, String boardConfigFileName, Player white, Player black){
        this.board = new Board(boardConfigFileName, white, black);
        this.white = white;
        this.black = black;
        this.currentPlayer = white;
        this.ui = ui;
	this.history = new Stack<Move>();

        for(Piece p : board.getPieces())
            this.ui.placePiece(p.getType(), p.getColor(), p.getPosition());
    }

    public Board getBoard(){
	return this.board;
    }

    public boolean undo(){
	if(this.history.empty()) return false;
	Move move = this.history.pop();
	board.emptyCell(move.destination);
	ui.removePiece(move.destination);
	if(move.pieceAtDestination != null){
	    move.pieceAtDestination.setPosition(move.destination);
	    board.addPiece(move.pieceAtDestination);
	    ui.placePiece(move.pieceAtDestination.getType(), move.pieceAtDestination.getColor(), move.pieceAtDestination.getPosition());
	}
	board.emptyCell(move.origin);
	ui.removePiece(move.origin);
	move.pieceAtOrigin.setPosition(move.origin);
	board.addPiece(move.pieceAtOrigin);
	ui.placePiece(move.pieceAtOrigin.getType(), move.pieceAtOrigin.getColor(), move.pieceAtOrigin.getPosition());
	
	currentPlayer = move.pieceAtOrigin.getOwner();
	if(move.pieceAtDestination != null)
	    currentPlayer.removeFromScore(move.pieceAtDestination.getValue());
	return true;
    }
    
    
    
    public boolean isMovePlayable(Move gameMove){
    	Piece piece = board.getPiece(gameMove.origin);
    	if(piece == null
    			||currentPlayer.getColor() != piece.getColor()
    			|| !gameMove.pieceAtOrigin.isMoveAuthorized(board, gameMove.destination)
    			 
    			|| gameMove.pieceAtOrigin.getOwner() != currentPlayer){
    		System.out.println("Le coups ne peut pas etre jouer 1");  
    		return false;}
    	
                
               

        if (gameMove.pieceAtDestination != null
                && gameMove.pieceAtDestination.sameColor(gameMove.pieceAtOrigin)) {
        	System.out.println("Le coups ne peut pas etre jouer 2");
        	
        	
        	
        	return false;}


        applyMove(gameMove);

        /**if (isCheck(getOpponent(currentPlayer))) {
            undo();
            return false;
        }

		***/
        undo();
        return true;
	
    }
    
    public void applyMove(Move move){
    	 Piece piece = board.getPiece(move.origin);
         history.push(move);
         board.emptyCell(piece.getPosition());
         piece.setPosition(move.destination);
         board.addPiece(piece);
         switchPlayers();
    }

    public void switchPlayers(){
    	this.currentPlayer = getOpponent(currentPlayer);
    }

    public Player getOpponent(Player player){
    	if (player == white) return black;
        return player;
    }

    public boolean isPrey(Piece prey){
        Player playerOp = getOpponent(prey.owner);
        List<Move> opponentMoves = playerOp.getAllMoves(board);
        for (Move move : opponentMoves) {
            if (prey.equals(move.pieceAtDestination)) return true;
        }
        return false;
    }

    public boolean isCheck(Player player){return isPrey(player.getKing());}

    public boolean isCheckMate(Player player){
	return false;
    }
    
    public void determineWinner(){
    }
    
    public void play(){
	int numberOfHits = 0;
	while(numberOfHits < 50){
		System.out.println("A toi de jouer " + currentPlayer.getColor());
		Move move;
        do {
            move = new Move(board, currentPlayer.getFromTo());
        } 
	    while(!isMovePlayable(move)); 
	    applyMove(move);
	    ui.placePiece(move.pieceAtOrigin.getType(), move.pieceAtOrigin.getColor(), move.destination);
        ui.removePiece(move.origin);
        numberOfHits++;
        switchPlayers();
	    
	    
	    
	    

	    numberOfHits ++;
	    System.out.println("Nombre de coups: " + numberOfHits+" /50");
	    switchPlayers();
	}
    }
}
+14 −0
Original line number Diff line number Diff line
public class Human extends Player{

    ChessUI ui;
    public Human(ChessUI ui, ChessColor color){
        super(color);
        this.ui = ui;
    }

    @Override
    public FromTo getFromTo() {
        return ui.waitForPlayerMove();
    }
    
}
+38 −0
Original line number Diff line number Diff line
public class King extends Piece {

    public King(int x, int y, Player owner){
		super(x, y, owner);
		owner.setKing(this);
    }

    public boolean isMoveAuthorized(Board board, Coordinates destination){
	int dx = destination.getX();
	int dy = destination.getY();
	int ox = this.getX();
	int oy = this.getY();
	
	for(int i=-1;i<=1;i++) {
		for(int j=-1; j<=1; j++) {
			if( (dx-ox)==i && (dy-oy)==j && board.isEmptyCell(dx, dy)) {
				return true;
			}
		}
		
	}



	return false;
    }

    @Override
    public Type getType() {
	return Type.KING;
    }

    @Override
    public int getValue() {
	return 0;
    }
    
}
+35 −0
Original line number Diff line number Diff line
public class Knight extends Piece {

    public Knight(int x, int y, Player owner){
		super(x, y, owner);
		
    }

    public boolean isMoveAuthorized(Board board, Coordinates destination){
	int dx = destination.getX();
	int dy = destination.getY();
	int ox = this.getX();
	int oy = this.getY();
	for(int i=-2; i <= 2; i++) {
		for(int j=-2; j <= 2; j++) {
			if(((dx-ox)%2==1 && (dy-oy)%2==0) || ((dx-ox)%2==0 && (dy-oy)%2==1)) {
				return true;
			}
		}
	}


	return false;
    }

    @Override
    public Type getType() {
	return Type.KNIGHT;
    }

    @Override
    public int getValue() {
	return 3;
    }
    
}
+9 −0
Original line number Diff line number Diff line
public class Main{
    public static void main(String[] args) {
    	ChessUI ui = new ChessUI();
	GameUI g = new GameUI(ui, "boardConfigurationFiles/FullBoard.txt", new Human(ui, ChessColor.WHITE), new Human(ui, ChessColor.BLACK));

	g.play();
    }

}
+29 −0
Original line number Diff line number Diff line
public class Move{
	
    final Coordinates origin;
    final Coordinates destination;
    final Piece pieceAtOrigin;
    final Piece pieceAtDestination;
    
    public Move(Board board, Coordinates origin, Coordinates destination){
	this.origin = origin;
	this.destination = destination;
	this.pieceAtOrigin = board.getPiece(origin);
	this.pieceAtDestination = board.getPiece(destination);
    }
    
    public Move(Coordinates origin, Coordinates destination, Piece pieceAtOrigin, Piece pieceAtDestination){
	this.origin = origin;
	this.destination = destination;
	this.pieceAtOrigin = pieceAtOrigin;
	this.pieceAtDestination = pieceAtDestination;
    }
    
    public Move(Board board, FromTo ft){
	this.origin = ft.getFrom();
	this.destination = ft.getTo();
	this.pieceAtOrigin = board.getPiece(ft.getFrom());
	this.pieceAtDestination = board.getPiece(ft.getTo());
    }
}
    
+37 −0
Original line number Diff line number Diff line
public class Pawn extends Piece {

    public Pawn(int x, int y, Player owner){
		super(x, y, owner);
		
    }

    public boolean isMoveAuthorized(Board board, Coordinates destination){
	int dx = destination.getX();
	int dy = destination.getY();
	int ox = this.getX();
	int oy = this.getY();
	int absx = Math.abs(dx-ox);
	int absy = Math.abs(dy-oy);
	for(int i=0; i<=7; i++) {
		
		if((oy==1 || oy == 6) && (absy==1 || absx == 2) && board.isEmptyCell(destination)&&absx==0) {return true;}
		
		if((oy!=1 || oy!=6) && absy==1 && absx==0){return true;}
		return false;
	}


	return true;
    }

    @Override
    public Type getType() {
	return Type.PAWN;
    }

    @Override
    public int getValue() {
	return 1;
    }
    
}
+66 −0
Original line number Diff line number Diff line
import java.util.ArrayList;
import java.util.List;

public abstract class Piece{
    protected Coordinates position;
    protected Player owner;
    
    public Piece(int x, int y, Player owner){
        this.position = new Coordinates(x,y);
        this.owner = owner;
    }

    public enum Type {
        KING,
        QUEEN,
        ROOK,
        BISHOP,
        KNIGHT,
        PAWN
    }

    public void setPosition(Coordinates destination){
    	this.position = destination;
    }
    
    public Player getOwner(){
	return this.owner;
    }

    public ChessColor getColor(){
	return this.owner.color;
    }

    public Coordinates getPosition(){
	return this.position;
    }

    public int getX(){
	return this.position.getX();
    }
    
    public int getY(){
	return this.position.getY();
    }

    public List<Move> getAllMoves(Board board) {
    	List<Move> allMoves = new ArrayList<>();
    	for (Coordinates coordinates : board.getAllCoordinates()){
    	    if (this.isMoveAuthorized(board,coordinates)){
    	        allMoves.add(new Move(board, position, coordinates));
            }
        }
    	return allMoves;
    }

    public boolean sameColor(Piece piece){
	return this.getColor()== piece.getColor();
    }

    public abstract boolean isMoveAuthorized(Board board, Coordinates destination);

    public abstract Type getType();
    public abstract int getValue();
    

}
+61 −0
Original line number Diff line number Diff line
import java.util.ArrayList;
import java.util.List;

public abstract class Player{
    protected ChessColor color;
    private int score;
    private King king;
    public boolean isCheck;
    public boolean isCheckMate;

    public Player(ChessColor color){
        this.color = color;
        this.score = 0;
        this.isCheckMate = false;
    }

    public ChessColor getColor(){
	return this.color;
    }

    public int getScore(){
	return this.score;
    }

    public void addToScore(int value){
    	score+=value;
    }
    
    public void removeFromScore(int value){
    	score-= value;
    }
    
    public abstract FromTo getFromTo();

    public Piece getKing(){
	return this.king;
    }
    
    public void setKing(King king){
    	this.king=king;
    }
    
    public boolean isCheckMate(Board board){
	return false;
    }

    public void setCheck(){
    }

    public void unSetCheck(){
    }
    
    public List<Move> getAllMoves(Board board) {
	return null;
    }

    @Override
    public String toString(){
	return null;
    }
}
+43 −0
Original line number Diff line number Diff line
public class Queen extends Piece {

    public Queen(int x, int y, Player owner){
		super(x, y, owner);
		
    }

    public boolean isMoveAuthorized(Board board, Coordinates destination){
	int dx = destination.getX();
	int dy = destination.getY();
	int ox = this.getX();
	int oy = this.getY();
	Coordinates origin = new Coordinates(ox,oy);
	


	for(int i=0; i<=7;i++) {
		for(int j=0; j<=7;j++) {
			if(board.sameColumnNothingBetween(origin,destination)&& dy<=7 && dy >=0) {return true;}
			else if(board.sameRowNothingBetween(origin,destination)&& dx<=7 && dx>=0) {return true;}
			else if(board.sameDiagonalNothingBetween(origin, destination) &&(dx-ox)%(dy-oy)==0) {return true;}
		}
	}
	
	



	return false;
    
    }

    @Override
    public Type getType() {
	return Type.QUEEN;
    }

    @Override
    public int getValue() {
	return 9;
    }
    
}
+33 −0
Original line number Diff line number Diff line
public class Rook extends Piece {

    public Rook(int x, int y, Player owner){
		super(x, y, owner);
		
    }

    public boolean isMoveAuthorized(Board board, Coordinates destination){
	int dx = destination.getX();
	int dy = destination.getY();
	int ox = this.getX();
	int oy = this.getY();
	Coordinates origin = new Coordinates(ox,oy);
	for(int i=0; i<=7;i++) {
		for(int j=0; j<=7;j++) {
			if(board.sameColumnNothingBetween(origin,destination)&& dy<=7 && dy >=0) {return true;}
			else if(board.sameRowNothingBetween(origin,destination)&& dx<=7 && dx>=0) {return true;}
		}
	}
	return false;
    }

    @Override
    public Type getType() {
	return Type.ROOK;
    }

    @Override
    public int getValue() {
	return 5;
    }
    
}
+76 −0
Original line number Diff line number Diff line
import java.io.*;
import java.util.Scanner;

public class TestChess{

	public static void main(String[] args) {
	    
	    boolean resultTest;
	    /* Test de déplacements autorisés selon les regles de pièces */
	    System.out.println("authorized moves");
	    System.out.print("test 1 : ");
	    resultTest = testAuthorizedMove("boardConfigurationFiles/FullBoard.txt", new Coordinates(0,1), new Coordinates(0,2));
	    if(resultTest == true) System.out.println("pass"); else System.out.println("fail");
	    
	    System.out.print("test 2 : ");
	    resultTest = testAuthorizedMove("boardConfigurationFiles/FullBoard.txt", new Coordinates(0,1), new Coordinates(0,4));
	    if(resultTest == false) System.out.println("pass"); else System.out.println("fail");
	    
	    
	    /*  Test de déplacements jouables sur l'échiquier actuel, selon les regles du jeu */
	    System.out.println("playable moves");
	    System.out.print("test 1 : ");
	    resultTest = testPlayableMove("boardConfigurationFiles/FullBoard.txt",new Coordinates(0,1),new Coordinates(0,2));
	    if(resultTest == true) System.out.println("pass"); else System.out.println("fail");

	    System.out.print("test 2 : ");
	    resultTest = testPlayableMove("boardConfigurationFiles/FullBoard.txt",new Coordinates(0,1),new Coordinates(0,3));
	    if(resultTest == true) System.out.println("pass"); else System.out.println("fail");
	    
	    /*  Tests de la mise en échec */
	    
	    /*  Tests de la Echec et mat "isCheckMate()" */
	    
	    /*  Tests pours le calcul des points en fin de partie */
    }

    
    public static boolean testAuthorizedMove(String filename, Coordinates origin, Coordinates destination) {    			
	ChessUI ui = new ChessUI();
	Board testBoard = new Board(filename, new Human(ui, ChessColor.WHITE), new Human(ui, ChessColor.BLACK));
	Piece testPiece = testBoard.getPiece(origin);
	if(testPiece == null) {
	    System.out.println("No Piece at :"+origin); 
	    return false;
	}
	return testPiece.isMoveAuthorized(testBoard, destination);
    }

	
    public static boolean testPlayableMove(String fileName, Coordinates origin, Coordinates destination) {    			
	ChessUI ui = new ChessUI();
	GameUI g = new GameUI(ui, fileName, new Human(ui, ChessColor.WHITE), new Human(ui, ChessColor.BLACK));
	
	Piece testPiece = g.getBoard().getPiece(origin);
	if(testPiece == null) {
	    System.out.println("No Piece at :"+origin); 
	    return false;
	}
	return g.isMovePlayable(new Move(g.getBoard(), origin, destination));
    }

    public static boolean testIsCheck(String fileName, Player p) {    			
	ChessUI ui = new ChessUI();
	GameUI g = new GameUI(ui, fileName, new Human(ui, ChessColor.WHITE), new Human(ui, ChessColor.BLACK));
	return g.isCheck(p);
    }

    public static boolean testIsCheckMate(String fileName, Player p) {    			
	ChessUI ui = new ChessUI();
	GameUI g = new GameUI(ui, fileName, new Human(ui, ChessColor.WHITE), new Human(ui, ChessColor.BLACK));
	return g.isCheck(p) && g.isCheckMate(p);
    }

	
}
+78 −0
Original line number Diff line number Diff line
# Projet de jeu d'échec en Java

Projet Final (S3 Programmation 2)

## Binôme

Alexandre AGUEDO

Astrid BEYER


Aix Marseille Université

L2 Informatique

Groupe 3

## Encadrant de TPs et projet

Pacôme PERROTIN

## Objectif et tâches

L’objectif de ce projet est de programmer un jeu d’´echec. Ce jeu permet `a deux joueurs humains de jouer ensemble
ou bien à un joueur humain de jouer contre une version très simple d’un joueur artificiel, ou à deux joueurs artificiels
de jouer ensemble !

En savoir plus : http://pageperso.lif.univ-mrs.fr/~alexis.nasr/Ens/PROG2/projet_echecs_an.pdf

## Les fichiers

* boardConfigurationFiles/
> Dossier contenant des placements de pièces pré-remplis, ces placements sont utiles pour tester le programme dans diverses situations.

* img/
> Dossier avec les images en format PNG des 12 pièces de l'échiquier (6 noires et 6 blanches).

* Player.java
> Classe abstraite déterminant un joueur. 

* Board.java
> Classe permettant d'instancier le plateau de jeu d'échec.

* ChessBot.java
> Classe qui étend Player. ChessBot est la classe d'un joueur robot qui va choisir les coups les plus avantageux (rapportant le plus de score) lorsqu'il jouera.

* Human.java
> Classe qui étend Player. Cette classe permet à un utilisateur de jouer. 

* ChessColor.java
> Énumération des couleurs possibles des joueurs/pièces.

* Piece.java
> Classe abstraite déterminant une pièce de l'échiquier.

* Bishop.java ; King.java ; Knight.java ; Pawn.java ; Queen.java ; Rook.java
> Respectivement les classes du fou, roi, cavalier, pion, dame et tour. Ces classes étendent toutes la classe Piece et déterminent, pour chaque pièce, leurs mouvements possibles et autorisés.

* TestChess.java
> Fichier de tests.

* Move.java
> Classe publique qui permet à une pièce de se déplacer d'un point à un autre dans l'échiquier.

* ChessUI.java
> Classe gérant l'interface du jeu d'échec et la possibilité de déplacer ses pièces avec sa souris.

* GameUI.java
> Classe gérant le déroulement de la partie.

* Coordinates.java
> Classe permettant de récupérer des coordonnées.

* FromTo.java
> Classe permettant de récupérer les coordonnées d'origine d'une pièce et les coordonnées de destination d'une pièce.

* Main.java
> Classe principale qui lance le jeu.
 No newline at end of file

tp6/.classpath

0 → 100644
+11 −0
Original line number Diff line number Diff line
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
	<classpathentry kind="src" path=""/>
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
		<attributes>
			<attribute name="module" value="true"/>
		</attributes>
	</classpathentry>
	<classpathentry kind="lib" path="/Users/teobk/programmation2/tp6/tp2.jar"/>
	<classpathentry kind="output" path=""/>
</classpath>

tp6/.gitignore

0 → 100644
+6 −0
Original line number Diff line number Diff line
/Main.class
/Point.class
/Rectangle.class
/Shape.class
/Triangle.class
/Turtle.class

tp6/.project

0 → 100644
+17 −0
Original line number Diff line number Diff line
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
	<name>tp6</name>
	<comment></comment>
	<projects>
	</projects>
	<buildSpec>
		<buildCommand>
			<name>org.eclipse.jdt.core.javabuilder</name>
			<arguments>
			</arguments>
		</buildCommand>
	</buildSpec>
	<natures>
		<nature>org.eclipse.jdt.core.javanature</nature>
	</natures>
</projectDescription>

tp6/Main.java

0 → 100755
+103 −0
Original line number Diff line number Diff line
/**
 * Created by Arnaud Labourel on 20/09/2018.
 */

import tp2.lib.Painter;

import java.awt.Color;
import java.util.Random;

import static tp2.lib.Tools.sleep;

public class Main {
    static final int WIDTH = 800;
    static final int HEIGHT = 600;


    public static void main(String[] args){
        Random random= new Random();
        Painter painter = new Painter(WIDTH, HEIGHT);
        

        // Point.test1_Point(painter);
        // Point.test2_Point(painter);
        
        //Rectangle.test_rectangle(painter);
        // dessin_Roue();
        // drawFractale();
        test_turtle();
        
    }
    
    public static void dessin_Roue() {
    	int numberOfPoint = 10;

        Painter painter = new Painter(WIDTH,HEIGHT);
        Point center = new Point(WIDTH/2,HEIGHT/2 );
        Point point = new Point(100,0);
        for (int i = 0; i < numberOfPoint; i++) {
        	Point p1 = point.rotate((360/numberOfPoint)*i);
            Point nextPoint = point.rotate((360/numberOfPoint)*(i+1));
            
            p1 = p1.translate(center.x,center.y);
            nextPoint = nextPoint.translate(center.x,center.y);

            nextPoint.draw(painter,Color.red);

            center.drawLine(p1,painter,Color.blue);
            p1.drawLine(nextPoint,painter,Color.black);


        }

    }
    
    public static void drawSquare(Turtle turtle, int size) {
    	for (int i = 0; i < 4; i++) {
    	turtle.moveForward(size);
    	turtle.turnLeft(90);
    	}
    }
    
    
    	public static void test_turtle() {
    	Turtle turtle = new Turtle(800,600);
    	turtle.setColor(Color.black);
    	turtle.setPenDown();
    	int n = 20;
    	for (int i = 0; i < n; i++) {
    	turtle.turnRight(360.0/n);
    	drawSquare(turtle, 10);
    	}
    	
    	
    }

/*
    private static void drawFractale(){
        int width = 590, height = 580, nbIterations = 4;
        Turtle turtle = new Turtle(width, height);

        // Déplacement de la tortue en bas à gauche.
        turtle.setPenUp();
        turtle.turnLeft(90); turtle.moveForward(width/2-10);
        turtle.turnLeft(90); turtle.moveForward(height/2-10);
        turtle.turnLeft(180);
        turtle.setPenDown();

        // Définition des règles
        Rule[] rules = { new Rule('X', "XAYAX+A+YAXAY-A-XAYAX"),
                new Rule('Y', "YAXAY-A-XAYAX+A+YAXAY") };
        SetOfRules setOfRules = new SetOfRules(rules);

        // Application des règles nbIterations fois
        String sequence = "X";
        for (int i = 0; i < nbIterations; i++)
            sequence = setOfRules.apply(sequence);

        // Dessin de la séquence par la tortue
        turtle.drawString(sequence, 7, 90);
    }
*/

}

tp6/Point.java

0 → 100755
+77 −0
Original line number Diff line number Diff line
/**
 * Created by Arnaud Labourel on 20/09/2018.
 */
import tp2.lib.Painter;

import java.awt.*;

public class Point {
    public final double x;
    public final double y;

    public Point(double x, double y) {
    	this.y = y;
    	this.x = x;
	// Add code here
    }

    void draw(Painter painter, Color color){
        // Add code here
    	painter.addPoint(this.x, this.y, color);
    }

    void drawLine(Point p, Painter painter, Color color){
    	painter.addLine(this.x, this.y, p.x, p.y, color);
        // Add code here
    }
    
    Point translate(double dx, double dy) {
    	return new Point(this.x+dx, this.y+dy);
    }
    
    Point rotate(double angle) {
    	double a = (Math.PI * angle)/180;
    	
    	double xr = (this.x*Math.cos(a)) - (this.y*Math.sin(a));
        double yr = (this.x*Math.sin(a)) + (this.y*Math.cos(a));
        

    	return new Point(xr,yr);
    }
    
    public double distance (Point point){
        return (Math.sqrt( Math.pow(this.x-point.x, 2) + Math.pow((this.y-point.y), 2) ));
    }


public static void test1_Point(Painter painter){
        Point p1 = new Point(100,100);
        Point p2 = new Point(300,100);
        Point p3 = new Point(300,300);
        Point p4 = new Point(100,300);
        p1.drawLine(p2, painter, Color.black);
        p2.drawLine(p3, painter, Color.black);
        p3.drawLine(p4, painter, Color.black);
        p4.drawLine(p1, painter, Color.black);
        p1.draw(painter, Color.red);
        p2.draw(painter, Color.red);
        p3.draw(painter, Color.red);
        p4.draw(painter, Color.red);
}

public static void test2_Point(Painter painter){
    Point p1 = new Point(100,100);
    Point p2 = p1.translate(200, 0);
    Point p3 = p2.translate(0, 200);
    Point p4 = p3.translate(-200,0);
    p1.drawLine(p2, painter, Color.black);
    p2.drawLine(p3, painter, Color.black);
    p3.drawLine(p4, painter, Color.black);
    p4.drawLine(p1, painter, Color.black);
    p1.draw(painter, Color.red);
    p2.draw(painter, Color.red);
    p3.draw(painter, Color.red);
    p4.draw(painter, Color.red);
}

}

tp6/Rectangle.java

0 → 100755
+82 −0
Original line number Diff line number Diff line
import tp2.lib.Painter;


import java.awt.*;
import java.util.Random;
import static tp2.lib.Tools.sleep;

/**
 * Created by Arnaud Labourel on 17/10/2018.
 */

public class Rectangle implements Shape{

    Point p1, p2;

    public Rectangle(Point p1, Point p2){
        // Add code here
    	this.p1 = p1;
        this.p2 = p2;

    }

    private double height(){
        return Math.abs(p2.y-p1.y);
    }

    private double width(){
        return Math.abs(p2.x-p1.x);
    }




    public static void test_rectangle(Painter painter){
        Point p1 = new Point(100,100);
        Point p2 = new Point(200,100);
        Point p3 = new Point(200,300);
	Random random= new Random();
        
	Shape r = new Rectangle(p1, p3);
        r.draw(painter, Color.black);

        for(int i =30; i<400; i+=30) {
            Shape t2 = r.translate(i, i);
            sleep(100);
            t2.draw(painter, new Color(random.nextFloat(),
                    random.nextFloat(), random.nextFloat()));
        }
    }


    @Override
    public double getPerimeter() {
        return height()*2 + width()*2;
    }

    @Override
    public void draw(Painter painter, Color color) {
        Point upRight = p1.translate(width(),0);
        Point downLeft = p1.translate(0,height());
        p1.drawLine(upRight,painter,color);
        p1.drawLine(downLeft,painter,color);
        p2.drawLine(upRight,painter,color);
        p2.drawLine(downLeft,painter,color);
    }

    @Override
    public Shape translate(int dx, int dy) {
        return new Rectangle(
                p1.translate(dx,dy),
                p2.translate(dx,dy)
        );
    }

    @Override
    public double getArea() {
        return height()*width();
    }



}

tp6/Shape.java

0 → 100755
+15 −0
Original line number Diff line number Diff line
import tp2.lib.Painter;

import java.awt.*;

/**
 * Created by Arnaud Labourel on 15/10/2018.
 */

public interface Shape {

    double getPerimeter();
    void draw(Painter painter, Color color);
    Shape translate(int dx, int dy);
    double getArea();
}

tp6/Triangle.java

0 → 100755
+73 −0
Original line number Diff line number Diff line
import tp2.lib.Painter;
import static tp2.lib.Tools.sleep;
import java.awt.*;
import java.util.Random;

/**
 * Created by Arnaud Labourel on 15/10/2018.
 */
public class Triangle implements Shape {
    private final Point[] vertices;

    public Triangle(Point p1, Point p2, Point p3) {
        vertices = new Point[]{p1, p2, p3};
    }

    private Triangle(Point[] vertices){
        this.vertices = vertices;
    }
    
    
    public static void test_triangle(Painter painter){
        Point p1 = new Point(100,100);
        Point p2 = new Point(200,100);
        Point p3 = new Point(200,200);

        Point point[] = {p1,p2,p3};

        Random random= new Random();
        Shape r = new Triangle(point);
        System.out.println(r.getArea());
        for(int i =30; i<400; i+=30) {
            Shape t2 = r.translate(i, i);
            sleep(100);
            t2.draw(painter, new Color(random.nextFloat(),
                    random.nextFloat(), random.nextFloat()));
        }
    }


    @Override
    public double getPerimeter() {
        return (vertices[0].distance(vertices[1]) +
               vertices[1].distance(vertices[2]) +
                vertices[2].distance(vertices[0]));
    }

    @Override
    public void draw(Painter painter, Color color) {
        for (int i = 0; i < 3; i++) {
            vertices[i].drawLine(vertices[ (i+1) % 3],painter,color);
        }
    }

    @Override
    public Shape translate(int dx, int dy) {
        return new Triangle(
                vertices[0].translate(dx,dy),
                vertices[1].translate(dx,dy),
                vertices[2].translate(dx,dy)
                );
    }

    @Override
    public double getArea() {
        double p = getPerimeter()/2;
        double a = vertices[0].distance(vertices[1]);
        double b = vertices[1].distance(vertices[2]);
        double c = vertices[2].distance(vertices[0]);
        return Math.sqrt( p * (p-a) * (p-b) * (p-c) );
    }


}

tp6/Turtle.java

0 → 100644
+67 −0
Original line number Diff line number Diff line
import java.awt.Color;
import static tp2.lib.Tools.sleep;
import tp2.lib.Painter;

public class Turtle {
Color penColor;
double angleDirection;
Point position;
boolean penIsDown;
Painter painter;

public Turtle(int width, int height) {
	penColor = null;
	angleDirection = 270;
	painter = new Painter(width, height);
	penIsDown = false;
	position = new Point(width/2, height/2);
	
}

public void moveForward(double distance) {
	sleep(500);
	double move = -(Math.sqrt(distance)-position.x);
	Point newPosition = position.translate(position.x + move, position.y );
	newPosition = newPosition.rotate(angleDirection);
	
	if (penIsDown){
		position.drawLine(newPosition, painter, penColor);
	}
	
	
	position = newPosition;
}

public void setColor(Color color) {
	penColor = color;
}

public void turnLeft(double angle) {
	 angleDirection = angleDirection - angle;
	 while (angleDirection < 0) {
		 angleDirection = 360 - angleDirection;
		 
	 }
}

public void turnRight(double angle) {
	angleDirection = angleDirection + angle;
	 while (angleDirection > 360) {
		 angleDirection = angleDirection - 360;
	 }
}

public void setPenDown() {
	penIsDown = true;

}

public void setPenUp() {
	penIsDown = false;

}




}