Drawing of board on canvas is now done from bitboards rather than translating.

This commit is contained in:
2025-12-05 01:20:01 +01:00
parent b3a97a8978
commit 38de4f2156
4 changed files with 22 additions and 51 deletions

View File

@@ -101,30 +101,14 @@ public abstract class BitGameCanvas<T extends BitboardGame<T>> implements GameCa
render();
}
protected int[] translateLegalMoves(long legalMoves){
int[] output = new int[Long.bitCount(legalMoves)];
int j = 0;
for(int i = 0; i < 64; i++){
if ((legalMoves & (1L << i)) != 0){
output[j] = i;
j++;
}
}
return output;
}
public void loopOverBoard(long bb, Consumer<Integer> onCell){
while (bb != 0) {
int idx = Long.numberOfTrailingZeros(bb); // index of least-significant 1-bit
onCell.accept(idx);
protected static int[] translateBoard(long[] playerBitboard){
int[] output = new int[64];
Arrays.fill(output, -1);
for(int i = 0; i < playerBitboard.length; i++){
for (int j = 0; j < 64; j++){
if ((playerBitboard[i] & (1L << j)) != 0){
output[j] = i;
bb &= bb - 1; // clear LSB 1-bit
}
}
}
return output;
}
private void render() {
graphics.setFill(backgroundColor);

View File

@@ -35,13 +35,8 @@ public class ReversiBitCanvas extends BitGameCanvas<BitboardReversi>{
@Override
public void redraw(BitboardReversi gameCopy) {
clearAll();
int[] board = translateBoard(gameCopy.getBoard());
for (int i = 0; i < board.length; i++) {
if (board[i] == 0) {
drawDot(Color.WHITE, i);
} else if (board[i] == 1) {
drawDot(Color.BLACK, i);
}
}
long[] board = gameCopy.getBoard();
loopOverBoard(board[0], (i) -> drawDot(Color.WHITE, i));
loopOverBoard(board[1], (i) -> drawDot(Color.BLACK, i));
}
}

View File

@@ -5,6 +5,7 @@ import org.toop.app.App;
import org.toop.game.games.tictactoe.BitboardTicTacToe;
import java.util.Arrays;
import java.util.function.Consumer;
public class TicTacToeBitCanvas extends BitGameCanvas<BitboardTicTacToe>{
public TicTacToeBitCanvas() {
@@ -23,26 +24,15 @@ public class TicTacToeBitCanvas extends BitGameCanvas<BitboardTicTacToe>{
@Override
public void redraw(BitboardTicTacToe gameCopy) {
clearAll();
drawMoves(translateBoard(gameCopy.getBoard()));
drawMoves(gameCopy.getBoard());
}
private void drawMoves(int[] gameBoard){
// Draw each square
for (int i = 0; i < 9; i++){
// If square isn't empty, draw player move
if (gameBoard[i] != -1){
drawPlayerMove(gameBoard[i], i);
}
}
private void drawMoves(long[] gameBoard){
loopOverBoard(gameBoard[0], (i) -> drawX(Color.RED, i));
loopOverBoard(gameBoard[1], (i) -> drawO(Color.BLUE, i));
}
public void drawPlayerMove(int player, int move) {
switch (player) {
case 0 -> drawX(Color.RED, move);
case 1 -> drawO(Color.BLUE, move);
default -> super.drawPlayerMove(player, move);
}
}
public void drawX(Color color, int cell) {
graphics.setStroke(color);

View File

@@ -75,6 +75,8 @@ public abstract class BitboardGame<T extends BitboardGame<T>> implements TurnBas
return players[getCurrentPlayerIndex()];
}
@Override
public long[] getBoard() {return this.playerBitboard;}