0
[Java] Generating Random Numbers in a Checkers Board [Java] ??
Good day to all members. There's this piece of java that I've been working on for the few days that'll generate VALID random moves. I used a 2D char array to store the data. The way I approached this problem was by generating TWO random numbers that are within the board's range, then call a function isValid() that takes two arguments and returns a boolean value when that move is VALID. This process is repeated in a while loop until isValid() returns a true value. Then call the function setPiece(). But I'm getting invalid moves. To all the gurus in the house, what's your insight.
3 ответов
+ 3
1) Show your code
2) I'd create an algorithm that only created random moves that were valid
If it is red's go, look for valid moves where they can take a white piece, or valid moves where they move without taking.
Note that the multi-take, where you can hop over and take many pieces, could be considered a single move! Or strictly it's a single turn with multiple moves!
Note, there are certain random configurations of pieces, that could never be created in a real game... so that's another concern.
+ 2
To find valid checker board moves straight away, you need something like this:
https://code.sololearn.com/cFWWv2lvE3Ih/#java
This code isn't complete, however, you can simply work out from here, what the valid moves are:
// Create a list of valid moves.
public void GetValidMoves()
{
for (int y = 0; y < 8; y ++)
{
for (int x = 0; x < 8; x ++)
{
if (checkersBoard[x][y] == WHITE_CHECKER)
{
// Work out possible move for this white piece.
// Regular white pieces can only move down the board (increasing y).
}
else if (checkersBoard[x][y] == BLACK_CHECKER)
{
// Work out possible move for this black piece.
// Regular black pieces can only move up the board (decreasing y).
}
else if
(
checkersBoard[x][y] == BLACK_QUEEN ||
checkersBoard[x][y] == WHITE_QUEEN
)
{
// Queens (whether black, or white), can move up or down
// the board.
}
}
}
}
+ 1
I'm not sure if my method works out any better (in terms of efficiency), as the board still needs to be scanned, and valid moves checked. I can't see a way of avoiding that, except caching a list of valid moves, and updating the cache after every new move, however that would probably end up doing the same amount of work eventually!