Files
chess/Board.java
2026-05-08 13:53:54 -05:00

114 lines
2.8 KiB
Java

import java.awt.*;
public class Board {
Piece[][] board;
public Board() {
board = new Piece[8][8];
for (int i = 0; i <= 7; i++) {
board[i][1] = new Pawn(i, 1, "Black");
board[i][6] = new Pawn(i, 6, "White");
}
for (int i = 0; i <= 7; i += 7) {
String color = i == 0 ? "Black" : "White";
board[0][i] = new Rook(0, i, color);
board[7][i] = new Rook(7, i, color);
board[1][i] = new Knight(1, i, color);
board[6][i] = new Knight(6, i, color);
board[2][i] = new Bishop(2, i, color);
board[5][i] = new Bishop(5, i, color);
board[4][i] = new King(4, i, color);
board[3][i] = new Queen(3, i, color);
}
}
public Board(boolean isCopy) {
board = new Piece[8][8];
}
public void capture(Piece capturing, Piece captured) {
board[capturing.pos.x][capturing.pos.y] = null;
board[captured.pos.x][captured.pos.y] = capturing;
capturing.pos.x = captured.pos.x;
capturing.pos.y = captured.pos.y;
}
public void move(Piece p, Position posi) {
board[p.pos.x][p.pos.y] = null;
board[posi.x][posi.y] = p;
p.pos = posi;
if (p instanceof Pawn) {
((Pawn) p).hasMoved = true;
}
if (p instanceof King) {
((King) p).hasMoved = true;
}
if (p instanceof Rook) {
((Rook) p).hasMoved = true;
}
}
public void castle(King king, boolean kingSide) {
int row = king.pos.y;
if (kingSide) {
move(king, new Position(6, row));
move(board[7][row], new Position(5, row));
} else {
move(king, new Position(2, row));
move(board[0][row], new Position(3, row));
}
}
public void draw(Graphics g) {
for (Piece[] row : board) {
for (Piece p : row) {
if (p != null) p.draw(g);
}
}
}
public static boolean inBounds(Position pos) {
return (pos.x >= 0 && pos.x <= 7) && (pos.y >= 0 && pos.y <= 7);
}
public boolean isOpen(Position pos) {
return this.getPiece(pos) == null;
}
public Piece getPiece(Position pos) {
if (inBounds(pos)) {
return this.board[pos.x][pos.y];
}
return null;
}
public Piece getPiece(int x, int y) {
if (inBounds(new Position(x, y))) {
return this.board[x][y];
}
return null;
}
public void setPiece(int x, int y, Piece p) {
this.board[x][y] = p;
}
public void setPiece(Position pos, Piece p) {
this.board[pos.x][pos.y] = p;
}
public static Board copy(Board b) {
Board newBoard = new Board();
for (int i = 0; i <= 7; i++) {
for (int j = 0; j <= 7; j++) {
Piece p = b.getPiece(i, j);
if (p == null) continue;
newBoard.board[i][j] = p.copy();
}
}
return newBoard;
}
}