implement userTouch method

This commit is contained in:
Tikea TE 2025-05-22 22:58:40 +02:00
parent b702e97e27
commit 738e2d8170
1 changed files with 57 additions and 5 deletions

View File

@ -7,6 +7,14 @@ public class Board {
private int width;
private int height;
private ArrayList<Piece> pieces;
// new fields for userTouch
private int turnNumber = 0;
private boolean turnWhite = true;
private boolean hasSelection = false;
private int selectedX;
private int selectedY;
public Board(int width, int height) {
this.width = width;
@ -24,12 +32,11 @@ public class Board {
public int getTurnNumber() {
//TODO
return 0;
return turnNumber;
}
public boolean isTurnWhite() {
//TODO
return false;
return turnWhite;
}
public void setPiece(boolean isWhite, PieceType type, int x, int y) {
@ -114,8 +121,53 @@ public class Board {
}
public void userTouch(int x, int y) {
//TODO
// 1. find if u clicked on a piece at (x,y)
Piece clicked = null;
for (int i = 0; i < pieces.size(); i++) {
Piece p = pieces.get(i);
if (p.getX() == x && p.getY() == y) {
clicked = p;
break;
}
}
// 2. if nothing is selected
if (!hasSelection) {
if(clicked != null) {
hasSelection = true;
selectedX = x;
selectedY = y;
}
return;
}
// 3. if u click on the same cell twice, cancel selection
if (selectedX == x && selectedY == y) {
hasSelection = false;
return;
}
// 4. otherwise, move the previously selected to (x,y)
// a, remove any piece that was already on the cell
pieces.removeIf(p -> p.getX() == x && p.getY() == y);
// remove p if p.getX() == x && p.getY() == y
// b) locate the selected piece object
Piece toMove = null;
for (int i = 0; i < pieces.size(); i++) {
Piece p = pieces.get(i);
if (p.getX() == selectedX && p.getY() == selectedY) {
toMove = p;
break;
}
}
// c) re-place it at the new coordinates
if (toMove != null) {
pieces.remove(toMove);
// we need to remove it from its old place
pieces.add(new Piece(x, y, toMove.getType(),toMove.isWhite()));
} // change the x y but still the same color and type
// 5) Advance half-move counter and switch player
turnNumber++;
turnWhite = !turnWhite;
// 6) Clear the selection so you can pick again next turn
hasSelection = false;
}
public boolean isSelected(int x, int y) {