Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Chess;
- import Chess.ChessPieces.ChessPiece;
- import Chess.ChessPieces.Pawn;
- import Chess.ChessPieces.Rook;
- public class ChessModel implements Boardgame {
- private String currentMessage = "No message yet";
- private ChessPiece[][] board = new ChessPiece[8][8];
- private boolean white = true;
- private ChessPiece activePiece;
- ChessModel() {
- // Creates the board.
- char color = 'B';
- for (int y = 0; y < 8; y+=7) {
- board[y][0] = new Rook(y, 0, color);
- board[y][1] = new Pawn(y, 1, color);
- board[y][2] = new Pawn(y, 2, color);
- board[y][3] = new Pawn(y, 3, color);
- board[y][4] = new Pawn(y, 4, color);
- board[y][5] = new Pawn(y, 5, color);
- board[y][6] = new Pawn(y, 6, color);
- board[y][7] = new Rook(y, 7, color);
- for (int x = 0; x < 8; x++) {
- int yPos = y + (color == 'B' ? 1 : -1);
- board[yPos][x] = new Pawn(yPos, x, color); // Skapar bönderna
- }
- color = 'W';
- }
- }
- @Override
- public boolean move(int y, int x) {
- if (!(0 <= y && y < 8) || !(0 <= x && x < 8)) { // Checks if the chosen coord. is out of bounds.
- this.currentMessage = "Please choose a position within the board!";
- return false;
- }
- if (board[y][x] != null) { // Om rutan har en pjäs.
- if (board[y][x].getWhite() == white) { // Om det är ens egna färg.
- activePiece = board[y][x];
- return true;
- }
- else if (activePiece == null){ // Om det är första draget och motståndarens färg.
- this.currentMessage = "Välj en pjäs av din egna färg.";
- return false;
- }
- else { // Om det är andra draget - attackera motståndare.
- if (activePiece.checkMove(y, x, board)) { // Kollar om pjäsens drag är giltigt.
- makeMove(y, x);
- return true;
- }
- }
- }
- else if (activePiece == null) { // Om rutan är tom och det är första draget.
- this.currentMessage = "Välj en pjäs.";
- return false;
- }
- else { // Om rutan är tom och det är andra draget.
- if (activePiece.checkMove(y, x, board)) { // Kollar om pjäsens drag är giltigt.
- makeMove(y, x);
- return true;
- }
- }
- return false;
- }
- private void makeMove(int y, int x) { // Utför draget.
- board[activePiece.y][activePiece.x] = null; // Tömmer rutan som blev "dödad".
- board[y][x] = activePiece; // Flyttar pjäsen i matrisen.
- board[y][x].x = x; // Uppdaterar pjäsens x-kord.
- board[y][x].y = y; // Uppdaterar pjäsens y-kord.
- activePiece = null; // Markerar pjäsen som ej aktiv.
- white = !white; // Ändrar till motståndarens tur.
- }
- @Override
- public String getStatus(int i, int j) {
- if(board[i][j] == null) {
- return " ";
- }
- return board[i][j].toString();
- }
- @Override
- public String getMessage() {
- return this.currentMessage;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement